Home > Blockchain >  How to get list of objects at given position with code? Unity3D
How to get list of objects at given position with code? Unity3D

Time:01-12

I am making a 3d tile game. The player must be free to walk on floor tiles, but should not move to wall tiles. As the movement is the size of the tile, collision detection does not allow solving this. I hence would like to know the tag of the objects present at the position the player is trying to go to. For instance, if the player is at (2,0,3), what object or objects are is at (3,0,3)? How can this be collected with code? (if you have another solution to the player movement problem, I'd be glad to know obout it as well, even in that case please let me know if you have an idea about getting object list at position)

For instance, if the player is at (2,0,3), what object or objects are is at (3,0,3)? How can this be collected with code? (if you have another solution to the player movement problem, I'd be glad to know obout it as well, even in that case please let me know if you have an idea about getting object list at position) Thank you in advance for your answer! Eric

CodePudding user response:

You can use the Physics.OverlapBox function. This function returns an array of colliders that overlap the specified box. You can then iterate through the array and get the tag of each collider using the tag property.

For example:

// Define the size and center of the box
Vector3 boxSize = new Vector3(1, 1, 1);
Vector3 boxCenter = yourPlayerTransform.position;

// Get the array of colliders that overlap the box
Collider[] colliders = Physics.OverlapBox(boxCenter, boxSize / 2);

// Iterate through the array and get the tag of each collider
foreach (Collider collider in colliders)
    Debug.Log(collider.tag);
  • Related