Rotating an entity based on the roll of another object

Good morning everyone,

I’m currently working on a little demo game along the lines of Mario Party’s Bumper Balls. I have my controls of the rolling of the ball and partnering it with the entity that will live on top of the ball as it rolls, but I’ve run into a bit of a wall.

The idea will be that the object that is paired with the ball will rotate to always look in the direction the ball is rolling (rotating on the Y axis), but I’m getting stuck in how to get the direction the ball is rolling and then subsequently rotating the object above.

I don’t know why I’m having so much trouble this morning, but any ideas will be very helpful!

Edit: As I fiddle with this, I’m guessing my question is how would I go about taking my linear velocity and converting it to a direction to face.

If I understand correctly and you only need the direction the ball is moving to, then by normalizing the linear velocity you will get it:

const direction = this.entity.rigidbody.linearVelocity.normalize();
1 Like

An easy way to have an entity look at that direction, is to add that direction to ppthe world position of the ball, and call lookAt to the resulting vector.

That will be a point a tad forward to the direction the ball is moving.

1 Like

@Leonidas !!!

Thank you so much for your answer. The normalize function was just what I was looking for! With that small bit I was able to pretty easily get my angle of rotation like this:

ParentToBall.prototype.postUpdate = function(dt) {
    this.entity.setLocalPosition(this.ball.getLocalPosition().x, this.ball.getLocalPosition().y + 1, this.ball.getLocalPosition().z);
    
    if(Math.abs(this.ball.rigidbody.linearVelocity.x) > 0.01 || Math.abs(this.ball.rigidbody.linearVelocity.z) > 0.01) {
        
        var angle = Math.acos(this.ball.rigidbody.linearVelocity.normalize().dot(pc.Vec3.BACK)) * pc.math.RAD_TO_DEG;
        console.log(angle);
        if(this.ball.rigidbody.linearVelocity.x < 0.01) {
            angle *= -1;
        }
        
        this.entity.setEulerAngles(0, angle, 0);
    }
    
};

Now I’m just going to smooth it out by lerping the movement, and I think all will be well! Thank you again very much!

1 Like