Search Unity

Raycast2D and collision issues.

Discussion in '2D' started by Carlos_7x, Feb 24, 2017.

  1. Carlos_7x

    Carlos_7x

    Joined:
    Jan 19, 2017
    Posts:
    16
    Hi people, I want to talk about two things.

    First thing:
    I'm developing a logic to determine if the player is touching ground, or if he isn't (he is jumping, or falling). In order to do that, I'm running a Raycast2D function in the Update method:

    Code (CSharp):
    1.         Vector2 originLeft = new Vector2(transform.position.x - 0.464f, transform.position.y + 0.25f);
    2.         Vector2 originRight = new Vector2(transform.position.x + 0.412f, transform.position.y + 0.25f);
    3.  
    4.         Ray ray = new Ray();
    5.         ray.origin = new Vector3(originLeft.x, originLeft.y, transform.position.z);
    6.         ray.direction = Vector2.down;
    7.  
    8.         // Draw methods are only for testing purposes.
    9.         Debug.DrawRay(ray.origin, ray.direction, Color.blue);
    10.         ray.origin = new Vector3(originRight.x, originRight.y, transform.position.z);
    11.         Debug.DrawRay(ray.origin, ray.direction, Color.red);
    12.  
    13.         if (   Physics2D.Raycast(originLeft, Vector2.down, 1f, 1 << LayerMask.NameToLayer("Ground"))
    14.             || Physics2D.Raycast(originRight, Vector2.down, 1f, 1 << LayerMask.NameToLayer("Ground")))
    15.         {
    16.             debugText[1].text = "Is Colliding";
    17.             grounded = true;
    18.         }
    19.         else
    20.         {
    21.             debugText[1].text = "Not Colliding";
    22.             grounded = false;
    23.         }
    It works good! My question is, is there a potential problem that I should be worried about? Is it recommended to raycast in this way?

    Second thing:
    The raycast lines are shown like this:
    image1.png image2.png

    As you can see, if the blue or red line, collide with the ground, then grounded variable is true.

    And the problem happens when I walk towards the left wall with a certain velocity and hit it. Somehow, I assume that my object overlaps the wall (and instantly it goes back to give the feeling that the object can't pass the wall) but it is enough to touch the blue raycast. So that makes my grounded variable to true for just one milisecond.

    Although it seems like it is not a big problem, the thing is that I animate my Megaman sprite with "jumping" frame when grounded is false. So in the scenario that I mentioned, my player is on the air falling, and suddenly the frame is changed to "idle" frame, for one milisecond...

    Any advice on this? I can't move the blue raycast to the right, because it will make grounded = false when the player stands at the edge of a block.

    Thanks!

    PS. The green lines represent the box collider
     
    Last edited: Feb 24, 2017