Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Question Physics2D.Raycast distance

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

  1. behdadsoft


    Aug 25, 2012

    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


    Mar 16, 2013
    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:

    "Think of [floating point] as JPEG of numbers." - orionsyndrome on the Unity3D Forums
    behdadsoft likes this.
  3. MelvMay


    Unity Technologies

    May 24, 2013
    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.
    behdadsoft likes this.