Help With Quaternion.LookRotation
I'm making a fairly basic 3D platformer, and trying to have my character look in the direction they are facing. When I try out the game with the line disabled, the script works fine (allows the character to move and jump). However, when I enable the line with Quaternion.LookDirection and try moving, the character rotates absurdly fast and cannot be controlled. I have a feeling I'm doing this wrong but can't find anything on how exactly I'm supposed to be using it.
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour {
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private float overAllSpeed;
private Vector3 moveDirection = Vector3.zero;
void FixedUpdate() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump")) {
moveDirection.y = jumpSpeed;
}
}
else if(controller.isGrounded==false) {
moveDirection.x = Input.GetAxis("Horizontal");
moveDirection.z = Input.GetAxis("Vertical");
moveDirection = transform.TransformDirection(moveDirection);
moveDirection.x *= speed;
moveDirection.z *= speed;
moveDirection.y -= gravity * Time.deltaTime;
}
controller.Move(moveDirection * Time.deltaTime);
overAllSpeed=Mathf.Abs((moveDirection.x+moveDirection.z)/2);
Debug.Log(overAllSpeed);
if (overAllSpeed!=0)
transform.rotation = Quaternion.LookRotation(moveDirection);
}
}
Answer by cjdev · Jun 15, 2016 at 04:32 AM
Because you're transforming the moveDirection vector into world coordinates I think you'd have better luck with Transform.LookAt instead. It takes a world position and orients the rotation towards that position.
Your answer
Follow this Question
Related Questions
How can I make my game object move like this? 0 Answers
Draw a ray from a gamobject and keep direction of the ray relative to the gameobjects rotation. 1 Answer
Uniform quaternion from a list of points? 0 Answers
Reading Quaternion.eulerAngles.y smaller 45 and greater 315 does not work 0 Answers
How do I orient one axis of an object following LookAt/LookRotation? 0 Answers