How can I check a Linecast across multiple layers, and assign the result to a single bool?
So, I want to have a player that's registered as "grounded"(bool) when he stands on the "Floor" Layer or "GrateFloor" layer.
I use a Linecast to check a hit on the "Floor" layer, and set grounded to true or false based on that. Here's the code:
// The player is grounded if a linecast to the groundcheck position hits anything on the floor layer. grounded = Physics2D.Linecast(player.position, groundCheck.position, 1 << LayerMask.NameToLayer("Floor"));
And it works. But what I need is to have the linecast also check the "GrateFloor" layer, but I'm not sure how. If I try this:
grounded = Physics2D.Linecast(player.position, groundCheck.position, 1 << LayerMask.NameToLayer("Floor") || LayerMask.NameToLayer("GrateFloor"));
or this:
grounded = Physics2D.Linecast(player.position, groundCheck.position, 1 << LayerMask.NameToLayer("Floor") || 1 << LayerMask.NameToLayer("GrateFloor"));
I get errors. If I try this:
grounded = Physics2D.Linecast(player.position, groundCheck.position, 1 << LayerMask.NameToLayer("Floor")); grounded = Physics2D.Linecast(player.position, groundCheck.position, 1 << LayerMask.NameToLayer("GrateFloor"))
one overrides the other.
What's the best way to check more than one Layer, and assign the result to a single variable?
Answer by jgodfrey · Apr 30, 2016 at 07:02 PM
Check the "Combining LayerMasks" section in the accepted answer here:
http://answers.unity3d.com/questions/8715/how-do-i-use-layermasks.html
So, specifically, that'd be something like this:
int mask1 = 1 << Layer$$anonymous$$ask.NameToLayer("Floor");
int mask2 = 1 << Layer$$anonymous$$ask.NameToLayer("GrateFloor");
int combined$$anonymous$$ask = mask1 | mask2;
grounded = Physics2D.Linecast(player.position, groundCheck.position, combined$$anonymous$$ask);
Upvoting for translating the Javascript used in the referenced answer to C# :P