I’m currently working on a Starfox-ish game.
I’ve managed to get quite far today, as I’ve managed to make an enemy fly towards the player. What I want to happen is that once an enemy flies within a certain range of the player, it will fly over the player and then self destruct. This is a behaviour I’ve called “disengage”.
At first I was uncertain how to make the enemy fly over the player (because midair collissions with every enemy would be stupid), then I created an actual prefab which is a child to the players plane, which the enemies try to fly in to.
However, once I wrote the code, I wasn’t certain, but I thought it was targeting the “disengage target” straight away. Once I added the self destrct, however, I realised that the enemy plane self destructs immediately. It seems to bypass the timer, as it gets destroyed on frame 1, even if I set the timer to ludicrously large numbers, and the disengage distance to ludicrously small distances.
Anyways, here’s the code:
using UnityEngine;
using System.Collections;
public class EnemyFighterScript : MonoBehaviour {
public float interceptvelocity = 10.0f ;
public Transform Player;
public float distance;
public Transform target;
public Transform disengagetarget;
public float disengagedistance;
public bool disengage;
public float timer;
// Use this for initialization
void Start () {
disengage = false;
}
// Update is called once per frame
void Update () {
distance =Vector3.Distance(transform.position,target.position);
if (distance<disengagedistance){
disengage=true;
}
if (disengage=false){
transform.LookAt (Player);
transform.position += transform.forward * interceptvelocity * Time.deltaTime;
}
if (disengage=true) {
//makes enemy fly away and prepare self destruct after reaching proximity to player
transform.LookAt (disengagetarget);
transform.position += transform.forward * interceptvelocity * Time.deltaTime;
timer =- Time.deltaTime;
}
if(timer <= 1){
//destroys NPC once it passes player
Destroy(gameObject);
}
}
}