Home > Net >  how to detect a player in unity when a spotlight hits the player
how to detect a player in unity when a spotlight hits the player

Time:02-05

I'm making a game in unity where I added a spotlight that is constantly rotating at the x-axis and I want the light to detect my player when the light hits the player

i tried raycasting but its just a single line so there is no accuracy

CodePudding user response:

You can have a cone mesh

-> use it as mesh in MeshCollider trigger without any mesh renderer

-> now you basically have an invisible collider object which is a trigger so other objects can still just pass it without actually colliding

-> however, now you can simply check for collider overlapping using e.g.

private void OnTriggerEnter(Collider other)
{
    if(other.TryGetComponent<Player>(out var player)
    {
        Debug.Log("Hey {player}, I see you!");
    }
}

This would be your pre-filter for checking if any further work is required at all - if there is no player at all within this trigger then there is nothing further to check anyway.

Then further checks could e.g. include also checking if there are multiple hit objects, if only the player is in there also nothing else to do as you know you already see the player. If a wall object is closer than the player only then you can do further raycasting checks if maybe you see any edge of the player etc

For example for staters making a raycast on each edge of the player and check if one of those hits the player and not the wall

  • Related