Rotating to Slope

Hello, I’ve been running into a bit of a problem with getting my character to rotate to the slope’s normal. I have a state machine set up to determine which direction to rotate the character and set his animation. Now I’m trying to get the character to flatten with the slope instead of appear to hang off of it. Here is the relevant code.

    // Setting up some values
    private Quaternion beforeMovement;
    private Quaternion target;

    private RaycastHit hit;
    private Ray ray;
    private LayerMask layer;

	public void DetermineCurrentMoveDirection() {
        // The code to determine ...
        // Cast the ray
        ray = new Ray(transform.position, Vector3.down);
        beforeMovement = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z);
        }

    // Everything works fine until we step on a "terrain" layered object.
    void Running() {
        anim.CrossFade("Walking");
        RaycastHit hitInfo;

        if (Physics.Raycast(ray, out hitInfo, layer)) {
            Debug.Log(hitInfo.transform.gameObject.layer == layer);
            if (hitInfo.transform.gameObject.layer == layer) {
                Debug.Log(hitInfo.normal.z * 90);
                Debug.Log(transform.rotation.eulerAngles.x);
                target = Quaternion.Euler((transform.rotation.eulerAngles.x + (hitInfo.normal.z * 90.0f)), transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z);
            } else {
                target = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z);
            }
        }

        transform.rotation = Quaternion.Slerp(beforeMovement, target, rotateSpeed * Time.deltaTime);
    }

At the line where we are setting the target if we are on a layered object the player rotates to 270 degrees no matter the angle. I’m not sure why.

Thanks for your help.

I would recommend to use look rotation. You need to make your vehicle’s forward axis perpendicular to terrain’s normal vector. Something like:

    Vector3 hitToVehicle = hitInfo.point - transform.position;
    Vector3 projectionVector = Vector3.Project(hitToVehicle, hitInfo.normal);
    Vector3 directionVector = hitToVehicle - projectionVector;
    target = Quaternion.LookRotation(directionVector,hitInfo.normal);

Hope that helps.