- Home /
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?
just out of curiosity and to confirm before posting some answer: is there a reason why you don't simply apply a force to your bullet object? If the force is large enough, the path will be very close to a straight line.
no reason actually, and with no gravity set it could be a straight line, thnx for the suggestion
Answer by Jason_DB · Mar 14, 2010 at 01:37 AM
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.
Answer by ESAR · Jul 21, 2010 at 05:00 PM
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
I had been using translate function with normalized direction vector but it never went in a straight line. This worked perfectly. Thanks!