1
\$\begingroup\$

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 :

 RaycastHit2D hit = Physics2D.Raycast (wallCheck.position, Vector2.right, wallCheckDistance);

     if (Physics2D.Raycast (wallCheck.position, Vector2.right, wallCheckDistance)) {
         Debug.Log ("collider name : " + hit.collider.name);
         isDead = true;
     }

     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.

enter image description here

For this game, I want to do game over if wallCheck object detect any object in collision.

Why wallCheck object detecting collision of ground object (stage1a)? That is big question of mine.

\$\endgroup\$
1
\$\begingroup\$

you can add the walls to there own Layer;

LayerMask wallLayer;

    if(Physics2D.Raycast(wallCheckPosition,Vector2.right, wallCheckDistance, wallLayer))
    {
        //Hit wall call GameOver()
    }

I prefer using Physics2D.OverlapCircle to set a radius rather than direction. ex.

    if (Physics2D.OverlapCircle(wallCheck.position, checkRadius, wallLayer))
    {
        //Hit wall call GameOver()
    }

you can also use the same method to detect other things like your barrels or ladders, ect.. or in your case you could just set any object that will end the game to a killLayer or something. then when the player touches within range of the checkRadius it will execute GameOver();

\$\endgroup\$
  • \$\begingroup\$ Awesome reply...:) I have changed my wall object layer compare to ground object layer. problem is completely resolved. \$\endgroup\$ – Siddharth Nov 8 '15 at 7:05
0
\$\begingroup\$

Why are you casting the ray twice? First cast the ray:

RaycastHit2D hit = Physics2D.Raycast (wallCheck.position, Vector2.right, wallCheckDistance);

Then, verify if anything is hit:

if (hit.collider != null)
{
    ... // Do collision reaction. Death, in your case
}
\$\endgroup\$
  • \$\begingroup\$ Those 2 casting are for testing only. I know about that but for detecting which object is collided with player. \$\endgroup\$ – Siddharth Nov 6 '15 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.