Reputation: 1664
I'm creating a top down 2D game. Here is the code that makes my player instantiate the bullet:
public GameObject bullet;
void Update ()
{
if (Input.GetButton("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(bullet, transform.position, transform.rotation);
}
}
Here is the script attached to the bullet to make it move:
void Update ()
{
transform.Translate(transform.forward * Time.deltaTime * speed);
}
It appears that the bullet only moves in its Z axis, which in a 2D game appears as if it's standing still. How to fix that?
Upvotes: 2
Views: 1533
Reputation: 374
Vector3.forward is the same as doing new Vector3(0, 0, 1) which means it would be a positive on the z axis. Pick from the below what represents your camera setup.
Here is the list of static helpers from Vector3 types:
EDIT for comment below:
Transform is your GameObjects position, rotation, and scale. When you use the translate method you are moving the position of the GameObject in a direction using Vector3(and in your case adjusting to the deltaTime between frames), so depending on the orientation(is it viewing on the X/Y/Z axis) of the camera the GameObject is relative to the world space(generally, unless relativeTo is adjusted) and has particular axis as a whole, your GameObject needs to move relative to that space.
Think of it this way, say you're sitting at a desk, the desk is the world space and what you can observe from your point of view is 3 dimensions. you can see to the left and right(x axis), up and down (y axis) and from your point of view forward(z axis). If you wanted to move a paper clip forward it would be Vector3.up since your staring down the z axis, however if you stand and looked down at the table(like the camera was above the world space) then in order to make the paper clip move forward(up) you would use Vector3.forward.
Thats why i stated what represents your camera setup since your scene can be in any arrangement if not specified.
Upvotes: 3