I am building a very simple car-driving game in Unity.
I have a Player object, which looks like this:
As you can see, I have a Rigidbody2d component attached to this object, as well as a script, called "PlayerScript".
Here is this script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
Rigidbody2D carRigidbody;
Vector3 turnVector;
Vector3 forwardDirection;
// Start is called before the first frame update
void Start()
{
carRigidbody = GetComponent<Rigidbody2D>();
turnVector = new Vector3(0, 1, 0);
}
// Update is called once per frame
void Update()
{
//transform.lo
Debug.Log(string.Format("Transform.rotation is {0}", transform.localRotation.eulerAngles));
Debug.DrawRay(transform.position, transform.forward, Color.yellow);
if (Input.GetKey(KeyCode.UpArrow))
{
carRigidbody.AddRelativeForce(transform.forward * 10);
}
if (Input.GetKey(KeyCode.DownArrow))
{
carRigidbody.AddRelativeForce(transform.forward * -10);
}
if (Input.GetKey(KeyCode.RightArrow))
{
transform.Rotate(turnVector);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.Rotate(-turnVector);
}
}
}
I would expect for this code to make my Player object move forward in its local coordinate space when I hold the up-arrow on the keyboard, and move backward in the same space when I hold the down-arrow. Also, The left and right arrows should simply rotate the player-object (changing the forward direction in its local coordinate space).
Rotating left and right seems to work, but moving forwards and backwards seems to only work in the world coordinate space for some reason. Not sure If I am missing something. Here is a gif of what happens.
As you can see, initially, moving forward and backward using the up and down arrow keys works. I then use the left arrow key to rotate the object left, which also works. But when I then try and add a force in the forward or backward direction, the object is not moving in the object's local forward direction, but instead, in the same forward direction as before.
What am I missing and how can I fix this?
AddRelativeForce
and not justAddForce
? \$\endgroup\$