Hello!
I’ve been breaking my brain over this all morning.
In Unity, I have a line of code that turns a car’s world velocity into a local velocity from the perspective of the wheel:
Vector3 localVelocity = transform.InverseTransformDirection( carBody.rb.velocity );
The entity hierarchy is pretty simple, and I’ve recreated it in PlayCanvas:
- carBody
– wheel (script is here)
– wheel
– wheel
– wheel
So I’ve been looking through the forums and the API for hours trying to figure this out myself, and so far I’ve got the following PlayCanvas code:
// Create a 3-dimensional vector
var globalVelocity = this.carBody.rigidbody.linearVelocity;
// Create a 4x4 rotation matrix
var localTransform = new pc.Mat4();
localTransform.clone( this.entity.getLocalTransform() );
localTransform.invert();
// Get Local Velocity
var localVelocity = localTransform.transformVector(globalVelocity);
I’ve never had to work with transform matrices before, so I’m a bit confused how to use them, but to me this is the most sensible code I’ve been able to come up with.
You get the local transform matrix of the wheel, you invert it, and then you transform (?) the global velocity based on that matrix to get the local velocity?
Anyway, It doesn’t do anything:
localVelocity always remains exactly the same as globalVelocity, even though in the screenshot above the carBody is diagonally zooming through the world while spinning around. localVelocity should constantly be changing based on the angle of the carBody relative to the world space. Instead, nothing.
I’ve tried switching stuff around, using getWorldTransform() instead of local, commenting out invert(), all sorts of things, but it does nothing. I’ve hit a wall.
Does anyone know what I’m doing wrong?
Thanks!
Here’s my project: PlayCanvas 3D HTML5 Game Engine
Scene is “Car”
The Car can be controlled with arrow keys, and shows a blue line denoting localVelocity.z and a red line denoting localVelocity.x
If you press F12 and go to console you can also see log lines spitting out global velocity and local velocity