Fishing Game fish code

godot 4

I am working on a fishing mini game and am working on a fish script to make it swim randomly around and it works but the fish is a bit jerky and doesnt move around all that much was wondering if anyone had a better idea on how to do this thank.
func swim():

if moved == false:
	direct = randi_range(1, 4)
	if direct == 1:
			global_position.y -= 6
			move_and_slide()
			%fishSprite.play("swim")


	elif direct == 2:
			global_position.x += 6
			move_and_slide()
			%fishSprite.play("swim")
			
	elif direct == 3:
			global_position.y += 6
			move_and_slide()
			%fishSprite.play("swim")
			
	elif direct == 4:
			global_position.x -= 6
			move_and_slide()
			%fishSprite.play("swim")

func _process(delta):

if swimTime == false && timerGoing == false:
	%Timer.start()
	timerGoing = true 

if swimTime == true:
	swim()
	swimTime = false

Rather than set the direction and change it when the timer expires, a good and fairly simple way to code this behavior would be to first pick a random position out of everywhere it could move. Then, every frame, move the fish towards that position a bit. When the fish is close enough to that position, pick a new position.

The way you’ve currently written it, there’s an equal chance of moving up, down, left, or right, so the fish is likely to go back and forth a lot, resulting in that behavior you see.

It’s going to require some tweaking, and there’s a lot more you can do in terms of customizing, but this is the general idea that you should go for:

var _target:Vector2
var _direction:Vector2

func _has_reached_target():
    const MIN_DISTANCE = 8.0 # Change this to suit your needs
    var d = _target.distance_to(position)
    return d < MIN_DISTANCE

func _pick_new_target():
    _target.x = randf_range(-100, 100) # Adjust these to your liking
    _target.y = randf_range(-100, 100)

    _direction = position.direction_to(_target)

func _process(delta):
    const speed = 16.0

    if _has_reached_target():
      _pick_new_target()

    var distance = speed * delta

    position += _direction * distance

As a next step, I suggest reading up on vector math and how it works into game coding. Vector math — Godot Engine (stable) documentation in English

Once this code is working, it will be easier to add more behaviors to the fish (maybe they could spend time not moving sometimes) by altering the check in _process.

Feel free to ask if you have any questions about this!

1 Like

Thats a really good idea thanks for the help

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.