Search Unity

Physics2D.CircleCast - Help Needed

Discussion in 'Scripting' started by matbrummitt, Sep 1, 2014.

  1. matbrummitt

    matbrummitt

    Joined:
    Jan 12, 2010
    Posts:
    107
    Hi all,

    I'm a little stumped on how Physics2D.CircleCast is working and I wonder if anyone can lend a hand.

    Basically in my game the player can click/touch to rope onto the environment. I want the player to be able to touch within range of any ropeable environment object and for the rope to snap to the nearest one (if found). This is so that players don't have to be super precise in order to attach to the terrain.

    I'm setting the rope anchor point to the raycastHit2D.point but this doesn't seem to be a point on the actual environment. The larger I set the circleCast range, the further away from the terrain it seems to latch on to.

    See the attached screenshot for example.

    Code (csharp):
    1.  
    2. privateboolEnvironmentIsInRange (Vector2 pos) {
    3.    
    4.     // pos is the click/mouse position
    5.     // 5f is the range
    6.     // Vector2.zero is because I want the cast to happen directly under the click/touch
    7.     // 1 is the distance to cast over
    8.  
    9.     _environmentHit = newRaycastHit2D();
    10.     _environmentHit = Physics2D.CircleCast(pos, 5f, Vector2.zero, 1, 1 << LayerMask.NameToLayer("Environment"));
    11.     return_environmentHit ? true : false;
    12. }
    13.  
    Thanks

    Mat
     

    Attached Files:

  2. ardizzle

    ardizzle

    Joined:
    Mar 28, 2013
    Posts:
    86
    First thing is that casting a single big circle would be a bad idea I think. I would make a while loop and call it multiple times slowly increasing the cast range until it hits an object. Also make sure its hitting your what it is suppose to. Print the name of what it hits.
     
  3. matbrummitt

    matbrummitt

    Joined:
    Jan 12, 2010
    Posts:
    107
    I'm confident that it's hitting the environment object that I think it is. If I create a primitive sphere at the location of _environmentHit.collider.transform.position it gets positioned at the centre of the terrain as expected.

    I'm surprised I can't cast a large sphere, but I suppose colliders work at their edges. I'll try your suggestion of enlarging the radius over time and hopefully this isn't too inefficient, as it'll have to do multiple raycasts. I suppose if my increments are large enough then raycasts will be minimal.

    Thanks

    Mat