Search Unity

2D Collision Detection with Raycast?

Discussion in 'Scripting' started by ChrisX, Mar 23, 2015.

  1. ChrisX

    ChrisX

    Joined:
    Feb 13, 2015
    Posts:
    63
    Hello all!

    I've heard about using Raycast in collision detection as opposed to using the usual collision (to be used in detecting whether you're grounded or not). Since I'm a complete newbie, I am having trouble where to start using that in 2D. Can anyone help me with this? With simple sample codes or something, something just as simple as using Raycast in 2D to detect whether you're on the ground or not?

    Also one more thing. If I use Raycast, how do I use the Debug.DrawRay to draw the Ray I've casted so I can measure the proper distances?

    Thanks.
     
  2. Timelog

    Timelog

    Joined:
    Nov 22, 2014
    Posts:
    528
    Check out this tutorial series from 3DBuzz. They create a 2D game using raycasts for collision detection and also explain in an excellent way why they do it and show how to use Debug.Drawray. They also explain a lot of other systems that are very interesting for future references (including a simple pathed AI).
     
  3. ChrisX

    ChrisX

    Joined:
    Feb 13, 2015
    Posts:
    63
    Which episode is that? The videos seems to be really long each...
     
  4. Timelog

    Timelog

    Joined:
    Nov 22, 2014
    Posts:
    528
    I suggest watching the entire series, as it will take a couple of episodes to implement it.
     
  5. ChrisX

    ChrisX

    Joined:
    Feb 13, 2015
    Posts:
    63
    I reached that raycast part. However, that tutorial seemed a little too bugged, starting from the Vertical movement. See, I implemented the codes he had, but yet I cannot jump at all because he didn't say anything about WHEN to put modify State.IsGrounded so I can jump.... Managed to solve that, but I ended up having infinite jump, while on his part, he's not jumping doubly.

    At least he did solve a bit about the 2D raycast collision detection, though. Still it just bugs me about that jumping problem.
     
  6. ChrisX

    ChrisX

    Joined:
    Feb 13, 2015
    Posts:
    63
    Sorry for double posting. I implemented some of the raycast elements he had, but something bugs me. For reference, I'll put my project in. Hope you have Unity 4.

    The thing is, if I make my raycast touch my own collision, it's like it's counted on hitting the raycast, so the move command is not being executed. If I move the raycast out of the collision, then it'll detect whether it hits something or not, but it causes problem on preventing the character to move to the corner if they're at a certain range from the corner...

    Can anyone help fleshing this out and giving me pointers on how the logic should be implemented? Thanks.
     

    Attached Files: