- Home /
Physics.Raycasy not really using Layermask?
I've got the following statement:
bool rayHit = Physics.Raycast(
transform.position, // position of the player
Turret.forward, // the direction the player is aiming
out hitInfo,
Transform.FindObjectOfType<SceneHandler>().TargetingLayerMask); // set to Player and EnemyShip physics layers
I have the TargetingLayerMask set to include ONLY the Player layer, and the EnemyShip layer. I also have a PlayerProjectile layer and an EnemyProjectile layer, both of which are not checked (I set the layers for the mask in the inspector). Despite this, rayhit is true when the ray hits any of the projectiles. I've already verified all the objects are allocated to the correct layers. Rayhit needs to only be true if the player is targeting an enemy or ally. Currently it appears to be true if it hits anything.
What type is ScenaHandler.TargetingLayer$$anonymous$$ask
? Int or Layer$$anonymous$$ask
Layer$$anonymous$$ask is int.
But you must realise that its not 1-32 to select each layer as you might think.
An int is made of 32 bits and each bit represents one of the 32 layers. The int value you enter must represent the bit value 1 of the binary word.
In the diagram there are 32 bits (0s or 1s). The numbers lined to it represent the decimal values of that bit if that bit were to be a 1. The value doubles with each digit to the left.
So layer 4&8 would be 8+128 = 136 Decimal.
Answer by Baste · Feb 11, 2015 at 08:16 AM
Physics.Raycast looks like this:
public static bool Raycast(
Vector3 origin,
Vector3 direction,
RaycastHit hitInfo,
float distance = Mathf.Infinity,
int layerMask = DefaultRaycastLayers);
which means that you're sending in your layer mask as the distance parameter. Since the layermask is an integer (wrapped up in an enum), that's cast to float, and you don't get any compilation errors.
To get the behavior you want, just send in Mathf.Infinity (or float.PositiveInfinity) as the fourth argument, and your layermask as the fifth.
Does the position of the out parameter not matter? Your example doesn't match any of the api reference examples Neither does $$anonymous$$e but I'll give your example a shot.
The position matters. That's not an example I've written, that's the actual declaration of the method as it's in the source.
The distance and layermask parameters has the distance and layermask parameters as optional arguments. This means that if you don't send in the parameters, the default values $$anonymous$$athf.Infinity and DefaultRaycastLayers will be used ins$$anonymous$$d.
in your case, you're sending in your layermask in the position of the distance parameter. You're not sending in anything in the position of the layermask, so the default layermask (hits everything except raycast ignore) will be used.
And you should probably read up on optional arguments, here. They're quite useful. Note that named parameters is something else, but it's in the same article.