- Home /
Keeping rigidbody upright in relation to slope
Hello, I want to make a snowboarding game and I want the character to always be perpendicular to the slope.
So far I've tried freezing the rotation of the x and z axis but that just keeps the character completely straight. I want him to follow the contours without having to increase the mass just to get him to stay put. If anyone could help that'd be awesome
Answer by syclamoth · Dec 20, 2011 at 06:44 AM
The most straightforward way of doing this would be to keep track of the current 'up' direction, and continually raycast downwards to find the normal of the surface below and update accordingly. Some sample code (how I would do it)-
// First off, make sure that you are freezing the rotation
// of the rigidbody since we are doing that manually now.
// This determines how fast the rigidbody rotates towards the correct value
public float dampingRate;
// This determines how far it can detect the ground from
public float rayLength;
// Set this up with the correct 'ground' layers
public LayerMask mask;
Vector3 currentUp = Vector3.up;
void FixedUpdate()
{
RaycastHit hit;
if(Physics.Raycast(transform.position, -currentUp, out hit, rayLength, mask))
{
currentUp = hit.normal;
}
Quaternion targetRotation = transform.rotation;
if(rigidbody.velocity.magnitude > 0)
{
targetRotation = Quaternion.LookRotation(rigidbody.velocity, currentUp);
}
rigidbody.rotation = Quaternion.Slerp(rigidbody.rotation, targetRotation, Time.deltaTime * dampingRate);
}
This will always rotate the object towards its velocity- as calculated by physics. Assuming that it slides down hills in a normal fashion, this should result in nicely directed rotations.
I'm getting an error when I'm trying it. I don't really use c#
I found this searching normals though.
using UnityEngine; using System.Collections;
public class align : $$anonymous$$onoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void FixedUpdate ()
{ RaycastHit hit;
Vector3 theRay = transform.TransformDirection(Vector3.down); // Convert from local space to world space
Debug.DrawRay(transform.position, theRay, Color.red);
if (Physics.Raycast(transform.position, theRay, out hit))
{
transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
}
} }
Answer by seanmul10 · May 12, 2014 at 08:30 PM
i cant make him stay straight in the first place, he was, i saved, came back and now he leans toward the camera
Your answer
Follow this Question
Related Questions
Guidelines for using rigidbody, collider, CharacterControllerScript, etc? 3 Answers
Character Controller meets Rigidbody 1 Answer
Unity 4.3 CharacterController collision with physics 2D not working 1 Answer
Prevent rigidbody being affected by character controller 2 Answers
Prevent player from "Running Over Top Of" specific colliders. 0 Answers