I'm developing a 2D point and click adventure and am having issues with the 2D colliders over lapping.
Here is a sample scene of the game:
What's going on:
This is the code for the player:
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;
}
Note: NavMesh2D is a third party asset for creating nav meshes for 2D environments
I have tried changed the z position on each collider to no effect.
How can I detect both colliders individually?
I added some details to the raycaster for the background. Moving it to the far back of the z axis, I then modified it's code.
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, 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();
}