2015-04-01 51 views
1

enter image description here如何让敌人不能同时射击(2D游戏)?

我的问题是,所有三个enemys在同一时间拍摄。我先要然后第二个然后第三个开始拍摄。

这里是我的代码:

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()方法被称为动画的事件。

你们有什么建议吗?

+0

的“InvokeRepeating()”方法也可用于这种情况。 – 2015-04-03 21:01:25

回答

3

那么,单向(尽管可能不是最好的)是在Start()内添加延迟。你可以有这样的事情:

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

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

这样,您只需设置startDelay当你看到合适的。因为它是一个公共变量,所以你可以在检查器中为相应的gameObject设置它(如果你在脚本中设置它,每个对象可能有相同的延迟,没有区别)。

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

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

+0

谢谢。它帮助了很多! – 2015-04-03 13:55:17

0

我只是保存一个静态布尔属性的地方。 让我们将其命名为“可以拍摄”。 当敌人在射击延迟后射击并使其成为真实时,我会将其设为假。

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”属性为true

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