- Home /
Why is my player object not moving where it is pointing?
I'm making a game that will need rigidbodies everywhere, but while testing the movement script, upon crashing into an object, the player seems to move in the direction it is not facing in (I crashed into a tree, moving forward, but then i started moving left) Also no rotation problems in the many objects in my player prefab are occuring and the crosshair has no collision. Here's my code: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class NewPlayerController : MonoBehaviour
{
private Rigidbody rb;
public GameObject player;
public float thrust = 1.0f;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.W))
{
rb.AddRelativeForce(player.transform.right * thrust * 2.5f);
}
if (Input.GetKey(KeyCode.A)) { player.transform.Rotate(0, -1, 0); }
if (Input.GetKey(KeyCode.D)) { player.transform.Rotate(0, 1, 0); }
if (Input.GetKey(KeyCode.S))
{
rb.AddRelativeForce(player.transform.right * thrust * -2.5f);
}
}
}
Hope someone can find an answer. :)
Answer by justgameitman · Mar 20, 2020 at 02:44 PM
It is moving according to the world coordinates not according to rotation of object.
void Update() { float moveHorizontal = Input.GetAxis("Horizontal"); float moveVertical= Input.GetAxis("Vertical"); Vector3 movement(moveHorizontal, 0f, moveVertical); movement = movement * Camera.main.transform.rotation; rb.velocity = movement; }