I’m trying to very roughly find the contact point between two 2D trigger colliders using a raycast since triggers don’t give me contact points. I will look into using non-triggers as well but I’d like to know if someone can explain why this is happening with my current trigger setup.
I have a ‘player’ physics object, moved with velocity only. I’m colliding it with a non-moving kinematic ‘obstacle’ object. Both have RigidBody2D and 2D colliders. Both 2D colliders are set to be triggers.
Here’s what I have attached to the obstacle.
{
// player object and this script parameter should have layermask set to the same layer in the inspector
public LayerMask layerMask;
void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.tag == "Player")
{
Debug.DrawLine(transform.position, other.transform.position, Color.yellow, 2f);
RaycastHit2D hit = Physics2D.Raycast(transform.position, other.transform.position, Mathf.Infinity, layerMask);
Debug.Log("RAYCAST HIT: " + hit.collider.ToString());
}
}
}
The trigger works as expected, but hit.collider is sometimes found by the raycast and sometimes returns null depending on the position of the obstacle collider and whether the ‘player’ makes contact from top or bottom.
I’ve attached a package with my setup so you can see the behavior. Hit play on the project as is, with the obstacle positioned off to the side with position.x = 4 and the raycast will only find the collider if the player object has passed the obstacle’s midpoint, and only when the player makes contact on the top of the obstacle (raycast from underneath always returns null).
If you set the obstacle position.x to zero, the behavior changes. The collision again is only detected when the player is over the obstacle, but only when it is near the obstacle midpoint. When it gets some distance away, the raycast no longer finds the player.
Any help or insight as to what is happening is appreciated, thank you!