- Home /
Normal Walker: Player Y Rotation Snapping back to 0?
I found a script recently that allows you to walk on an object and rotate based on the normals below the object. The problem is that the player y rotation snaps back to 0 whenever the rotation of the player is modified. This is a problem as I am making a first person game where you navigate the inside of a tube. Also how would I make the transition smoother when the player rotation changes. I know I would need to add a slerp or lerp of some sort but I am a noob and am not familiar with quaternions.
using UnityEngine;
using System.Collections;
public class NormalWalker : MonoBehaviour
{
//this game object's Transform
private Transform goTransform;
//the speed to move the game object
private float speed = 6.0f;
//the gravity
private float gravity = 50.0f;
//the direction to move the character
private Vector3 moveDirection = Vector3.zero;
//the attached character controller
private CharacterController cController;
//a ray to be cast
private Ray ray;
//A class that stores ray collision info
private RaycastHit hit;
//a class to store the previous normal value
private Vector3 oldNormal;
//the threshold, to discard some of the normal value variations
public float threshold = 0.009f;
// Use this for initialization
void Start()
{
//get this game object's Transform
goTransform = this.GetComponent<Transform>();
//get the attached CharacterController component
cController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
//cast a ray from the current game object position downward, relative to the current game object orientation
ray = new Ray(goTransform.position, -goTransform.up);
//if the ray has hit something
if (Physics.Raycast(ray.origin, ray.direction, out hit, 5))//cast the ray 5 units at the specified direction
{
//if the current goTransform.up.y value has passed the threshold test
if (oldNormal.y >= goTransform.up.y + threshold || oldNormal.y <= goTransform.up.y - threshold)
{
//set the up vector to match the normal of the ray's collision
goTransform.up = hit.normal;
}
//store the current hit.normal inside the oldNormal
oldNormal = hit.normal;
}
}
}
Your answer
Follow this Question
Related Questions
Quaternion and gravity trouble 2 Answers
How do you change gravity with a press of a button? Unity 2D 2 Answers
How do you change the direction of gravity? 2 Answers
I am getting LOW Fps, because of simple Physics. Help. 5 Answers
Upside down wall jumps! 1 Answer