Reputation: 4941
I have a bullet that has to hit a constantly moving enemy.
So, in BulletScript, I have declared a Transform
public Transform enemy; //and assigned enemy object to it that is continuously moving and changing its position
Now, when I try to use enemy.position
in bullet script so as to hit it, enemy.position
gives the position at which the enemy strted and not the position at which it was when bulletprefab was shot.
How can I get the updated position of enemy object every time bulletprefab is instantiated.
This is how I am changing the enemy's position:
void Update () {
float amttomove = currentSpeed * Time.deltaTime;
transform.Translate (Vector3.left * amttomove);
if (transform.position.x < 0f)
setposandspeed();
}
void setposandspeed()
{
x = 11.5f;
z = 0.0f;
currentSpeed = Random.Range (MinSpeed, MaxSpeed);
y = Random.Range (0f, 2.5f);
transform.position = new Vector3(x, y, z);
}
This is where tried to use enemy's position in bulletscript:
float target_Distance = Vector3.Distance(Projectile.position, Target.transform.position );
It is called inside Start() of bulletscript
This is where I instantiated the bullet in Player class:
Inside Updated method:
if (Input.GetKeyDown ("space")) {
Vector3 position = new Vector3 (transform.position.x, transform.position.y + collider.bounds.size.y / 2);
Instantiate (bulletprefab, position, Quaternion.identity);
}
Upvotes: 1
Views: 207
Reputation: 39164
enemy.position in bullet script so as to hit it, enemy.positiongives the position at which the enemy strted and not the position at which it was when bulletprefab was shot.
No, enemy.position
will return the current position of the enemy, suitable if you want your projectile follow the enemy.
If you are instantiating dynamically your projectiles (BullerScript
) and want to shoot them toward the position the enemy is during the shoot frame, record it just after bullet is instantiated for example:
class BulletScript : MonoBehavior
{
public Vector3 targetPos;
void Update()
{
//move toward targetPos
}
}
BulletScript bullet = GameObject.Instantiate(bulletPrefab,shootPosition) as BulletScript;
bullet.targetPos = enemyPosition;
Upvotes: 1