Physics2D.Raycast distance

Hi.

I wrote this following code for detect collision between player and enemy when distance is 0.2f.
I want the Ray collision to occur only when the distance between the player and the enemy is 0.2. That is, if this distance is less or more, the collision will not be done.

var hit = Physics2D.Raycast(transform.position, child.transform.position, 0.2f, 1 << LayerMask.NameToLayer("Player"));

How can this be done?

You would need to do two checks, giving slightly-different values on either side of 0.2f, and see which ones hit.

If both hit or if both miss, the object is either too close or too far.

Keep in mind the distance will almost certainly never actually be 0.2f.

Floating (float) point imprecision:

Never test floating point (float) quantities for equality / inequality. Here’s why:

https://starmanta.gitbooks.io/unitytipsredux/content/floating-point.html

“Think of [floating point] as JPEG of numbers.” - orionsyndrome on the Unity3D Forums

1 Like

Look at the docs, the 2nd argument is not a world position, it’s a direction.

If you want to detect contacts between two points then you use Physics2D.LineCast.

It’s not clear if you’re interested in the distance between potential contacts or not because a ray from the player position to an enemy position would give you the distance from the player center to a contact which is an odd arbitrary value. Why not just use the distance i.e. magnitude of the vector (enemy position - player position)?

Alternately, use Physics2D.Distance, Collider2D.Distance, Rigidbody2D.Distance to ask what the nearest contact points are and use the distance between those which is accurate if you need it.

1 Like