Make dynamic rigidbody lookAt mouse pointer

Hello all,

I am trying to rotate my rigid body so that it looks at the mouse pointer while making the rotation physically correct(synced with the physics engine), the following methods wont work on the dynamic rigid body for rotation:
setRotation()
setEulerAngles()
setLocalEulerAngles()
lookAt()

while only applyTorque works.
So the main question is how to determine the torque which would make the entity look at the mouse pointer, I have already calculated the ‘from’ and the ‘to’ vector. ‘to’ vector being a directional vector to the mouse pointer.
Any sample project/code would be helpful.

Thanks.

Hi @Geniteam,

If you aren’t doing this per frame and only once in a while you can use the teleport method which accepts a position and optionally rotation values:

https://developer.playcanvas.com/en/api/pc.RigidBodyComponent.html#teleport

Though this method comes with a performance hit and shouldn’t be used often. The proper way would be to calculate the required torque, as you say, but that isn’t an easy problem to solve.

Hello @Leonidas

My game involves changing a lot of position and rotation values.

Here it is : https://playcanv.as/b/Q0Wpfqll/

Currently the pusher object can be moved using mouse down input and it is kinematic while the other objects are dynamic, the movement of the pusher object is done manually using set position and rotation through lookAt. The main issue is that the collision are not good if i do some sudden movements i.e if I move my pointer down while the pusher object is looking up then it rotates suddenly and apply a huge amount of force(since it is kinematic) on the dynamic objects(boxes). I have already clamped the speed of the pusher object using lerp but how can I remove sudden rotations which happen due to lookAt.

Thanks.

Nice game! Actually I find that it behaves pretty much correctly. Sudden changes in velocity (linear or angular) can produce unexpected forces but that isn’t so much a bug but mostly how the physics simulation works.

So I think there might be a simple solution here, you will have to clamp the rotation much like you clamp the speed. Instead of using lookAt you should calculate the angle between the object’s forward vector and the mouse point yourself using some math (do a search for dot product). That way you will have a current angle and a target angle and you can lerp in a slower pace to avoid sudden changes.

1 Like