0
\$\begingroup\$

I'm making a 2D game and I'm using a raycast.

I want the raycast to ignore the platform when hitting it from beneath, but not when hitting it from above.

Right now the raycast always hits no matter what side of the platform it touches.

Is there any way to configure the raycast or the platform effector so that they work as I explained?

\$\endgroup\$
1
  • 3
    \$\begingroup\$ What game engine you are using? can you provide a code sample? \$\endgroup\$
    – Barreto
    Mar 19, 2023 at 19:34

1 Answer 1

2
\$\begingroup\$

This example assumes you are using Unity, other game engines might work differently although the concept still applies.

You could to use RaycastAll and check the position of the platform.

This function is similar to the Raycast function but instead of detecting just the first Collider that is hit, an array of all Colliders along the path of the ray is returned.

Create a Tag named something like "Platform" and add it to the platform game object.

Then in code use the above mentioned raycast to check all game objects in the desired direction and check if any are tagged as Platform.

If it's tagged Platform then check its position relative to the origin of the raycast.

Now that you know if its below or above you can act accordingly.

//script on a "player" game object
var hits = Physics2D.RaycastAll(transform.position, Vector2.up, 10);
foreach (var hit in hits)
{
    if (hit.transform.CompareTag("Platform"))
    {
        if (transform.position.y > hit.transform.position.y)
        {
            Debug.Log(hit.transform.gameObject);
        }
    }
    else
    {
        //if its not a platform do something else
        Debug.Log(hit.transform.gameObject);
    }
}

The player is represented by the triangle and the raycast is pointing up.

Example

Now the player is above the platform and the raycast is pointing down.

Example 2

\$\endgroup\$
1
  • 1
    \$\begingroup\$ You may want to use the NonAlloc version if this is something you'll be calling frequently, to reduce pressure on the garbage collector. \$\endgroup\$
    – DMGregory
    Mar 20, 2023 at 17:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .