Sxribe
Sxribe

Reputation: 829

Controls messed up on rotation

I am creating a simple controller script for a character in my Unity game. However, when I press W and make my character turn, it's movement changes and all the keybinds are messed up. Here is my Code that turns the character:

transform.rotation = Quaternion.Euler(0,90,0);

Rest of my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class player : MonoBehaviour {
    public float moveSpeed;
    void Start () {
        moveSpeed = 2f;
    }

    void Update () {

        transform.Translate(moveSpeed*Input.GetAxis("Horizontal")*Time.deltaTime,0f,moveSpeed*Input.GetAxis("Vertical")*Time.deltaTime);
        var v = Input.GetAxis("Vertical");
        var h = Input.GetAxis("Horizontal");

        if (v==1)
        {
            transform.rotation = Quaternion.Euler(0,90,0);
        }
    }
}

Upvotes: 0

Views: 121

Answers (1)

Programmer
Programmer

Reputation: 125275

The Transform.Translate function moves in the object in local space by default. When the GameObject rotates, this makes the WASD key to move where the object is facing instead.

To prevent this, make it move to the world space instead. You can do this by passing Space.World to the second parameter of the Transform.Translate function.

void Update()
{

    var v = Input.GetAxis("Vertical");
    var h = Input.GetAxis("Horizontal");

    Vector3 translation = new Vector3(h, 0, v);
    translation *= moveSpeed * Time.deltaTime;

    transform.Translate(translation, Space.World);


    if (v == 1)
    {
        transform.rotation = Quaternion.Euler(0, 90, 0);
    }
}

Upvotes: 1

Related Questions