3d Character rotation
Hello, I'm kinda a beginner when it comes to 3d in unity. I put this script together:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
Animator anim;
public float speed = 6.0F;
private Vector3 moveDirection = Vector3.zero;
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
float input_x = Input.GetAxisRaw("Horizontal1");
float input_y = Input.GetAxisRaw("Vertical1");
bool isWalking = (Mathf.Abs(input_x) + Mathf.Abs(input_y)) > 0;
anim.SetBool("IsWalking", isWalking);
if(isWalking)
{
anim.SetFloat("x", input_x);
anim.SetFloat("y", input_y);
CharacterController controller = GetComponent<CharacterController>();
moveDirection = new Vector3(Input.GetAxis("Horizontal1"), 0, Input.GetAxis("Vertical1"));
moveDirection = transform.TransformDirection(moveDirection);
controller.Move(moveDirection * speed * Time.deltaTime);
}
}
}
It works fine for the most part. The character plays the walking animation when a key is down and the idle animation when nothing is pressed. However, the character only faces forward even when I move right and left. I don't know how to fix it....Help please. Thanks in advance,
Comment
Best Answer
Answer by Mergster · Dec 08, 2016 at 08:36 PM
I fixed it! Here's my fixed script:
Animator anim;
public float speed = 6.0F;
private Vector3 moveDirection = Vector3.zero;
public GameObject player;
public float turnspeed=180f;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
float input_x = Input.GetAxisRaw("Horizontal1");
float input_y = Input.GetAxisRaw("Vertical1");
bool isWalking = (Mathf.Abs(input_x) + Mathf.Abs(input_y)) > 0;
anim.SetBool("IsWalking", isWalking);
if(isWalking)
{
CharacterController controller = GetComponent<CharacterController>();
moveDirection = new Vector3 (Input.GetAxis ("Horizontal1"), 0, Input.GetAxis ("Vertical1"));
player.transform.rotation = Quaternion.RotateTowards (player.transform.rotation, Quaternion.LookRotation (moveDirection), turnspeed * Time.deltaTime);
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * speed * Time.deltaTime);
}
}
}
Your answer