如何解决Unity 2D重叠碰撞器
我正在开发2D点并单击冒险,并且在研磨过程中遇到了2D对撞机的问题。
这是游戏的示例场景:
发生了什么事
- 红色对象:玩家角色。具有一个禁用了运动功能的RigidBody2D和主要运动代码。
- 绿色背景:是角色移动的环境。使用Box Collider 2D并具有OnGroundClick()的事件触发器。
- 紫色对象:是要检测的可交互项。还具有Box Collider 2D和OnInteractableClick()事件触发器。
- 主摄像头具有物理二维射线投射器。
这是播放器的代码:
public NavMeshAgent2D agent;
public float turnSmoothing = 15f;
public float speeddampTime = 0.1f;
public float slowingSpeed = 0.175f;
public float turnSpeedThreshold = 0.5f;
public float inputHoldDelay = 0.5f;
public Rigidbody2D body;
public bool freezeRotation;
private WaitForSeconds inputHoldWait;
private Vector3 destinationPosition;
private Interactables currentInteractable;
private bool handleInput = true;
private const float navMeshSampledistance = 4f;
private const float stopdistanceProportion = 0.1f;
public void OnGroundClick(BaseEventData data)
{
Debug.Log("OnGroundClick");
if (!handleInput)
{
return;
}
currentInteractable = null;
PointerEventData pData = (PointerEventData)data;
NavMeshHit2D hit;
if (NavMesh2D.SamplePosition(pData.pointerCurrentRaycast.worldPosition,out hit,navMeshSampledistance,NavMesh2D.AllAreas))
{
destinationPosition = hit.position;
}
else
{
destinationPosition = pData.pointerCurrentRaycast.worldPosition;
}
agent.SetDestination(destinationPosition);
agent.isstopped = false; //agent.Resume();
}
public void OnInteractableClick(Interactables interactable)
{
Debug.Log("OnInteractableClick");
if (!handleInput)
{
return;
}
currentInteractable = interactable;
destinationPosition = currentInteractable.interactionLocation.position;
agent.SetDestination(destinationPosition);
agent.isstopped = false;
}
注意:NavMesh2D是用于为2D环境创建导航网格物体的第三方资产
我尝试将每个对撞机的z位置更改为无效。
如何分别检测两个对撞机?
解决方法
我在背景的光线投射器中添加了一些细节。将其移至z轴的最远位置,然后修改其代码。
public void OnGroundClick(BaseEventData data)
{
Debug.Log("OnGroundClick");
if (!handleInput)
{
return;
}
currentInteractable = null;
PointerEventData pData = (PointerEventData)data;
Vector3 worldPoint = Camera.main.ScreenToWorldPoint(pData.pointerCurrentRaycast.worldPosition);
worldPoint.z = Camera.main.transform.position.z;
Ray ray = new Ray(worldPoint,new Vector3(0,1));
RaycastHit2D hitInfo = Physics2D.GetRayIntersection(ray);
NavMeshHit2D hit;
if (NavMesh2D.SamplePosition(pData.pointerCurrentRaycast.worldPosition,out hit,navMeshSampleDistance,NavMesh2D.AllAreas))
{
destinationPosition = hit.position;
}
else
{
destinationPosition = pData.pointerCurrentRaycast.worldPosition;
}
agent.SetDestination(destinationPosition);
agent.isStopped = false; //agent.Resume();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。