npc motorbike rotation

Hey guys

I have an npc motorbike consisting out of 2 wheel colliders and rigidbody. I want the bike to drive on it’s own from waypoint to waypoint and all the script to apply wheel torque etc is working fine. I want to rotate the rigidbody towards the next waypoint, but the catch is that the z-axis must stay at zero so that the bike does not fall over. So after spending a lot of time searching for a solution I compiled the following code and cant see why it is not working. I have tried numersour variations on this code with mixed results.

Vector3 targetDir = target.transform.position - transform.position;
        Vector3 forward = transform.forward;
        Vector3 localTarget = transform.InverseTransformPoint(target.transform.position);
        float angle = Mathf.Atan2(localTarget.x, localTarget.z) * Mathf.Rad2Deg;
        Vector3 eulerAngleVelocity = new Vector3(0, angle, 0);
        Quaternion deltaRotation = Quaternion.Euler(eulerAngleVelocity * Time.deltaTime);

        //now set z to 0 so that the bike does not fall over
        deltaRotation.z = 0;
        rigidbody.MoveRotation(rigidbody.rotation * deltaRotation);

When I take the line out that is supposed to keep the bike upright, the bike falls over.

so I tried this

        Vector3 target_pos = target.transform.position - transform.position;
        Quaternion rotation = Quaternion.LookRotation(target_pos);
        rotation.z = 0;
        rigidbody.MoveRotation(rotation);

and the results are better, except that the local x of the rigidbody seems to vary between 0 and the rigidbody’s x

Any advice welcome, please and thanks

have to bump, sorry.

Hey guys

Ok, I think I am colse now, here is my new approach

Vector3 target_pos = target.transform.position - transform.position;
float angle = Mathf.Atan2(target_pos.x, target_pos.z) * Mathf.Rad2Deg;

transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(transform.rotation.eulerAngles.x, angle, 0), Time.deltaTime * 25);

This still gives me a slight jitter on the forward rotation of the bike, but seems to be much more stable