我试图创建标记我可以访问的单元格的对象。我用红色方块标记它们:
我创建对象的代码:
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
我的代码会生成太多的红色方块并将它们相互产生。我希望红色方块只创建一次,而不是在墙壁上创建(白色方块)。
答案 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.OverlapBox
,Physics2D.OverlapArea
或Physics2D.OverlapCircle
。你喜欢哪一个。