Movement Direction Problem

I am having a problem with my script: Paste All -Art, Craft, Design, Drawing & Photography Guide

When ever I rotate the vehicle, it works fine, but if I try to move forward after I turn it, the tank only moves in the original axis. It doesn’t move along the direction the vehicle is pointing. What could cause that, and how can I fix it? Thanks!!!

Instead of

transform.position.z += 1;

You need to move in the direction the tank is facing. To do this you use vectors and transform.forward.

float speed = 10.0f;
transform.position += transform.forward * speed * Time.deltaTime;

This does a couple of things. Instead of always moving a fixed amount, it often works better to scale the speed based on how fast frames are being rendered. This has the affect of always moving the same distance over the same amount of time, regardless of the number of frames being rendered.

So this code uses the speed variable to control how many “units per second” the tank moves. The transform.forward property gives a unit length vector that points in the direction the tank is facing. “Unit length” means the vector has a length of one, so if we add it to position it will move the tank 1 unit (e.g. 1 meter). Multipying that by speed gives us 10 units. We then multiply that by Time.deltaTime which scales the movement amount by the frame rate, so over the course of 1 second it will move 10 meters, spread across multiple frames.

To go backwards, just subtract that instead of adding…

transform.position -= transform.forward * speed * Time.deltaTime;