In a 2D game, how do i aim towards the mouse's moving direction instead of aiming towards the cursor?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By fmajor


I am very new to godot and have managed to make a 2D object aim towards my cursor. But i have no idea how to make it so that my object aims towards any mouse movements. I thought of constantly bringing the mouse back towards the object so that every mouse move starts from the origin, but this didn’t work for me. Help is greatly appreciated.

What exactly does happen when you move mouse back to the object? Does the aim change at all?

jahu00 | 2023-02-07 22:31

It makes the aim very stuttery. Though yesterday i managed to make a step in the right direction by making the object look at the mouse movement, but this is still far from perfect as its very stuttery and inaccurate.

fmajor | 2023-02-08 07:33

:bust_in_silhouette: Reply From: jahu00

If I understand you correctly, you want the mouse to work like a virtual joystick (one that goes back to center the moment you stop moving the mouse) for aiming your object.

Each process, check for mouse position and compare it to where it’s supposed to be (it could be your object position like you mentioned). If mouse is at the the target location, do nothing. If it’s elsewhere, subtract the target position from your current mouse position and move the mouse back to the target position. You should be able to extract your aim angle from mouse movement vector that you just computed using mouseMovementVector.angle(). and apply this to your object’s rotation.

If you intend to move your object around, it might be better to use the center of screen as the return position for mouse (and probably hide the cursor). Otherwise, your object will keep aiming backwards when you move it.

If you want your aiming to be less erratic, you could introduce a little inertia to your aiming. Rather than use the angle you got from mouse movement directly, compute an angle based on both the new and the old value. Something like objectAngle = oldAngle * 0.5 + newAngle * 0.5. You just need to make sure that the weights sum to 1.