【问题标题】:Physics.CheckSphere always give false (Unity3D)Physics.CheckSphere 总是给出错误(Unity3D)
【发布时间】:2016-11-08 19:18:28
【问题描述】:

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

我创建对象的代码:

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,我的代码产生了太多的红色方块,并且它们相互重叠。我希望红色方块只创建一次,永远不要在墙上创建(白色方块)。

【问题讨论】:

  • 我只想指出一件事。您应该使用Equals() 方法而不是==OnTriggerEnter2D 方法中进行字符串比较。
  • 您是否检查过确实有一个或多个碰撞器与由中心 spawnPos 和半径 5 定义的球体重叠?
  • @greenPadawan 我如何检查它?

标签: unity3d game-physics


【解决方案1】:

您的Check(Clone) GameObject 附有Box Collider 2D。因此,您必须使用的每个物理函数都应该是 Physics2D.something 而不是 Physics.something。注意那里的关键字“2D”。

如果您只使用Box Collider 而不使用其中的 2D,那么您可以使用Physics.something。所以,Physics.CheckSphere 不能与 2D 对撞机一起使用。

Check(Clone)SpriteRenderer,适合 2D Collider。您只需要使用Physics2D 重叠函数之一,例如Physics2D.OverlapBoxPhysics2D.OverlapAreaPhysics2D.OverlapCircle。你喜欢哪一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    相关资源
    最近更新 更多