【发布时间】:2019-01-11 12:11:21
【问题描述】:
我创建了一个 2d 隐身游戏,敌人向玩家开火,唯一的问题是,尽管在另一个脚本上可以很好地创建和删除子弹,但脚本本身每帧都会用子弹向程序发送垃圾邮件,从而产生不需要的结果
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HurtPlayer : MonoBehaviour
{
public float timeToShoot;
private float timeToShootCounter;
private bool shot;
private Vector3 moveDirection;
public float timeBetweenShot;
public float timeBetweenShotCounter;
public Transform firePoint;
public GameObject Bullet;
// Use this for initialization
void Start()
{
shot = false;
timeToShootCounter = timeToShoot;
}
// Update is called once per frame
void Update()
{
while (shot == true)
{
StartCoroutine(Delay());
Destroy(GameObject.Find("Bullet"));
timeBetweenShot -= Time.deltaTime;
timeToShoot -= Time.deltaTime;
}
}
IEnumerator Delay()
{
yield return new WaitForSeconds(0.5f);
}
void OnTriggerStay2D(Collider2D other)
{
if (other.gameObject.tag == "player")
{
if (shot == false)
{
if (timeToShoot >= 0f)
{
shot = true;
if (shot == true)
{
shot = false;
Instantiate(Bullet, firePoint.position, firePoint.rotation);
Delay();
if (timeBetweenShot <= 0f)
{
shot = false;
timeToShoot = timeToShootCounter;
timeBetweenShot = timeBetweenShotCounter;
}
}
}
}
}
}
}
我想要的是射击工作之间的时间和敌人每一秒或半秒只射击一次的时间,谢谢。
【问题讨论】:
-
标题是给你简单说明你的问题,不是说“我的代码不行”
-
我认为这个逻辑对于这样的任务来说太复杂了。你为什么不在
OnTriggerStay2D中获得一个标志,并且当标志为真时,每 0.5 秒实例化一个子弹? -
另外,Update 中的 while 循环完全没用。您尚未完全冻结编辑器的唯一原因是,
shot永远不会为真,除非在OnTriggerStay中的某个瞬间再次立即设置为假。 -
您的
Delay没有任何作用。即使您使用 StartCoroutine 正确调用它,它也不会延迟随后的代码。直接调用它不会将代码作为协程运行,但即使这样做了,您也只能在协程内部延迟代码。 -
最后,你可以简单地写
if(shot)而不是if(shot == true)