Skip to content
Advertisement

(Three.js) How to slowly rotate a mesh until it reaches a specific value

I’ve just gotten into Three.JS, and I’ve ran into an issue. I’m trying to make a car, that is drivable using the Arrow Keys. So far, I’ve gotten it to move forwards, and backwards, and the wheels turn when you press Up (Forwards) and Down (Backwards). So, logically, the next step would be turning. However, that’s where I run I to my issue.

I can’t figure out how to make it so that when I press the left or right arrow keys, it will slowly, gradually increase the rotation of the wheels, until they reach a certain value, say, 45 for left, and -45 for right.

I have a cube, stretched out to the shape of a mostly flat rectangle, called chassis. I have four wheels, Wheel_FL, FR, RL, and RR. F meaning Front, First R meaning rear, L meaning Left, Second R meaning right. Both Wheel_FL and Wheel_FR have a group as their parent, which I will use to rotate them left or right, they act as a pivot. I cannot figure out how to do this, I’ve tried looking for an answer everywhere for the past couple of days, to no avail. If anyone has any ideas, please, let me know! And if anyone needs any more information, please, let me know!

I’m also looking for a way to, then, once this steering issue is fixed, to rotate the chassis itself in a way that is realistic to how a car would turn.

Thanks!

If anyone needs an example, I have one here.

Advertisement

Answer

I can help you with the first part of the question:

Let’s name the variables: Wheel_FL, Wheel_FR, Group_FL, Group_FR;. Each wheel is nested inside its respective group with Group_FL.add(Wheel_FL);

So to spin the wheels, you’d probably do Wheel_FL.rotation.x += spinAngle; or maybe rotation.z based on the orientation of your asset. Now to steer left/right, you’d want to rotate the container Group so it doesn’t interfere with the spinning angle: Group_FL.rotation.y = steerAngle;

To animate, or tween this steering angle, you could use the MathUtils.lerp() function (lerp stands for Linear-interpolation), which takes a variable and eases it towards its target.

JavaScript

I’ve created a working demo for you below. Use w-a-s-d keys to steer, accelerate, and decelerate:

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement