Pointing a RigidBody2D towards a point using torque.

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

I’m trying to create a top-down space shooter like Asteroids, where all of the ships are RigidBodies. I want to make it so that the enemies always turn to face the player, which is done through the below code:

func _integrate_forces(state):
    [...]
    var player_vector = (player.position - position).normalized()
    set_applied_torque((rad2deg(player_vector.angle()) - rotation_degrees + 90) * spin_speed)

For the most part, this works fine. Unless the player is to the lower-left of the enemy, in which case the enemy begins to spin uncontrollably,

Spinning

First of all, is this the best way to implement this sort of behavior? If so, what am I doing wrong? If not, what is the best way to do this?

I’ve found that a simple way to do it is to replace the last line of code with rotation = player_vector.angle() + PI / 2, but I’d prefer a solution that actually applies torque rather than instantly changing the rotation, as I could see such rapid movement causing problems.

Turnovus | 2019-06-24 17:31