c# - 如何检测精灵是否与任何背景精灵重叠?
问题描述
背景对象被标记为“背景”并且位于“背景”层中。
目前,Debug.log 语句总是说“不检测背景”。我尝试了几次将光线投射的方向从后切换到前,但这并没有解决问题。射出射线的游戏对象的 z 位置为 -1,精灵的 z 位置为 0。精灵上有一个 2D 盒子碰撞器。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RoomMaker : MonoBehaviour
{
public float speed = 5;
public float distance = 5;
public Transform horse;
public Transform carriage;
void Update()
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
RaycastHit2D backgroundInfo = Physics2D.Raycast(horse.position, Vector3.forward, distance);
if (backgroundInfo)
{
Debug.Log("DETECTSBACKGROUND");
}
else
{
Debug.Log("Does not detect Background");
//it always displays this one, it never displays the other debug.log
}
}
}
解决方案
考虑使用Physics2D.OverlapPointAll代替光线投射。
这将要求背景精灵Collider2D
在其游戏对象上具有组件,它们的游戏对象被标记Background
并位于background
图层上。
我建议让background
图层忽略与所有内容的冲突。有关如何执行此操作的更多信息,请参阅物理 2d 选项文档。
下面是代码的样子:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RoomMaker : MonoBehaviour
{
public float speed = 5;
public float distance = 5;
public Transform horse;
public Transform carriage;
void FixedUpdate() // otherwise, visual lag can make for inconsistent collision checking.
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
Collider2D[] cols = Physics2D.OverlapPointAll(
Vector3.Scale(new Vector3(1,1,0), horse.position), // background at z=0
LayerMask.GetMask("background")); // ignore non background layer objects
Collider2D backgroundCol = null;
for (int i = 0 ; i < cols.Length ; i++) // order of increasing z value
{
if (cols[i].tag == "Background") // may be redundant with layer mask
{
backgroundCol = cols[i];
break;
}
}
if (backgroundCol != null)
{
Debug.Log("DETECTSBACKGROUND: " + backgroundCol.name);
}
else
{
Debug.Log("Does not detect Background");
}
}
}
我用这个设置进行了测试:
推荐阅读
- sql - laravel DB连接中的数组到字符串转换
- php - 在php中使用数组和关联数组创建数组数组的有效方法
- android - 导航组件共享元素转换适用于输入,但不适用于弹回
- r - 如何以快速(并行)方式正确地将函数应用于每一行
- react-native - 无法运行-android,因为无法解析 POM https://dl.google.com/dl/android/maven2/android/arch/lifecycle/runtime/1.1.1/runtime-1.1.1.pom
- mysql - 我该怎么做这个 SQL 查询?
- java - 如何将 StickyHeaders 添加到 recyclerView?
- ios - SwiftyJSON 响应中的 for 循环
- html - 有没有办法让我的复选框使用引导程序与固定数字水平对齐?
- python - 如何在 python 中处理“HTTP 错误 502”?