While setting up a moving Camera, I’ve noticed that the z position from the “Car” object keeps changing when the “Horizontal” Input changes. I pretty much copied the code from the course. It doesn’t really break anything, but I still wonder why this is happening.
“DriverScript”
public class Driver : MonoBehaviour
{
[SerializeField] int SteerSpeed = 220;
[SerializeField] float MoveSpeed = 10.5f;
float SteerAmount;
float MoveAmount;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
SteerAmount = Input.GetAxis("Horizontal") * SteerSpeed * Time.deltaTime;
MoveAmount = Input.GetAxis("Vertical") * MoveSpeed * Time.deltaTime;
transform.Translate(0, MoveAmount, 0);
transform.Rotate(0, 0, -SteerAmount);
}
}
“CameraScript”
public class FollowCamera : MonoBehaviour
{
[SerializeField] GameObject Car;
void LateUpdate()
{
transform.position = Car.transform.position + new Vector3 (0,0,-5.5f);
}
}
That behaviour is indeed odd. What Rigidbody type did you select in the car’s Rigidbody2D component? Is the car colliding with another collider in the scene? Maybe it there is a collision which moves the car on the z-axis.
I have selected a “Rigibody 2D” and a “Box Collider 2D” on the Car-Object. Furthermore, I have noticed that wherever the Car-Object starts z is equal to 0. Z increases if I move right or down, and decreases if I move up or left. I hope this additional information helps narrow down the cause of the problem.
Please expand the Contraints menu in the Rigidbody2D component. Then “freeze” the z-position. Maybe that’ll fix the problem.
You could also try to add f behind the 0s: 0f. In the past, I occasionally experienced unexpected results when passing on an integer to methods expecting floats.
If freezing the z-position did not help, add this piece of code to the bottom your Update method code block:
So, freezing the z-position isn’t possible. I have only the option to freeze the z-rotation, x-position and y-position.
Adding a f behind the 0s also doesn’t seem to work.
Although adding the 3 lines of code works perfectly fine, it still doesn’t explain why the z-position is changing in the first place.
Edit: I just got it. Seems like I had a small amount of x and y rotation in the Car-Object, which then messed up the vector. This also explains why z was decreasing going up and left and increasing going down and right. Thanks anyway, you’ve put me on the right track.