# Getting my bullet to move in a straight line

This is my bullet code:

function Awake () { target = GameObject.FindWithTag("Enemy"); xPosition = target.GetComponent("Transform").transform.position.x; zPosition = target.GetComponent("Transform").transform.position.z; xDifference = Mathf.Abs(transform.position.x - xPosition); zDifference = Mathf.Abs(transform.position.z - zPosition); }

function Update () {

``````Go ();
``````

}

function Go () { if (xDifference < .01) x = 0; else { if (transform.position.x < xPosition) { x = speed * Time.deltaTime; } if (transform.position.x > xPosition) { x = -1 * speed * Time.deltaTime; } }

``````if (zDifference < .01)
z = 0;
else
{
if (transform.position.z < zPosition)
{
z = speed * Time.deltaTime;
}
if (transform.position.z > zPosition)
{
z = -1 * speed * Time.deltaTime;
}
}

transform.Translate(x,0,z);

return void;

``````

}

(well, there's more to it, but that's the condensed version) I want the bullet I fire to go in a straight line, but if the object in question isn't an equal distance away in x and z, the bullet unrealistically turns in mid air. Can I please have help?

Or you can do this vector math:

` transform.position = transform.position + fSpeed * transform.forward; `

and tada the bullet will go straight forward from where you shoot it.

also you can change transform.forward for any direction vector which can be something like this:

` vDirection = target.position - transform.position; vDirection = vDirection.normalized; `

hope its usefull.

:P

The problem is that you only have one speed for both x and z. What is happening is that it goes at a 45 degree angle until either xdifference or zdifference is zero, and then goes straight to the object.

What you need to do is make two speeds (one for x and one for z) and them calculate them based on the angle between where the bullet starts and its target, possibly by using the vector between the two points.