如何使爆炸召唤代码正常工作

时间:2019-04-04 01:41:40

标签: c# unity3d

所以,我正在做一个游戏,其中的主要机制是火箭跳跃(向脚开火和爆炸推动你的力量(如TF2)),我无法一次召唤爆炸并且它在错误的位置传唤:/

我尝试在if语句中添加等待,并偶然发现了我当前正在使用的内容。从理论上讲这应该起作用,但是不起作用。

using UnityEngine;
using System.Collections;

public class Rocket : MonoBehaviour
{
    //Public changable things
    public float speed = 20.0f;
    public float life = 5.0f;
    public bool canRunProgress = true;
    public bool isGrounded;
    public GameObject Explosion;
    public Transform rocket;
    public Rigidbody rb;


    // If the object is alive for more than 5 seconds it dissapears.
    void Start()
    {
        Invoke("Kill", life);
    }
    // Update is called once per frame
    void Update()
    {
        //if the object isn't tounching the ground and is able to run it's process
        if (isGrounded == false && canRunProgress)
        {
            transform.position += transform.forward * speed * Time.deltaTime;
            canRunProgress = true;
        }
        //if the object IS touching the ground it then makes the above process unable to work and then begins the kill routine
        else if(isGrounded == true)
        {
            canRunProgress = false;
            StartCoroutine(Kill());
        }
        //detects if tounching ground
        void OnCollisionEnter(Collision other)
        {
            if (other.gameObject.tag == "Ground")
            {
                isGrounded = true;
            }
        }
        //detects if tounching ground
        void OnCollisionExit(Collision other)
        {
            if (other.gameObject.tag == "Ground")
            {
                isGrounded = false;
            }
        }
        //kill routine - explosion is summoned and explodes 2 seconds later it then destroys the rocket.
        IEnumerator Kill()
        {
            GameObject go = (GameObject)Instantiate(Explosion, transform); // also this needs to have the explosion be summoned in the middel of the rocket.
            yield return new WaitForSeconds(2f);
            Destroy(gameObject);
        }
    }
}

(当发射器将火箭召唤到游戏中时)它应该使火箭向前飞行,然后当它撞击地面(带有“ ground”标记)时停止移动并召唤其周围爆炸,并在2秒后毁了。目前,它只是沿着地面反弹。

任何帮助将不胜感激。 :3

1 个答案:

答案 0 :(得分:0)

首先,您遇到语法错误:OnCollisionEnter,OnCollisionExit和Kill方法位于Update方法中……您应该首先对其进行修复。

然后,为了使您的代码正常工作,我假设您已在火箭上放置了对撞机,并在地面上放置了对撞机。 如果火箭弹跳,则可能是刚体的原因。确实,刚体使对象发生碰撞和反弹,因此不会抛出OnCollisionEnter。如果火箭或地面上有一颗,请尝试将其移除。