英文:
How to get list of objects at given position with code? Unity3D
问题
我正在制作一个3D瓦片游戏。玩家必须可以自由走在地板瓦片上,但不能移动到墙瓦片上。由于移动与瓦片的大小相同,碰撞检测无法解决这个问题。因此,我想知道玩家试图前往的位置上存在的对象的标签是什么。例如,如果玩家在(2,0,3)处,那么在(3,0,3)处有什么对象或物体?如何使用代码收集这些信息?(如果您有解决玩家移动问题的其他方法,我也会很高兴知道,即使在这种情况下,请告诉我是否有关于获取位置上对象列表的想法)提前感谢您的回答!Eric
英文:
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
答案1
得分: 1
你可以使用Physics.OverlapBox函数。这个函数返回与指定框重叠的碰撞体数组。然后,你可以遍历该数组并使用tag属性获取每个碰撞体的标签。
例如:
// 定义框的大小和中心点
Vector3 boxSize = new Vector3(1, 1, 1);
Vector3 boxCenter = yourPlayerTransform.position;
// 获取与框重叠的碰撞体数组
Collider[] colliders = Physics.OverlapBox(boxCenter, boxSize / 2);
// 遍历数组并获取每个碰撞体的标签
foreach (Collider collider in colliders)
Debug.Log(collider.tag);
英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论