- Home /
Rotating / Smooth look at direction for Player
float inputX = Input.GetAxis("Horizontal");
float inputY = Input.GetAxis("Vertical");
if(inputX > 0 && inputY < 0)//D and S
{
rotatationY += inputX*turnSpeed;
rotatationY = Mathf.Clamp (rotatationY, 0, 135);
}
else if(inputX < 0 && inputY < 0)//A and S
{
rotatationY += inputX*turnSpeed;
rotatationY = Mathf.Clamp (rotatationY, 225, 360);
}
else if(inputX > 0 && inputY > 0)//D and W
{
rotatationY += inputY*turnSpeed;
rotatationY = Mathf.Clamp (rotatationY, 0, 45);
}
else if(inputX < 0 && inputY > 0)//A and W
{
rotatationY -= inputY*turnSpeed;
rotatationY = Mathf.Clamp (rotatationY, -45, 0);
}
else if(inputX > 0 || inputX < 0)//A or D
{
rotatationY += inputX*turnSpeed;
rotatationY = Mathf.Clamp (rotatationY, -90, 90);
}
else if(inputY > 0 || inputY < 0)//W or S
{
rotatationY -= inputY*turnSpeed;
rotatationY = Mathf.Clamp (rotatationY, 0, 180);
}
dir.y = rotatationY;
transform.localRotation = Quaternion.Slerp(transform.localRotation, Quaternion.Euler(dir.x,dir.y,dir.z), Time.deltaTime * speed);
This code here makes the player rotate and face its direction. Is there another way to make this code lesser and better? or is this fine which I highly doubt it.
Answer by robertbu · Dec 15, 2013 at 04:15 PM
I'm guessing a bit on your desired behavior. Here is a different way to do what I believe you are doing in this script. Note it depends on the object having a "normal" rotation where the front is facing positive 'z' and up is facing positive 'y'.
using UnityEngine;
using System.Collections;
public class Facing : MonoBehaviour {
public float speed = 2.0f;
private Quaternion qTo;
void Start() {
qTo = transform.rotation;
}
void Update () {
Vector3 direction = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
if (direction != Vector3.zero)
qTo = Quaternion.LookRotation (direction);
transform.rotation = Quaternion.Slerp (transform.rotation, qTo, Time.deltaTime * speed);
}
}
Your answer
Follow this Question
Related Questions
Camera rotation around player while following. 6 Answers
How to Rotate Camera around GameObject (Player) 0 Answers
Rotate vector around vector? 2 Answers
How to rotate an object along the Y axis to the right, and then to the left? 2 Answers
how do i rotate the player with the camera using this code i made. 2 Answers