- Home /
 
How to rotate/tilt an object to match angle of slope?
The title says it all. Here is my code(In C#)
float spinSpeed = 2000f; float moveSpeed; float gravity = 40f; float moveLimit; RaycastHit hit; Vector3 moveDirection = Vector3.zero; CharacterController controller;
 
               // Use this for initialization void Start () { controller = GetComponent<CharacterController>(); animation.wrapMode = WrapMode.Loop; animation["Take 001"].speed = spinSpeed; animation.CrossFade("Take 001"); moveLimit = controller.slopeLimit - 0.1f; }
 
               // Update is called once per frame void Update() { if (Input.GetAxis("Horizontal") > 0.1) moveSpeed = 15f; else if (Input.GetAxis("Horizontal") < -0.1) moveSpeed = 15f; else if (Input.GetAxis("Vertical") > 0.1) moveSpeed = 15f; else if (Input.GetAxis("Vertical") < -0.1) moveSpeed = 15f; else moveSpeed = 0f;
 
                if (Vector3.Angle(hit.normal, Vector3.up) > moveLimit)
     transform.rotation =
         Quaternion.FromToRotation(Vector3.up, hit.normal) * Quaternion.LookRotation(moveDirection);
 moveDirection = new Vector3(Input.GetAxis("Vertical"), 0, Input.GetAxis("Horizontal"));
 moveDirection = transform.TransformDirection(moveDirection);
 moveDirection.y -= gravity * Time.deltaTime;
 controller.Move(moveDirection * (Time.deltaTime * moveSpeed));
  
               }  
You're using the 'hit' variable, but you never actually perform a raycast (at least not in the code you posted). Is that intentional?
Answer by Arunabh Das · Dec 26, 2010 at 05:04 AM
I don't really get what you are talking about. Actually I never worked with raycast in my game.
At the top, you have a variable RaycastHit hit;. Its only goal in life is get the data back from a RayCast. You are using hit in the code, but it is all zeros, since you don't do a Raycast, which is the only way to put useful data into hit. Double-check where you found this -- you probably missed a line or two. 
Answer by user-10163 (google) · Mar 11, 2011 at 01:03 AM
The above script does not work as desire, could you post more information how to use the code?
Your answer