Help with making FISH ai?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By InstelGames
:warning: Old Version Published before Godot 3 was released.

Hey! does anyone have any suggestions where to start?

My goal is to make a fish in an area, and make them move around and not leave the area while bobbing up/down and facing left (when moving left) etc.

As well as swim away when a player comes near?

I tried making a pos2d switch to a random location every second in an area and have the fish navigate to that area, but how would I make it face left when moving left or right when moving right? or is this a bad approach?

Thanks.

:bust_in_silhouette: Reply From: ADcomp

Hi ,

Sometimes ago, I tested something with particles acting “like” a fish … maybe it can help ?
I use trigonometry sine wave to set the speed and random rotation at random time …

https://www.youtube.com/watch?v=NizaGYAndXY

extends Particles2D

var min_speed = 32
var acc = randf() * 360
var speed = 0
var vel = Vector2()
var timer = 0
var max_timer = .2
var rot = 0
var world_size
var bounce = 1
var bounce_damping = 0.5

func _ready():
	set_process(true)

func init(rec):
	world_size = rec
	set_pos(Vector2(randf() * rec.x, randf() * rec.y))
	set_color(Color(.5 + randf()+.5, .5 + randf()*.5, .5 + randf()*.5, 1))
	vel = Vector2(1, 0).rotated(randf()*360)
	
func _process(delta):
	timer += delta * randf()
	if timer > max_timer:
		timer = 0
		vel = vel.rotated(-.5 + randf())

	acc += delta * randf() * .1
	if acc >= 360: acc = 0

	if speed < 2*min_speed: speed += delta

	move(delta)

func move(delta):
	var pos = get_pos()
	
	if pos.x < 0:
		pos.x = 2
		vel = Vector2(-vel.x, vel.y)
		speed *= bounce_damping
		acc = 0
	elif pos.x > world_size.x:
		pos.x = world_size.x - bounce
		vel = Vector2(-vel.x, vel.y)
		speed *= bounce_damping
		acc = 0

	if pos.y < 1:
		pos.y = 2
		vel = Vector2(vel.x, -vel.y)
		speed *= bounce_damping
		acc = 0
	elif pos.y > world_size.y:
		pos.y = world_size.y - bounce
		vel = Vector2(vel.x, -vel.y)
		speed *= bounce_damping
		acc = 0

	speed = min_speed + (min_speed * 0.73 * sin(acc * 4.6)) + (min_speed/4 * sin(acc * 0.16)) + (min_speed/2 * sin(acc * 3.14))
	pos += speed * vel * delta
	set_pos(pos)