Detecting If The Player Is Near A Monster

Updated on March 12, 2018 in [A] Brackeys Courses
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
7 on March 6, 2018

The game I’m working on has monsters that if the player goes in their magic casting range, the player will be slowed down.

 

What I tried to do to accomplish this feature is adding a 2d collision box larger than my monster sprite(the 2d collision box represents their magic casting range), and the player game object already has a 2d collision box. In my player’s script, I used a OnCollisionEnter2D function, and if the player’s collision box hits the monster’s collision box, it detects!

 

however, this is not what I wanted, when the player hits the monster’s collision box, it gets blocked.

 

What I want to create is the player should be able to walk freely near the monster.

 

 

  • Liked by
Reply
2 on March 6, 2018

If you are not using rigidbody change it OnTriggerEnter2D instead of OnCollisionEnter2d.

 

if(col.gameObject.tag == "monster"){
    //Decrease the player speed 
   // Or decrease the Time.timeScale -> This provide nice slowdown effect.
}
 
    //In TriggerExit change the values to normal.

 

 

on March 7, 2018

Hi Screz! Thanks for replying 🙂

I actually put a rigidbody on my player object, but didn’t put one on my monster, will I still be able to use OnTriggerEnter2D?

Also, I already have a OnCollisionEnter2D in my player script, will I be able to use both OnTriggerEnter2D and OnCollisionEnter2D in the same class?

Thanks!

on March 8, 2018

Yes to both.

OnTriggerEnter only requires 1 of the participants to have a Rigidbody.

OnTriggger and OnCollision can be in the same class, but the object will need both a normal collider and a trigger collider for both methods to activate.

 

Show more replies
  • Liked by
Reply
Cancel
3 on March 7, 2018

Instead of giving the monster a collision, you could just check in the update method of the monster for the distance between him and the player:

float monsterRange = 3f;
void Update(){
    Transform player = GameObject.Find("Player").transform;
    if( Vector2.distance( transform.position, player.position )  < monsterRange ){
        //DO YOUR STUFF HERE
    }
}

You can optimize this by finding the player transform just once somewhere else, instead of the update method.

on March 7, 2018

Hi Fetomarcio! Thanks for you reply!

I like this approach a lot, but what if my game randomly spawns the monster all over the map? Would I have lots of monsterRange then?

Thanks!

on March 11, 2018

each monster should have its own monsterRagne attached to it, as a monobehaviour

Devoted
on March 12, 2018

You don’t want to use Find() in an Update function. Leads to trash frame rates. That part of the code should be in a Start function and stored into a global variable.

Show more replies
  • Liked by
Reply
Cancel