I have a Bike that travels down a race track, the track is one long mesh. I have a rectangular object, let’s call him Ben, that sits under the bike that has the below script on it, the bike will eventually Lerp it’s Y rotation to Ben’s Y rotation.
Ben casts a red ray straight down, obtains the normal vector of the object below, and matches it’s rotation.
It’s working fine for the X and Z values, but not for Y, which is the one I need. Ben also casts a green ray sideways to detect the edge of the road.
How do I rotate Ben to have the same Y rotation as the normal directly below him?
Or rather, how do I make Ben face down the track? I want his Y rotation perfectly aligned with the white lines on the road as it passes over them.
function Update ()
{
OrientThisToObjectBelow(transform.TransformDirection(-Vector3.up));
}
function OrientThisToObjectBelow (dir : Vector3)
{
if (Physics.Raycast (transform.position, dir, hit, 150, LayerMask))
{
Debug.DrawLine(transform.position, hit.point, Color.red);
transform.up = hit.normal;
}
}
Below the bike is the road, which is one long mesh made up of several faces, I’ve used the EasyRoads 3d package to generate the road.
I want to cast a ray downwards from the bike, hit a face on the road mesh, and use that face’s normal to align my bike with it on the bikes Y axis. So that the bike is always facing in the direction of face’s Z axis.
So that if I set the bike to always drive forward, it will follow the road no matter how the road bends or turns, because the bike is always aligned with whatever face it is passing over on the road.
The normal isn’t going to “spin” when you rotate the plane on the up axis. You’ll have to align the bike with something like the forward vector of the plane itself.
Ah, yep this was my mistake, for some reason I thought a normal had an X and Z direction. Thank you everyone for your help anyway it’s much appreciated!