# Question Physics2D.Raycast distance

Discussion in 'Physics' started by behdadsoft, Jan 11, 2024.

Joined:
Aug 25, 2012
Posts:
154
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.

Code (CSharp):
1. var hit = Physics2D.Raycast(transform.position, child.transform.position, 0.2f, 1 << LayerMask.NameToLayer("Player"));
How can this be done?

2. ### Kurt-Dekker

Joined:
Mar 16, 2013
Posts:
39,412
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

### Unity Technologies

Joined:
May 24, 2013
Posts:
11,700
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.