Hi! I have these object on scenes: player (its just a ball) with rigidbody and collider, a object named grappling point, that has a big trigger collider, and some walls with colliders too. My goal is to check, whether there are walls between player and grappling point, when player entering a grappling point’s rigidbody collider. Here is the code: private void OnTriggerEnter2D(Collider2D collision) { float distance = GetComponent<CircleCollider2D>().radius; Vector2 playerPosition = collision.transform.position; RaycastHit2D hit = Physics2D.Raycast(playerPosition, transform.position, distance, layerMask); if (hit) { Debug.Log(hit.collider.gameObject + ": " + hit.collider.transform.position); } }
I create layerMask to avoid ray collide with player’s rigidbody.
When between point and player is no walls it seems to be working fine but when I’m entering in grappling point area behind the wall, debug says to me, that ray didn’t hit the wall! Or, sometimes, it says that another wall was hitten… wall which isn’t between these to objects.
Thanks for help.
@Xkrakz - Make sure you are calculating the direction properly by subtracting the player’s position from the grappling point’s position. Next, double-check your layer mask settings to make sure it’s properly set up for the walls.
Try this for the OnTriggerEnter2D function:
private void OnTriggerEnter2D(Collider2D collision)
{
float distance = GetComponent<CircleCollider2D>().radius;
Vector2 playerPosition = collision.transform.position;
Vector2 direction = (transform.position - playerPosition).normalized;
RaycastHit2D hit = Physics2D.Raycast(playerPosition, direction, distance, layerMask);
if (hit)
{
Debug.Log(hit.collider.gameObject + ": " + hit.collider.transform.position);
}
}
Make sure your layer mask is correctly set up for the walls. You can do this by assigning the walls to a specific layer and then setting the layerMask variable accordingly:
-
In the Unity editor, select your wall objects.
-
In the Inspector, click on the “Layer” dropdown at the top-right corner and choose “Add Layer”.
-
Add a new layer named “Walls” and assign your wall objects to this layer.
-
In your script, define the layerMask variable as follows:
public LayerMask layerMask;
-
In the Unity editor, select the object containing the script and assign the “Walls” layer to the layerMask field in the Inspector.
Let me know if that helps.