在Unity 3D中沿着特定方向创建对象直到某一点。

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

Creating objects up to a point along a certain direction in unity 3d

问题

我正在制作一个恐怖游戏,其中一部分是一个敌人可以检测到的手电筒。我正在使用一组立方体,怪物将能够检测到它们。我无法弄清楚如何从手电筒到墙壁创建一行这些立方体。

我已经获取了手电筒指向的方向:
hitDirection = (hit.point - flashlight.transform.position).normalized;

以及射线投射的长度(我称之为“rayLength”),使用这个长度创建了以下循环以每米创建一个对象:

for (int i = 0; i < rayLength; i++)
{
    Instantiate(visionCube, new Vector3(), Quaternion.identity);
}

显然,new Vector3 是空的,这是因为我在其中放了一些东西,但似乎没有达到我想要的效果。

英文:

I am making a horror game and part of that is a flashlight that an enemy can detect. I am using a set of cubes that the monster will be able to detect. I can't figure out how to create a line of those cubes from the flashlight to the wall.

I have grabbed the direction the torch is pointing in with:
hitDirection = (hit.point - flashlight.transform.position).normalized;

and the length of the ray cast by grabbing the hit distance (which I called "rayLength")
using that I created this for loop to create the object every metre:

for (int i = 0; i &gt; rayLength; i++)
            {
                Instantiate(visionCube, new Vector3(), Quaternion.identity);
            }
            

Obviously the new Vector3 is empty, this is because I have put a few things in there but nothing seems to do what I want it to.

答案1

得分: 0

使用标准化的方向,将其与距离相乘,然后加上起点。

for (float d = 0; d < rayLength; d += 1.0f)
{
    Instantiate(visionCube, originPosition + hitDirection * d, Quaternion.identity);
}

这将在起点创建一个立方体,以及在该方向上每隔1.0f单位创建一个。您还可以在射线击中点处创建一个最终立方体,因为它可以在上一个创建的立方体之间的任意距离之间,距离范围为0到increment单位。

如果您想更改放置每个立方体的距离,请将d += 1.0f更改为您想要的距离。

英文:

Use the normalized direction and mutliply it by the distance and add the origin.

for (float d = 0; d &lt; rayLength; d += 1.0f)
{
    Instantiate(visionCube, originPosition + hitDirection * d, Quaternion.identity);
}

This will create a cube at the origin, and every 1.0f units away in the direction. You may also want to create a final cube at the ray hit point, since it can be any distance between 0 and increment units from the last box you created.

If you want to change the distance each box is placed, change d += 1.0f to the distance you want.

huangapple
  • 本文由 发表于 2023年6月15日 08:37:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76478380.html
匿名

发表评论

匿名网友

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

确定