OnCollisionEnter2D从未调用过

时间:2014-09-08 22:40:18

标签: c# unity3d unity3d-2dtools

所以我的目标是检测pacman何时吃一颗颗粒,但OnCollisionEnter2D方法从未被调用过。我是Unity的新手,很抱歉,如果这是一个简单的解决方案。唯一的' catch'是因为一切都是动态生成的,所以这可能是问题的原因。

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(...)永远不会被调用?

1 个答案:

答案 0 :(得分:1)

碰撞需要对碰撞中涉及的两个物体使用碰撞器或刚体。

您可以将BoxCollider2D,CircleCollider2D类或PolygonCollider2D组件添加到您的弹丸中。对于颗粒,你可能想要一个CircleCollider2D。

例如,尝试将此代码添加到for循环中:

go.AddComponent<CircleCollider2D >();