OnCollisionEnter2D从未调用

本文关键字:调用 OnCollisionEnter2D | 更新日期: 2023-09-27 18:21:11

所以我的目标是检测pacman何时吃颗粒,但从未调用OnCollisionEnter2D方法。我是Unity的新手,很抱歉这只是一个简单的解决方案。唯一的"问题"是所有内容都是动态生成的,因此这可能是问题的原因之一。

public class World : MonoBehavior
{
    GameObject pacman;
    List<GameObject> pellets;
    // Use this for initialization
    void Start()
    {
         pellets = new List<GameObject>();
         pacman = new GameObject();
         pacman.AddComponent("PacmanController");
         pacman.AddComponent<SpriteRenderer>();
         pacman.GetComponent<PacmanController>().Setup(eastSprite, new Vector3((y - width / 2)*scale.x, -(x - height / 2) * scale.y, 0), new Vector3(2, 2, 0));
         pacman.AddComponent<Rigidbody2D>();
         pacman.GetComponent<Rigidbody2D>().gravityScale = 0;
         for(...)
         {
             GameObject go = new GameObject();
             go.transform.position = new Vector3((y - width / 2) * scale.x, -(x - height / 2) * scale.y, 0);
             go.AddComponent<SpriteRenderer>();                 
             go.GetComponent<SpriteRenderer>().sprite = pelletSprite;
             go.transform.localScale = new Vector3(2, 2, 0);
             go.name = "pellet";// +y + "," + x;
             pellets.Add(go);
         }
    }
}

pacman类:

using UnityEngine;
using System.Collections;
public class PacmanController : MonoBehaviour {
    // Use this for initialization
    void Start () {
    }
    bool aDown;
    bool wDown;
    bool dDown;
    bool sDown;
    void Update () {
        Vector3 scale = new Vector3(.4f, .4f, 0);
        if (Input.GetKeyDown(KeyCode.A)) aDown = true;
        else if (Input.GetKeyUp(KeyCode.A)) aDown = false;
        if (Input.GetKeyDown(KeyCode.W)) wDown = true;
        else if (Input.GetKeyUp(KeyCode.W)) wDown = false;
        if (Input.GetKeyDown(KeyCode.S)) sDown = true;
        else if (Input.GetKeyUp(KeyCode.S)) sDown = false;
        if (Input.GetKeyDown(KeyCode.D)) dDown = true;
        else if (Input.GetKeyUp(KeyCode.D)) dDown = false;
        Vector3 vel = new Vector3();
        if (dDown) vel = new Vector3(1, 0, 0);
        else if (aDown) vel = new Vector3(-1, 0, 0);
        else if (wDown) vel = new Vector3(0, 1, 0);
        else if (sDown) vel = new Vector3(0, -1, 0);
    this.transform.position += vel * Time.deltaTime;
}
public void Setup(Sprite sprite, Vector3 position, Vector3 scale)
{
    this.GetComponent<SpriteRenderer>().sprite = sprite;
    this.transform.position = position;
    this.transform.localScale = scale;
}
void OnCollisionEnter2D(Collision2D coll)
{
    Debug.Log("Collision Detected!");
    if (coll.gameObject.name == "pellet")
    {
        coll.gameObject.SetActive(false);
    }
}

}

你知道为什么从来没有调用过OnCollisionEnter2D(…)吗?

OnCollisionEnter2D从未调用

碰撞中涉及的两个对象都需要碰撞器或刚体。

可以将BoxCollider2D、CircleCollider2D类或PolygonCollider2D组件添加到粒子中。对于颗粒,您可能需要CircleCollider2D。

例如,尝试将以下代码添加到For循环中:

go.AddComponent<CircleCollider2D >();