如何使用代码获取给定位置的对象列表?Unity3D

huangapple go评论84阅读模式
英文:

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);

huangapple
  • 本文由 发表于 2023年1月8日 22:56:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048757.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定