Challenge With Raycast2D

I handled this challenge of checking if there is a wall by using the raycast2D like this:

 void Update()
    {
        onDrawGizmos();
        wallInFront();
        endOfTerrain();
        myRigidbody2D.velocity = new Vector2(movementSpeed, 0f);
    }

    private void wallInFront(){
        Vector2 position = transform.position;
        Vector2 direction = new Vector2(transform.localScale.x, 0f);

        RaycastHit2D hit = Physics2D.Raycast(position, direction, frontRayDistance, LayerMask.GetMask("Ground"));
        
        if (hit.collider != null) {
            transform.localScale = new Vector3(-transform.localScale.x,1,1);
            movementSpeed *= -1;
        }
    }

    private void endOfTerrain(){
        Vector2 position = transform.position;
        Vector2 direction = new Vector2(transform.localScale.x, -transform.localScale.y);

        RaycastHit2D hit = Physics2D.Raycast(position, direction, diagonalRayDistance, LayerMask.GetMask("Ground"));
        
        if (hit.collider == null) {
            transform.localScale = new Vector3(-transform.localScale.x,1,1);
            movementSpeed *= -1;
        }
    }

    private void onDrawGizmos(){
        Vector2 frontDirection = new Vector2(frontRayDistance * transform.localScale.x, 0f);
        Vector2 diagonalDirection = new Vector2(diagonalRayDistance * transform.localScale.x, diagonalRayDistance * -transform.localScale.y);
        Debug.DrawRay (transform.position, frontDirection, Color.blue);
        Debug.DrawRay (transform.position, diagonalDirection, Color.red);
    }

Hope that can help anyone in other ways.

2 Likes

Great thinking! However, there are near-future problems I see with using Raycast:

  • Add new layer mask conditions
    e.g. 2 enemies pumping each other will flip facing and both go the other way. Raycast must check for layer named “Enemy”;
  • Expand Raycast to check different angles
    e.g. A locked door or obstacles on the same row as the enemy. Raycast must check horizontally.

Both can be cumbersome to be neatly implemented further in codes.
So far, with the solution suggested by Rick, we know we can easily expand the flipping functionality by adding new colliders and changing collision matrix, which will be mostly done in the inspector.

This is a great solution. There are some pros and cons to this approach.

Pros

  • You won’t need to keep adding colliders, which might be annoying in the long run.

Cons

  • With Rick’s approach you can do all sorts of behaviours with just one script. With this approach you’ll be very limited.

There’s also a way to simplify this code. Instead of using two different methods to check for walls and falls, you could use a CircleCast or an OverlapCircle, it basically does the same, but it will check a circular area instead of a point, so it can check for falls and walls at the same time.

Privacy & Terms