基本上我想制造一个可以随时转换为恶魔的玩家,只要用户按下启动按钮,但我希望转换在60秒后结束(转换结束时我想让玩家恢复原状州)。如果玩家被敌人击中,我也希望转变结束。到目前为止,我已经制作了这个代码并且它可以工作,但是如果玩家被敌人击中并且如果用户决定按下按钮,我就无法将等待时间重置为等待秒数60秒将玩家变回恶魔。任何人都可以帮我解决这个问题吗?
在我的等级制度中,我将我的玩家作为父亲,将我的恶魔玩家作为孩子。附加到播放器的播放器移动脚本以及下面的转换脚本:
public GameObject demon;
public BoxCollider2D col;
public Renderer rend;
public ParticleSystem par1;
public static Vector3 target;
void Start () {
target = transform.position;
}
void Update () {
target.z = transform.position.z;
}
public void DemonCharacter() {
StartCoroutine (PowerUpCoroutine ());
}
private IEnumerator PowerUpCoroutine() {
yield return new WaitForSeconds (0.3f);
par1.Play (); // particle system animation to cover transformation happening
par1.transform.position = target;
yield return new WaitForSeconds (0.2f);
demon.SetActive (true); // activates demon gameobject
rend.enabled = false; // deactivate players spriterenderer
col.enabled = false;
yield return new WaitForSeconds (60f);
demon.SetActive (false); // deactivates demon gameobject
rend.enabled = true; // activate players spriterenderer
col.enabled = true;
par1.Stop ();
}
在我的恶魔玩家身上,我附上了这个剧本; 我工作但是当用户点击按钮转换成恶魔时,yield waitforseconds不会停止,所以当玩家在几秒钟之后变成恶魔时恶魔玩家会转变回玩家而不是重置产量等待秒。
public BoxCollider2D Playercol;
public Renderer PlayerRend;
void Start()
{
}
void Update ()
{
}
void OnTriggerEnter2D(Collider2D col) {
if (col.tag == "enemy") {
demon.SetActive (false);
PlayerRend.enabled = true;
Playercol.enabled = true;
}
}
答案 0 :(得分:3)
除了@ m.rogalski建议的另一种方法是使用一个简单的浮点变量作为计时器:
public GameObject demon;
public BoxCollider2D col;
public Renderer rend;
public ParticleSystem par1;
public static Vector3 target;
private float demonTimer;
void Start()
{
target = transform.position;
demonTimer = 0.0f;
}
void Update()
{
target.z = transform.position.z;
if (demonTimer > 0.0f)
{
demonTimer -= Time.deltaTime;
if (demonTimer <= 0.0f)
{
demon.SetActive(false);
rend.enabled = true;
col.enabled = true;
}
}
}
public void DemonCharacter()
{
par1.Play();
par1.transform.position = target;
demon.SetActive(true);
rend.enabled = false;
col.enabled = false;
demonTimer = 60.0f;
}
public void CancelDemon()
{
demonTimer = 0.0f;
}
希望这有帮助,
答案 1 :(得分:2)
我建议您修改Coroutine
不使用WaitForSeconds
,但要使用自己的时间计算。
// create the flag indicating interruption
bool _interrupt = false;
// create your coroutine
IEnumerator PowerUpCoroutine()
{
// set the time you want to hold transformation
const float TRANSFORMATION_INTERVAL = 60.0f;
// currently elapsed time
float currentlyElapsed = 0.0f;
// add your logic for pre-transformation
while ( currentlyElapsed < TRANSFORMATION_INTERVAL && !_interrupt )
{
yield return null;
currentlyElapsed += Time.deltaTime;
}
// add post-transformation logic
// revert transformation process
_interrupt = false;
}
现在,如果您运行此协程调用StartCoroutine(PowerUpCoroutine());
,则可以将其中断,将_interrupt
标记设置为true
。例如:
public void Interrupt()
{
_interrupt = true;
}
// in some update :
if ( gotHitThisFrame == true )
Interrupt();