I’m trying to cast a box upwards in order to make the sprite transparent when the player is above it but I don’t understand how to use Unity - Scripting API: Physics2D and there doesn’t seem to exist method of visualizing the box. All I want to do is check if the player is on the tile above the snow/crate sprites.
Here’s my code for casting the box:
var hit = Physics2D.BoxCast(transform.position, new Vector2(1f, 1f), 180f, Vector2.up, 1f, 1);
First of all I think this code has to be in the Player object, so it won’t check 500 times if there’s something above every box.
Then if you want to visualize your box just une OnDrawGizmos() and call that with the same property:
and finally if your code doesn’t work properly for me it’s because of the Layer (the last parameter).
just use a public LayerMask variable and set the layer you want to check in it, and use this variable in the last parameter.
Well, I solved the issue by making a Raycast2D at the center of the grid and that works. I’m going to stick with the Raycast2D unless something changes and I’ll need to switch.
I’m gonna move this in the player or a separate class when I have the time.
private void Update()
{
var position = transform.position;
/* RayCast from the center of the tile up one distance and set layerMask to Player only! */
var hit = Physics2D.Raycast(new Vector2(position.x + .5f, position.y + 0.5f),
Vector2.up, 1f, 1 << 15);
if (hit.collider)
{
BecomeTransparent();
}
else
{
BecomeOpaque();
}
}