Sunday, October 30, 2022
HomeGame Developmentunity - Detecting Participant by Raycasting

unity – Detecting Participant by Raycasting


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

Paraphrasing/quoting my reply there:

The issue is that raycast features have so darned many elective parameters, and LayerMask is not choosy about what sort it is handled as.

From the docs:

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

layerMask is the fourth parameter. So for those who present solely three parameters, Unity needs to interpret them as origin, route, and distance.

It’d look like offering an enter of sort LayerMask ought to make your intent unambiguous, or not less than generate a compile-time error, however LayerMask can implicitly convert to int, and int can implicitly convert to float.

So if 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.

In case your masks evaluates to a small quantity, like say 1, you then get a really brief ray that misses your participant. If it evaluates to a big quantity, you may get a ray lengthy sufficient to hit the participant, however alongside the way in which it hits one thing on a non-player layer (for the reason that perform thinks you offered no layer masks), and returns that as an alternative.

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

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

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments