How to apply a force in the facing direction?

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

I am making a game where the player is in control of a rocketship. The rocket is a RigidBody2D node that I apply torque and a central impulse to in order to move. However, the thrust vector should align with the rocket engine (instead of just propelling the ship directly upward) so that you can steer the rocket. Basically, how can I make the impulse apply in the direction the rocket is facing?
Thanks in advance! :slight_smile:

:bust_in_silhouette: Reply From: jgodfrey

The apply_central_impulse() method takes a vector that’s used as the direction of the applied force. So, really, you just want that vector to represent the direction your ship is facing. You can get that from the ship’s rotation property.

So, assuming your ship is facing to the right at it’s zero orientation, something like this should work (wired to a button in this case):

func _on_ButtonForward_pressed():
    var impulse_strength = 100
	var angle = $RigidBody2D.rotation
	$RigidBody2D.apply_central_impulse(Vector2(cos(angle), sin(angle)) * impuse_strength)

Just season to taste…

Holy cow this worked perfectly, thank you so much! I had some janky crap with like 3 different constants I was trying to tweak but it never worked. I’m taking trig this week so hopefully this method will make sense to me soon. For now, it works great and that’s what matters :slight_smile:

redstonecreeper8 | 2020-11-18 15:08

1 Like