Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Wall checking not working correctly

Discussion in '2D' started by siddharth3322, Nov 5, 2015.

  1. siddharth3322

    siddharth3322

    Joined:
    Nov 29, 2013
    Posts:
    1,049
    Basically I am working on side scrolling 2d game. For that I want to check whether player is collided with wall. I have written some code for it but can't able to decide where I have done stupid mistake. So please guide me in this. If you need any more details then I am always available.

    Code for detecting wall :

    Code (CSharp):
    1. RaycastHit2D hit = Physics2D.Raycast (wallCheck.position, Vector2.right, wallCheckDistance);
    2.  
    3.         if (Physics2D.Raycast (wallCheck.position, Vector2.right, wallCheckDistance)) {
    4.             Debug.Log ("collider name : " + hit.collider.name);
    5.             isDead = true;
    6.         }
    7.  
    8.         Debug.DrawRay (wallCheck.position, Vector3.right * wallCheckDistance, Color.red);
    Following image gives you all idea about situation. In that I have allocated player with groundCheck and wallCheck flag. At present in wallCheck section, I am detecting ground as collider response after execution of above code. Above code I have placed in Update method for continuous checking.

    Screen Shot 2015-11-05 at 10.22.17 pm.png
     
  2. siddharth3322

    siddharth3322

    Joined:
    Nov 29, 2013
    Posts:
    1,049
    Why wallCheck object detecting collision of ground object (stage1a)?
    That is big question of mine. Please someone give me reply of this.
     
  3. RemDust

    RemDust

    Joined:
    Aug 28, 2015
    Posts:
    431
    interested in this too !
    isn't it possible that your "Vector2.right" doesnt actually point to the right direction ?
    I mean, "right" for you might not be "right" for your ingame world space.
    By the way, in your debug, you're using vector3 while you use vector2 in your cast, maybe what you see is not what you really get from your raycast...
     
  4. AlanGameDev

    AlanGameDev

    Joined:
    Jun 30, 2012
    Posts:
    437
    Few things to clarify...
    Why are you raycasting twice? Just use 'hit' since it's exactly the same thing.
    Also, just a guess, but perhaps you dropped a wrong object in the inspector, or somehow the names aren't correct. I don't see why the example wouldn't work.
    Also, considering it's a very simple interaction, perhaps you could make an sscce... possibly that will allow you to debug and fix the problem yourself.

    Edit: Something you can try is drawing a line from the origin to the hit point. That way you'll be able to see exactly where the ray is hitting.
     
    Last edited: Nov 27, 2015