我创建了一个光线投射 2D 以在单击时销毁第一个游戏对象,并创建了第二个光线投射 2D 以在单击时销毁第二个游戏对象。
当我点击第一个游戏对象时,两个游戏对象会同时被销毁,为什么会发生这种情况,我怎样才能让它只摧毁我触摸的对象?
// First gameObject Script
using UnityEngine.EventSystems;
RaycastHit2D hit1Up = Physics2D.CircleCast(transform.position, 0.5f, Vector2.up * 0.35f);
RaycastHit2D hit1Bottom = Physics2D.CircleCast(transform.position, 0.5f, Vector2.down * 0.77f);
Debug.DrawRay(transform.position, Vector3.up * 0.35f, Color.green);
Debug.DrawRay(transform.position, Vector3.down * 0.77f, Color.green);
Ray firstRay = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject())
{
if (hit1Up.collider != null || hit1Bottom.collider != null)
{
if (hit1Up.collider.tag == "TagName1" || hit1Bottom.collider.tag == "TagName1")
{
Debug.Log("You touched TagName1");
destroy(this.gameObject);
}
}
}
// Second gameObject Script
using UnityEngine.EventSystems;
RaycastHit2D hit2Up = Physics2D.CircleCast(transform.position, 0.5f, Vector2.up * 0.35f);
RaycastHit2D hit2Bottom = Physics2D.CircleCast(transform.position, 0.5f, Vector2.down * 0.77f);
Debug.DrawRay(transform.position, Vector3.up * 0.35f, Color.yellow);
Debug.DrawRay(transform.position, Vector3.down * 0.77f, Color.yellow);
Ray secondRay = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject())
{
if (hit2Up.collider != null || hit2Bottom.collider != null)
{
if (hit2Up.collider.tag == "TagName2" || hit2Bottom.collider.tag == "TagName2")
{
Debug.Log("You touched TagName2");
destroy(this.gameObject);
}
}
}
如果(鼠标向下){检查我感兴趣的对象是否存在,然后销毁它}
您的代码没有检查光线是否真的击中了物体!或者,就此而言,甚至进行射线投射,看看他是否准备好了什么。
if (hit2Up.collider != null || hit2Bottom.collider != null)
天哪,我希望在你的代码运行之前这是真的。此检查是无用的。
if (hit2Up.collider.tag == "TagName2" || hit2Bottom.collider.tag == "TagName2")
我认为这要么永远是真的,要么永远是假的。鉴于您的代码正在破坏对象,我怀疑这是真的。此检查是无用的。
你应该做什么:
- 使用
out RaycastHit
参数调用Physics.raycast
(这将包装在 if 语句中,如果您没有点击任何内容,则无需执行任何其他检查) - 检查
hit.collider == hitUp.collider
您也不需要两个脚本,使用两次不同值的相同脚本就足够了。
实现示例:
string tagName;
Update() {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit)) {
if(hit.collider.CompareTag(tagName)) {
Debug.Log("You touched " + tagName);
destroy(hit.collider.gameObject);
}
}
}
注意:如果您使用的是 2D 物理场,则需要分别使用RaycastHit2D
和Physics2D
。2D 和 3D 物理引擎不会以任何方式进行通信。
感谢您@Draco18s的回复,它帮助我通过一些研究提出了我需要的 2D 版本逻辑。干杯!
string tagName1, tagName2;
if (Input.GetMouseButtonDown(0))
{
Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero);
if (hit.collider != null)
{
//Debug.Log(hit.collider.name);
if (hit.collider.CompareTag(tagName1))
{
print(tagName1);
Destroy(hit.collider.gameObject);
} else if (hit.collider.CompareTag(tagName2))
{
print(tagName2);
Destroy(hit.collider.gameObject);
}
}
}