- Home /
C# - 2D - How can I make my homing rockets follow my player, and when my player dies, the rocket just keeps going forward?
How can I make a lot of homing rockets to follow my player, and when my player dies of one of the rockets, the other rockets just keeps going forward on the same direction as they were going before?
This code only looks at the player, and follows it, which is how it's supposed to work, but when the player dies, they're just stuck on the same position of where they were when the player died. I want them to just keep moving forward on the same angle as before endlessly (I have a destroyer collider).
var dir = playerPosition - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - 90;
if(player.alive)
{
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.position = Vector3.MoveTowards (transform.position, playerPosition, Time.deltaTime * speed);
}
Thanks!
Answer by HarshadK · May 13, 2014 at 11:40 AM
Procedure:
1) Just add an else loop to player.alive check.
2) In that else loop set the transform.position to the forward position so that the rocket keeps moving in forward direction.
Code:
else {
transform.position += transform.forward * Time.deltaTime;
}
transform.forward doesn't work in 2D though, it just moves on the Z position, which doesn't affect the 2D view at all, so it looks like the missile is just stuck there, not moving. Any way around it? Thanks :)
Is it a rigid body? You can try freezing the axis you don't want moving (i.e. freezing y and z so that it just goes straight).
rigidbody.transform.position.Z = 0; // Or whatever set height you want the projectile to stay at.
Thanks! It works now. I just changed transform.forward to transform.up.
Thanks Harshad and Addyarb, oh and it was a Rigidbody 2D.
Also there are constraints on the rigidbody component itself that you an access. rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY;