Physics.CheckSphere总是给出错误(Unity3D)

时间:2016-11-08 07:33:26

标签: unity3d game-physics

我试图创建标记我可以访问的单元格的对象。我用红色方块标记它们:

enter image description here enter image description here

我创建对象的代码:

using UnityEngine;
using System.Collections;
using System;

public class SpawnCheck : MonoBehaviour {

    public GameObject checkObject;

    public bool canSpawnCheck = true;
    Vector2 boxSize;

    public GameObject spawnedObject;
    // Use this for initialization
    void Start () {
        Debug.Log("Into spawn check");
    }

    void OnTriggerEnter2D(Collider2D other) {
        Debug.Log("Enter trigger collision");
        canSpawnCheck = false;

        if (other.gameObject.tag == "Target") {
            Debug.Log ("Found Target");
        }

        if (other.gameObject.tag == "Wall") {
            canSpawnCheck = false;
        }

        if (other.gameObject.tag == "Check") {
            canSpawnCheck = false;
        }
    }

    void OnTriggerExit2D(Collider2D other) {
        Debug.Log("Exit trigger collision");
        canSpawnCheck = true;
    }

    // Update is called once per frame
    void Update () {

        Debug.Log ("canSpawnCheck " + canSpawnCheck);

        if (canSpawnCheck == true) {

            Vector3 currentPosition = this.gameObject.transform.position;
            Vector3 spawnPos = new Vector3 (Mathf.Round (currentPosition.x), Mathf.Round (currentPosition.y),0);

            Debug.Log ("Physics.CheckSphere " + Physics.CheckSphere (spawnPos, 5));

            if (!Physics.CheckSphere(spawnPos,5)) {

                spawnedObject = (GameObject)Instantiate (checkObject, spawnPos, Quaternion.identity);

                this.gameObject.GetComponentInParent<AILerp> ().possibleTargets.Add (spawnedObject);
            }
        }

    }
}

我的问题:因为Physics.CheckSphere(spawnPos,5)总是返回false我的代码会生成太多的红色方块并将它们相互产生。我希望红色方块只创建一次,而不是在墙壁上创建(白色方块)。

1 个答案:

答案 0 :(得分:1)

您的检查(克隆) GameObject附加了Box Collider 2D。因此,您必须使用的每个物理函数都应该是Physics2D.something而不是Physics.something。注意那里的关键字&#34; 2D&#34;。

如果仅使用Box Collider而不使用2D,则可以使用Physics.something。因此,Physics.CheckSphere不能与2D对撞机一起使用。

检查(克隆)SpriteRenderer,2D碰撞器是合适的。您只需使用其中一个Physics2D重叠函数,例如Physics2D.OverlapBoxPhysics2D.OverlapAreaPhysics2D.OverlapCircle。你喜欢哪一个。

相关问题