- Home /
Character Rotation
Alright so i am trying to write a movement script kind of like what would be used for a 2d side scroller. my problem lies in having the character rotate to the direction he is walking. i cant seem to figure out a solution to make this work properly. here is the current code i have atm
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public float speed = 10.0f;
public float rotationspeed = 100.0f;
private float moveBack = -1.0f;
private float moveForward = 1.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if(Input.GetKey(KeyCode.A))
{
float translation = moveBack * speed;
//float rotation = moveBack * rotationspeed;
translation *= Time.deltaTime;
//rotation *= Time.deltaTime;
transform.position += Vector3.right * translation;
}
if(Input.GetKey(KeyCode.D))
{
float translation = moveForward * speed;
//float rotation = moveBack * rotationspeed;
translation *= Time.deltaTime;
//rotation *= Time.deltaTime;
transform.position += Vector3.right * translation;
}
}
}
I presume the problem is that the player keeps rotating forever? Also you might want to use Vector3.forward as the move direction, assu$$anonymous$$g the player character faces the walk direction. In case my assumption was correct, you may want to try a $$anonymous$$athf.Clamp method to constraint the rotation.
Answer by Piflik · Sep 15, 2011 at 11:58 AM
Try this:
transform.forward = Vector3.Slerp(transform.forward, Vector3.right * translation, rotationspeed);
Thank you so much this worked perfectly. just had to multiply Time.deltaTime to rotationspeed for it to rotate smoothly. i cant thank you enough for this.
Answer by PaxNemesis · Sep 15, 2011 at 12:15 PM
This might be what you are looking for.
[RequireComponent(typeof(CharacterController))]
public class PlayerMovement : MonoBehaviour
{
public float movementSpeed = 10.0f;
public float rotationSpeed = 100.0f;
private CharacterController controller;
void Start()
{
// Finds the objects charactercontroller.
controller = GetComponent<CharacterController>();
}
void Update()
{
if (Input.GetKey(KeyCode.A))
{
LookAtDirection(-Vector3.right);
Move();
}
if (Input.GetKey(KeyCode.D))
{
LookAtDirection(Vector3.right);
Move();
}
}
public void LookAtDirection(Vector3 targetDirection)
{
gameObject.transform.rotation = Quaternion.Slerp(gameObject.transform.rotation,
Quaternion.LookRotation(targetDirection),
rotationSpeed * Time.deltaTime);
}
public void Move()
{
Vector3 moveDirection = gameObject.transform.forward * movementSpeed;
// Move the controller
controller.Move(moveDirection * Time.deltaTime);
}
}
*Updated to include some movement code.