首页 > 解决方案 > 如何使 OnCollisionEnter 函数工作?

问题描述

所以,我有一个火箭,当它不与地面碰撞时,它会向前飞。当它击中带有“地面”标签的东西时,它应该停止并召唤爆炸。但是,它没有检测到它何时接触“地面”并穿过它。

我试过改变对撞机的工作方式,但它只是出错了。

我添加了一些打印功能,看看它是否真的被触发了,而事实并非如此。

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 disapears.
    void Start()
    {
        Invoke("Kill", life);
    }


    //detects if tounching ground
    void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "Ground")
        {
            print("working");
            isGrounded = true;
            print("working");
        }
    }
    //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);

    }


    // 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)
        {
            print("YES");
            canRunProgress = false;
            StartCoroutine(Kill());

        }


    }
}

它应该停止火箭,然后召唤爆炸。但是目前它经历了一切。

抱歉粘贴了整个代码。任何帮助将不胜感激:3

标签: c#unity3d

解决方案


如果只是路过,则需要查看 Tag、Collider 和 Rigidbody 的值。请注意,以下代码适用于 2D 项目,如果您正在处理 3D 项目,请确保应用更改。

public class Example : MonoBehaviour
{
    public GameObject explosion;
    public bool isGrounded;

    private void Start()
    {
        Invoke("RemoveRocket", 5);
    }

    private void FixedUpdate()
    {
        if (!isGrounded)
        {
            MoveRocket();
        }
    }

    private void MoveRocket()
    {
        transform.position += (transform.right / .1f) * Time.deltaTime;
    }

    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Ground"))
        {
            Instantiate(explosion, transform);
            isGrounded = true;
            CancelInvoke();
            Destroy(gameObject, 2);
        }
    }

    private void RemoveRocket()
    {
        Destroy(gameObject, 0);
    }
}

推荐阅读