I’m trying to make my character rotate in the direction i move in; so if i go forward, the player faces forward, if i go right it faces right, etc. I have checked some other answers tothis problem but they wont work for me. =( Here is my code without any rotation function in it. Also, i want to keep my movement the same as this since it makes the player move in a slippery way, which i like.
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public float moveSpeed; //determined through inspector
private float maxSpeed = 15f;
public GameObject deathParticles;
private Vector3 spawnpoint;
private Vector3 userInput;
float delaytime = 1.0f;
void Start() {
spawnpoint = transform.position;
}
void Update() {
if (delaytime >= 0) {
delaytime -= Time.deltaTime;
return;
} else {
userInput = new Vector3(Input.GetAxisRaw("LeftnRightMovement"), 0, Input.GetAxisRaw("FornBackMovement"));
if (GetComponent<Rigidbody>().velocity.magnitude < maxSpeed)
{
GetComponent<Rigidbody>().AddForce(userInput * moveSpeed);
}
}
}
If anyone could show me how to include the rotation in this script without disrupting the movement it would be great. Also, if possible, please explain how to do it since I am a beginner and I want to understand how it is done and not just copy the code.
Since i’m not sure what is your case, i’ll foward you the easiest way to rotate the character depending on the movement, using a character controller in this case.
Here’s the full thing.
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour
{
public float _gravity = 1.5f;
public float _yVelocity = 0.0f;
public float _moveSpeed = 25.0f;
public float _jumpSpeed = 40.0f;
public CharacterController _controller;
private bool _onGround;
// Use this for initialization
void Start ()
{
_controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update ()
{
_onGround = _controller.isGrounded; //Gets if the controller is grounded
Vector3 direction = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); //Gets the direction
if (direction.sqrMagnitude > 1f) direction = direction.normalized; //This prevents going faster when running diagonically
Vector3 velocity = direction * _moveSpeed; //Multiplies the movement speed
if (_onGround)
{
//JUMPING
if (Input.GetButtonDown("Jump"))
{
_yVelocity = _jumpSpeed; //Gets the jump height on the Y Axis
}
}
else
_yVelocity -= _gravity;
_controller.Move(velocity * Time.deltaTime);
Vector3 facingrotation = Vector3.Normalize(new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical")));
if (facingrotation != Vector3.zero) //This condition prevents from spamming "Look rotation viewing vector is zero" when not moving.
transform.forward = facingrotation;
}
}
Keep in mind this requires a character controller and not a rigid body.
If your character is not that complex, this should be good to go.