简体   繁体   English

Unity3D Raycasting

[英]Unity3D Raycasting

Writing a C# script that allow player to construct with simple blocks. 编写允许玩家使用简单块构建的C#脚本。 For this reason, I strike a raycast forward from playercam. 出于这个原因,我从playercam向前投射光线。 When ray hit some object - I get the collison world coords with hit.point If I Instantiate a constructing block on that coordinates - it will be created overlapping with other objects. 当光线撞击某个物体时 - 我得到了与hit.point的collison世界坐标。如果我在该坐标上实例化一个构造块 - 它将与其他对象重叠。 I have to change coords. 我必须改变坐标。

在此输入图像描述

How can I get the point that lay as shown in the picture above? 我怎样才能得到如上图所示的点? This will allow me to calculate created blocks' coordinates 这将允许我计算创建的块的坐标

You can take the RaycastHit's point property and move out along the intersected face's normal to your block's extent (half its width; if it's a unit cube, this will be 0.5f); 您可以使用RaycastHit的point属性,沿着交叉面的法线移动到块的范围内(宽度的一半;如果是单位立方体,则为0.5f); something like this: 这样的事情:

if (Input.GetMouseButtonDown (0)) {
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    RaycastHit hit;
    if (Physics.Raycast (ray, out hit)) {
        Instantiate (prefab, hit.point + hit.normal * blockExtent, hit.transform.rotation);
    }
}

This will instantiate your new block at the raycast's intersection point (you'd need to calculate the center of the intersected face if you wanted them to align precisely), and inherit the rotation of the intersected GameObject. 这将在光线投射的交叉点处实例化您的新块(如果您希望它们精确对齐,则需要计算相交面的中心),并继承相交的GameObject的旋转。

Note that this won't prevent a new block from spawning inside an existing block; 请注意,这不会阻止新块在现有块内生成; it will just keep it from spawning inside the block that you raycasted against. 它只会阻止它在你发射光线的区域内产生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM