# Getting my bullet to move in a straight line

 0 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? more ▼ asked Mar 13 '10 at 11:18 PM The BOOM 283 ● 20 ● 26 ● 39 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. Mar 14 '10 at 12:25 AM Sebas no reason actually, and with no gravity set it could be a straight line, thnx for the suggestion Mar 14 '10 at 09:22 PM The BOOM add new comment (comments are locked) 10|3000 characters needed characters left ▼ Viewable by all users

 0 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. more ▼ answered Mar 14 '10 at 01:37 AM Jason_DB 1.9k ● 4 ● 14 ● 36 add new comment (comments are locked) 10|3000 characters needed characters left ▼ Viewable by all users
 0 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 more ▼ answered Jul 21 '10 at 05:00 PM ESAR 32 thanks (moar letters) Jul 21 '10 at 06:36 PM The BOOM add new comment (comments are locked) 10|3000 characters needed characters left ▼ Viewable by all users

By Email:

Topics:

x1425
x320
x245

asked: Mar 13 '10 at 11:18 PM

Seen: 1882 times

Last Updated: Mar 13 '10 at 11:18 PM