Setting rotation of game object relative to ground does not work

I have set up a humanoid moving around the game world. On right click its move point will change, will start walking towards it and it should rotate towards its target. But I also wanted to take into account terrain curvature, so I rotate the object in x and z axis based on terrain normal and rotate the object on y axis based on the target.

protected void Move()
    {
        Vector3 heading = new Vector3();
        heading = (movePoint - this.transform.position);

        Ray ray = new Ray(transform.TransformPoint(GetComponent<BoxCollider>().center), -transform.up);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, GetComponent<BoxCollider>().size.y, terrainLayerMask))
        {
            float rotStep = rotSpeed * Time.deltaTime;
            Vector3 objectForward = transform.TransformDirection(Vector3.forward);
            Vector3 newDir = Vector3.RotateTowards(objectForward, heading, rotStep, 0f);
            transform.rotation = Quaternion.Euler (Quaternion.LookRotation(objectForward, hit.normal).eulerAngles.x, Quaternion.LookRotation(newDir, hit.normal).eulerAngles.y, Quaternion.LookRotation(objectForward, hit.normal).eulerAngles.z);
        }
        float moveStep = moveSpeed * Time.deltaTime;
        Vector3 tempPos = Vector3.MoveTowards(transform.position, movePoint, moveStep);
        transform.position = new Vector3(tempPos.x, GetTerrainHeight(), tempPos.z);
    }

The code that calculates the rotation and sets it is inside the if (Physics.Raycast) part.

First I assign object forward transform in a variable “objectForward”.

Then I calculate rotation towards the target and store it in “newDir”.

After that I set objects rotation. The problem is, the rotation around the x axis is not setting, it stays on 0 all the time. The y and z axis are set up properly. Y rotation is based on target position, z rotation is based on terrain normal and x is also based on terrain normal but it’s not working even though I use the same function for both of those variables.

I’ve suspected that i’ve used a wrong function for calculating x rotation so I’ve used “Debug.Log(Quaternion.LookRotation(objectForward, hit.normal).eulerAngles.x)” to check if it actually has a value and it does so I have no idea why it’s not working properly.

This is not a complete answer, but one thing that helps me out with rotations and transforms is their right, up, and forward properties. You can let Unity handle the rotation madness internally, and use something like:

transform.up = hit.normal;

These will be in world space by the way. I hope this helps :slight_smile: