Question by
Vioswift · Sep 10, 2015 at 10:50 AM ·
rotationpositionquaternionslopeoncontrollercolliderhit
Unity 3D C# - Rotation To Slope Of Terrain
My plan is to always keep player up right when going up a slope when moving, right now, the code Is close to working but not there yet, can anyone please help me?
this is my code, focus on lines Vector3 newDir and down
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
//private float myAng;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
// if (Input.GetButton("Jump"))
// {
// moveDirection.y = jumpSpeed;
// }
//keep player grounded
moveDirection.y -= 10f;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
//transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, 10);
Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, speed * Time.deltaTime, 0.0F);
transform.rotation = Quaternion.LookRotation(newDir);
Debug.DrawRay(transform.position, targetDir, Color.red);
}
Quaternion targetRotation;
Vector3 targetDir;
void OnControllerColliderHit(ControllerColliderHit hit) {
//myAng = Vector3.Angle(Vector3.up, hit.normal); //Calc angle between normal and character
//transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal) * transform.rotation;
//transform.Rotate(Vector3.up * Time.deltaTime * 6f);
//transform.rotation = Quaternion.LookRotation(new Vector3(hit.normal.x / 2, transform.position.y / 2, hit.normal.z / 2));
//targetRotation = Quaternion.FromToRotation(transform.eulerAngles, new Vector3(hit.normal.x, 0, hit.normal.z));
targetDir = (transform.position - (new Vector3(hit.point.x, 0, hit.point.z) / hit.point.magnitude));
}
Comment