Make Gameobject Stand On Surface Facing Certain Direction
        Posted  
        
            by 
                Julian
            
        on Game Development
        
        See other posts from Game Development
        
            or by Julian
        
        
        
        Published on 2013-11-10T18:57:29Z
        Indexed on 
            2013/11/10
            22:25 UTC
        
        
        Read the original article
        Hit count: 310
        
I want to make a biped character stand on any surface I click on.
Surfaces have up vectors of any of positive or negative X,Y,Z. So imagine a cube with each face being a gameobject whose up vector pointing directly away from the cube.
If my character is facing "forward" and I click on a surface which is to the left or right of me ( left or right walls), I want my character to now be standing on that surface but still be facing in the direction he initially was. If I click on a wall which is in the forward path of my character i want him to now be standing on that surface and his forward to now be what was once "up" relative to my character. Here is the code I am working with now.
void Update()
{
    if (Input.GetMouseButtonUp (0)) {
        RaycastHit hit;
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit)) {
            Vector3 upVectBefore = transform.up;
            Vector3 forwardVectBefore = transform.forward;
            Quaternion rotationVectBefore = transform.rotation;
            Vector3 hitPosition = hit.transform.position;
            transform.position = hitPosition;
            float lookDifference = Vector3.Distance(hit.transform.up, forwardVectBefore);
            if(Vector3.Distance(hit.transform.up, upVectBefore) < .23) //Same normal
            {
                transform.rotation = rotationVectBefore;
            }
            else if(lookDifference > 1.412 && lookDifference <= 1.70607) //side wall
            {
                transform.up = hit.transform.up;
                transform.forward = forwardVectBefore;
            }
            else //head on wall
            {
                transform.up = hit.transform.up;
                transform.forward = upVectBefore;
            }
        }
    }
}
The first case "Same normal" works fine, however the other two do not work as I would like them to. Sometimes my character is laying down on the surface or on the wrong side of the surface. Does anyone know nice way of solving this problem?
© Game Development or respective owner