Peter Gyarmati
Peter Gyarmati

Reputation: 13

Unity Raycast2D problem when the character sitting on the corner

Hi I have a problem with the Raycast2D. When the character sitting on the platform like on the image, the Raycast2D dosen't work. I have tried the Raycast and RaycastAll both. How can I detect the platform under the character when he's on the corner?

https://i.sstatic.net/3aF71.jpg

    if(Input.GetMouseButton(0))
    {
        RaycastHit2D[] hit = Physics2D.RaycastAll(transform.position, -Vector2.up, 2f, layerMask);
        if(hit[0].collider != null)
        {
            Destroy(hit[0].collider.gameObject);
        }
    }

Upvotes: 1

Views: 430

Answers (1)

Savaria
Savaria

Reputation: 565

1) Use multiple raycasts

In your code, the game only detects a platform if the center of your player is standing above it. To detect the platform at all times, you should use two raycasts at the bounds of your character's collider.

void Update()
{
    // Cast the rays
    castRays(transform.localScale.x / 2f);
}

private void castRays(float distanceFromCenter)
{
    // Return if the ray on the left hit something
    if(castRay(new Vector2(-distanceFromCenter, 0f) == true) { return; }
    // Return if the ray on the right hit something
    else if(castRay(new Vector2(distanceFromCenter, 0f) == true) { return; }
}


private bool castRay(Vector2 offset)
{
    RaycastHit2D hit; // Stores the result of the raycast

    // Cast the ray and store the result in hit
    hit = Physics2D.Raycast(transform.position + offset, -Vector2.up, 2f, layerMask);

    // If the ray hit a collider...
    if(hit.collider != null)
    {
        // Destroy it
        Destroy(hit.collider.gameObject);

        // Return true      
        return true;
    }

    // Else, return false
    return false;
}

Optional: You can re-include the ray in the center in case there are platforms smaller than the player or for safety.

2) Use a trigger

Place a BoxCollider2D at the feet of the character and set 'isTrigger' to true. When it enters another collider it will call "OnTriggerEnter2D".

void OnTriggerEnter2D(Collider2D other)
{
    Destroy(other.gameObject);
}

Upvotes: 1

Related Questions