- Home /
How do I make this kind of follow script?
So basically, I'm making a 2d android game similar to the game asteroids but instead of asteroids, I fight alien spaceships. What I want my alien spaceship to do is look at the player and follow it. When the alien spaceship reaches a certain distance,like for example the ship is 5 units near my ship, it stops following my ship but continues to look at it, then if i move closer to the alien spaceship, it moves backwards as if it was avoiding collision to my ship.
Then here's the catch, my ship has the ability to push the aliens away using this line of code:
var explosionPos : Vector3 = transform.position;
var colliders : Collider[] = Physics.OverlapSphere (explosionPos, radius);
for (var hit : Collider in colliders) {
if (!hit)
continue;
if (hit.rigidbody)
hit.rigidbody.AddExplosionForce(power, explosionPos, radius);
}
In other words, I made the alien spaceships rigidbodies.
How do I make a code in which that when I apply an explosion force to them, they temporarily get pushed back, then after getting pushed away for a while, the alien looks at and follows the player once again?
I hope that those who read this is getting me. I would really appreciate the help you would give me since this code you're about to teach me plays an important role in my game.
Thanks a lot! :D
Answer by Azuri · Aug 19, 2012 at 02:30 AM
put this script on the alien spaceship
var playerSpaceShip:Transform; // assign the player spaceship here
function Update() {
// this rotates the alienspaceship into the player direction
var wantedRotation : Quaternion = Quaternion.LookRotation(transform.position - playerSpaceShip.position, Vector3.forward);
wantedRotation.x = 0.0;
wantedRotation.y = 0.0;
playerSpaceShip.rotation = wantedRotation;
//move forward
if ( Vector3.Distance(transform.position, playerSpaceShip.position) < 5 ) // if distance < 5 units then stop moving forward
transform.Translate(Vector3.up * 1 * Time.deltaTime);// this moves it forward
}
it's kinda getting screwed up, since I rotated my model 270 degrees.
and the movement gets ruined when the explosion force is applied