How do I rotate a RigidBody with mouse movement?

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

As far as I know:

  • I need to use the _integrate_forces() method to rotate a RigidBody without jittering

  • I need to use the _input() method and cast to InputEventMouseMotion to get mouse movement.

So, how can I do both of these things at once? I tried having _input place the rotation amounts in a temporary variable which is later accessed and reset by _integrate_forces(), but that results in laggy mouse movement.

Does your whole game lag or just the mouse?
If the whole games lag, maybe only read the mouse every 1/60 of a second or 1/30.

coffeeDragon | 2018-07-25 09:14

It’s just the mouse. I also have the arrow keys set up as rotation and it’s smooth as butter.

Aaron Franke | 2018-07-25 19:12

1 Like
:bust_in_silhouette: Reply From: anonymous

Alright, so I was able to figure it out. You do indeed have to use both methods, and transfer information between them using a temporary variable (such as Vector2).

public override void _Input(InputEvent inputEvent)
    InputEventMouseMotion motion = inputEvent as InputEventMouseMotion;
    if (motion != null) {
        mouseSpeed.y += motion.Relative.y;
        mouseSpeed.x += motion.Relative.x;

private Vector2 mouseSpeed;
public override void _IntegrateForces(PhysicsDirectBodyState state)
    Vector3 angularVelocity = Vector3.Zero;      
    Transform transform = GetTransform();
    angularVelocity -= mouseSpeed.x * 0.125f * transform.basis.y;
    angularVelocity -= mouseSpeed.y * 0.125f * transform.basis.x;
    mouseSpeed = Vector2.Zero;
    state.AngularVelocity = angularVelocity;

This code is designed for RigidBody nodes in any orientation.

Also, ensure that the “Can Sleep” property of the RigidBody node is Disabled, otherwise the _IntegrateForces() method will not be called!

Bro!! I had a similar problem, I tryed to convert your code to gdscript but i had lot of errors …could you please rewrite the code in gdsciprt!?

Thanks in advance

u_nes | 2020-05-16 00:45

Can we make it in GDscript? Thanks

Okan Ozdemir | 2020-06-21 10:46