Simple Perception System (Unity, C#)

Here is a very simple perception C# code that I used my lecture today for Unity.

Function that can be added to the Enemy class to check if the enemy sees the player object or not (the code for other functionality can be found on the post /2011/10/29/intro-to-gameplay-programming-with-unity/). With this code, an enemy can perceive player object farther away if the player object is front and when rear on the side perseption range is more limited.There is also very simple line-of-sight checking functionality.

The features of the perception system can be controlled via class variables

public float frontRange = 10.0f;
public float frontAngle = 30.0f; // if angle between forward and los is less than this, the target is at front
public float closeRange = 2.0f;

Then the function actually handling the if enemy can see the player object or not.

public bool IsPlayerWithinPerceptionRange()  {
   RaycastHit hit;
   bool playerWithinPerceptionRange = false;
   if(Physics.Linecast(transform.position, GameAgents.GetPlayer().transform.position, out hit)) {
        if(hit.transform == GameAgents.GetPlayer().transform) {
            if(hit.distance <= closeRange) {
                 playerWithinPerceptionRange = true;
                 Debug.DrawLine(transform.position, hit.transform.position, Color.black);
            }
            else if(hit.distance <= frontRange) {
                 if(Vector3.Angle(transform.forward,hit.transform.position - transform.position) <= frontAngle) {
                     playerWithinPerceptionRange = true;
                     Debug.DrawLine(transform.position, hit.transform.position, Color.black);
                 }
            }
         }

    }
    return playerWithinPerceptionRange;
}

Published by lankoski

Petri Lankoski, D.Arts, is a Associate Professor in Game Studies at the school of Communication, Media and IT at the Södertörn University, Sweden. His research focuses on game design, game characters, role-playing, and playing experience. Petri has been concentrating on single-player video games but researched also (multi-player) pnp and live-action role-playing games. This blog focuses on his research on games and related things.

One thought on “Simple Perception System (Unity, C#)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: