- Home /
how to detect object position in specific time?
im making shooting game. enemy can shoot the player. i want to make the enemy detect the player position and shoot. but, if the player move to the left or right, the bullet is still move to the player last position before moving. im trying this, transform.position = Vector3.MoveTowards(transform.position, letakbox.transform.position, 0.2f); but the bullet is like homing missile!!
please help me. im newbie here.
im sorry my english is bad. but i hope you can understand what i mean. Thankyouu Pleas help ToT
Answer by flamy · Mar 18, 2014 at 05:49 AM
transform.position = Vector3.MoveTowards(transform.position, letakbox.transform.position, 0.2f);
this line is the problem you are moving the bullet toward the player always instead have something like Shoot position and save the position of the player when enemy shoots. That woudl solve it
or when you instantiate the bulled save the position of the player in that frame and use it in move towards.
var targetPosition:Vector3;
function Start()
{
targetPosition = letakbox.transform.position;
}
function Update()
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, 0.2f);
}
Answer by RyanZimmerman87 · Mar 21, 2014 at 03:49 AM
You could also just use something like:
transform.position += transform.forward bulletSpeed Time.deltaTime;
That would cause the bullet to always shoot in a straight line. You might just need to make sure it's original rotation is correct with something like:
transform.LookAt(letakbox.transform.position);
You would only need to use the LookAt command when the bullet first instantiates, not every Update(). After that you could just use the transform.forward stuff.
I think that would be slightly more performance friendly since you would just be moving the bullet to an exact spot each Update instead of comparing it's current position to the end location before the movement calculation every time, but either way should be fine. You may also want to consider adding force to your bullet and moving it as a rigid body in FixedUpdate() if you want any gravity effects.
http://docs.unity3d.com/Documentation/ScriptReference/Rigidbody.AddForce.html
Your answer
![](https://koobas.hobune.stream/wayback/20220613140527im_/https://answers.unity.com/themes/thub/images/avi.jpg)