How do you make an enemy follow you in a curve?
Asked Answered
L

2

0

I feel like I am being really stupid here, but is there an easy way to have an enemy follow you in a curved motion by adjusting the steering force?

Here is my basic code to have a sprite follow the mouse around the map, but as expected it always follows it in a strait line. How would you go about adjusting the steering force to have the character follow the mouse in a curved motion, in particular when there is a change of direction, so the change of direction is more natural and less snappy.

func _physics_process(delta):
	
	var desired_velocity = (get_global_mouse_position() - global_position).normalized() * MAX_SPEED
	var steering_force = desired_velocity - velocity
		
	velocity = (velocity + steering_force).limit_length(MAX_SPEED)
	
	position += velocity * delta

Here is an example drawing. If I were to drag my mouse along the strait line, how could I get the character to follow me in a way more similar to the curved line. (Apologies for my awful art)

Legibility answered 24/4, 2023 at 18:35 Comment(0)
M
0

Legibility
In your code:
steering_force = desired_velocity - velocity
velocity = velocity + steering_force

from that it follows that:
velocity = velocity + desired_velocity - velocity

which shortens down to
velocity = desired_velocity

So your code is basically assigning desired velocity to velocity each frame. If you want to use this type of steering (which is not ideal), you should scale down the steering vector.

Milanmilanese answered 24/4, 2023 at 18:42 Comment(0)
L
0

Milanmilanese

Ye I realised that as well, after thinking about it for a bit.

I actually found something vaguely similar to this in a kidscancode video on youtube for context driven steering and between that and your answer it makes sense re scaling it down each frame.

func _physics_process(delta):
	
	
	look_at(get_global_mouse_position())
	
	var chosen_dir = (get_global_mouse_position() - global_position).normalized()
	var desired_velocity = chosen_dir * MAX_SPEED
	velocity = velocity.lerp(desired_velocity, 0.075)
	
#	move_and_collide(velocity * delta)
	move_and_slide()

This works really well in the end and is very close to what I'd expect (and obviously loads of room for tweaking/improving) as a basic concept

Legibility answered 24/4, 2023 at 20:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.