How to make character rotate in direction of movement?

Hi,

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.

Have you tried using [Vector3.RotateTowards][1] with your RB's velocity (= movement vector) as the target parameter? [1]: http://docs.unity3d.com/ScriptReference/Vector3.RotateTowards.html

@Cherno Thanks for the reply. Could you please explain how exactly i can use this? I tried to use this in my code however it did not rotate my cube.

I'm using 5.2. async.allowSceneActivation set to true initially bypasses the error, but that means I cannot decide when to activate the scenes myself. The error only happens second time I try to load the scenes (after having all of them unloaded).

1 Answer

1

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.

I'm glad it worked :), I was using this in my old character but i ditched it because my character is too complex to just rotate it this way so i went through an animation system, but for something simple it should be good to go.

hi there!, i used your code on my character(with character controller)the part with the jumping doesn't seem to work i changed get button to key down with space i also put a debug.Log to see if it is indeed pressed which it does and the character just doesn't jump :/ any idea? also in some if's you dont do the { } does this have an impact? all this is so new to me!

This is great, thanks! The only further feature I'd like is to get the smooth transitions between angles, like when you go from North to North-East in your example. How would one go about implementing this for all possible angles?

Ah, then maybe this is a new issue for Unity to fix. Try Resources.UnloadAllUnusedAssets. after an unload to see if it flushes some references that might be causing the failed load. Also if still failing then try with some very bare scenes to see if it's a script load issue as well. I remember having failed scene loads due to plugins failing. [Mainly Reign as they had Singletons that were trying to awaken causing weird issues.]

Thanks Kyle. There is only a sprite renderer in each scene currently. I'll try to unload all unused assets, but I have the feeling that even async loading cannot handle loading more scenes than 1 simultaenously.