# I need to know if an object is on top a tile. Use ontriggerenter/exit or calculate distances?

Discussion in 'Getting Started' started by cagallo436, Oct 25, 2021.

1. ### cagallo436

Joined:
Oct 12, 2021
Posts:
6
(I attached an image, if that's visible.)

Newbie here. For a sports game, I would like to know if a player is on top of a tile and then trigger a bool. I see two ways of doing it: 1) adding a trigger enter/exit on the tile with a collider and so; or 2) calculate the distances between each player and the tile and, when within boundary distance, trigger the bool.

Taking into account that there are 10 players moving around, what would be the most standard way to proceed? I honestly don't know what is more flexible down the line and what is more effective in terms of performance.

I have the code for the distance calculation below. I also have the on trigger enter/exit but, since probably it's quite common, I'll skip copying to keep the length of this post reasonable.

Code (CSharp):
1. public class testtileboundaries : MonoBehaviour
2. {
3.     public float bound;
4.     public bool isAnyPlayerOnTop;
5.     public testplayer[] allplayers;
6.     public float[] distancextoplayer;
7.     public float[] distanceztoplayer;
8.
9.
10.     void Start()
11.     {
12.         bound = this.transform.localScale.x / 2;
13.         allplayers = GameObject.FindObjectsOfType<testplayer>();
14.         distancextoplayer = new float[allplayers.Length];
15.         distanceztoplayer = new float[allplayers.Length];
16.     }
17.
18.     void Update()
19.     {
20.         for (int i = 0; i < allplayers.Length; i++)
21.         {
22.             distancextoplayer[i] = Mathf.Abs(this.transform.position.x - allplayers[i].transform.position.x);
23.             distanceztoplayer[i] = Mathf.Abs(this.transform.position.z - allplayers[i].transform.position.z);
24.         }
25.
26.         isAnyPlayerOnTop = distancextoplayer.Any(t => t < bound) && distanceztoplayer.Any(t => t < bound);
27.
28.     }
29. }
30.

File size:
11.6 KB
Views:
245