Hey everyone, so I’m trying to code a feature which would allow the the bodies in the “Enemy” group to be applied a one time force in the direction of the mouse cursor.
Right now this is what I have but when i run it, whenever it enters the area2d, the enemy body kind of looks like it just teleports or moves very fast the same distance every time the function is called. I tried implementing the cursor position here but it was saying I couldn’t use a Vector2 there so I was trying to see how I could change it but I got stuck, -
pass # Replace with function body.
For context, this script is attached to a node within the same folder as where the player scripts are and the enemy scripts are within another folder.
the issue was this?
then just slow down the velocity ?
It looks like you are giving the enemy the same velocity each time, so it’s expected that it moves in the same direction each time.
To send the enemy towards the mouse, you can try something like:
var base_impulse := Vector2(2000, 2000)
var mouse_pos : Vector2 = get_global_mouse_position()
var enemy_pos : Vector2 = body.global_position
var dir : Vector2 = enemy_pos.direction_to(mouse_pos)
var impulse : Vector2 = base_impulse * dir
I used your original value for
base_impulse, but if it’s moving so fast it looks like it’s teleporting, you probably want a lower value. I’m also not sure what type of physics body your enemy is, so I’m just using your original set_velocity() command. I assume if it’s a CharacterBody2D that you’re handling the actual movement elsewhere.
This is better but it still looks like the enemy is just teleported a shorter distance than before, it is still a very quick movement, I thought adding velocity would result in the body accelerating then decelerating as it loses velocity
This seems very good but I encounter an error which was my main problem I forgot to mention in the original post, for some reason it won’t let me use functions from CharacterBody2D even though the enemy is that. I can’t find out whats going on yet.
Hey thanks I found the solution thanks to your code. I just had to change the set_velocity to velocity, it works awesome.