Home Game Development unity – Detecting Player by Raycasting

unity – Detecting Player by Raycasting

0
unity – Detecting Player by Raycasting

[ad_1]

You’ve made the identical mistake as on this earlier query: Why is Raycast hitting a masked layer?

Paraphrasing/quoting my reply there:

The downside is that raycast capabilities have so darned many non-compulsory parameters, and LayerMask is not choosy about what kind it is handled as.

From the docs:

public static RaycastHit2D Raycast(
      Vector2 origin, 
      Vector2 path, 
      float distance = Mathf.Infinity, 
      int layerMask = DefaultRaycastLayers, 
      float minDepth = -Mathf.Infinity, 
      float maxDepth = Mathf.Infinity
);

layerMask is the fourth parameter. So in case you present solely three parameters, Unity needs to interpret them as origin, path, and distance.

It would possibly look like offering an enter of kind LayerMask ought to make your intent unambiguous, or a minimum of generate a compile-time error, however LayerMask can implicitly convert to int, and int can implicitly convert to float.

So while you put a LayerMask within the third argument, the compiler tries to transform it to a float, succeeds, and so silently re-interprets your masks as a distance.

If your masks evaluates to a small quantity, like say 1, then you definately get a really brief ray that misses your participant. If it evaluates to a big quantity, you would possibly get a ray lengthy sufficient to hit the participant, however alongside the best way it hits one thing on a non-player layer (for the reason that operate thinks you supplied no layer masks), and returns that as an alternative.

You can repair this by offering a dummy distance worth (say, infinity, if you haven’t any extra conservative higher certain) so your layer masks picks find yourself within the fourth argument the place Unity expects it:

RaycastHit2D raycastHit2D = Physics2D.Raycast(enemyEyes.rework.place, new Vector2(directionOfRay, 0), float.optimisticInfinity, LayerMask.GetMask("Player"));

[ad_2]

LEAVE A REPLY

Please enter your comment!
Please enter your name here