如何让敌人不同时射击(2d 游戏)?

How to make enemys not to shoot at the same time (2d game)?

我的问题是三个敌人同时射击。我要先拍第二拍第三拍

这是我的代码:

public float speed = 7f;
public float attackDelay = 3f;
public Projectile projectile;

private Animator animator;

public AudioClip attackSound;

void Start () {
    animator = GetComponent<Animator> ();

    if(attackDelay > 0){

        StartCoroutine(onAttack());
    }
}

void Update () {
    animator.SetInteger("AnimState", 0);
}

IEnumerator onAttack(){
    yield return new WaitForSeconds(attackDelay);
    fire();
    StartCoroutine(onAttack());
}

void fire(){
    animator.SetInteger("AnimState", 1);

    if(attackSound){
        AudioSource.PlayClipAtPoint(attackSound, transform.position);
    }
}
void onShoot(){
    if (projectile){
        Projectile clone = Instantiate(projectile, transform.position, Quaternion.identity)as Projectile;
        if(transform.localEulerAngles.z == 0){
            clone.rigidbody2D.velocity = new Vector2(0, transform.localScale.y) * speed * -1;
        }
        else if(Mathf.RoundToInt(transform.localEulerAngles.z) == 90){

            clone.rigidbody2D.velocity = new Vector2 (transform.localScale.x, 0) * speed;
        }
        else if(Mathf.RoundToInt(transform.localEulerAngles.z) == 180){
            clone.rigidbody2D.velocity = new Vector2 (0, transform.localScale.y) * speed;
        }
        else if(Mathf.RoundToInt(transform.localEulerAngles.z) == 270){
            clone.rigidbody2D.velocity = new Vector2(transform.localScale.x, 0) * speed * -1;
        }
}

}

onShoot() 方法在动画中作为事件调用。

大家对此有什么建议吗?

好吧,一种方法(虽然可能不是最好的)是在 Start() 内添加延迟。你可以有这样的东西:

public float startDelay;
...
void Start()
{
    ...
    StartCoroutine(startDelay());
}

IEnumerator startDelay()
{
    yield return new WaitForSeconds(startDelay);
    StartCoroutine(onAttack());
}

您只需根据需要设置 startDelay 即可。因为它是一个 public 变量,您可以在检查器中为相应的游戏对象设置它(如果您在脚本中设置它,每个对象可能会有相同的延迟,没有区别)。

另一种方法可能是随机化 attackDelay。使用Random.Range确定attackDelay,同时保持在合理范围内。

我想你可能还想重新考虑你的敌人是如何运作的。也许让他们在玩家越过触发器时射击,或者加入一些逻辑让他们在玩家进入范围内时射击。

我只是在某处保存一个静态布尔值 属性。 我们将其命名为"Can Shoot"。 我会在敌人射击时将其设置为 false,并在射击延迟后将其设置为 true。

public float shooting delay;    

bool _canShoot;
public static bool canShoot
{
    get { return _canShoot; }
    set { _canShoot = value; StartCoroutine(EnableShooting()); }
}

IEnumerator EnableShooting()
{
    yield return new WaitForSeconds(delay);
    _canShoot = true;
}

现在只需修改你的拍摄方法,仅在 "canShoot" 属性 为真时拍摄

void onShoot(){
if (projectile && canShoot){ 
    canShoot = false;
    ... 
}