在unity3d中使用raycast进行块放置

时间:2019-07-12 03:15:23

标签: c# unity3d raycasting

我正在尝试类似“太空工程师/我的世界”这样的游戏。 使用此代码,我将一个块放置在已经使用raycast放置的块的侧面。直到我添加对撞机(然后将块放置在块与屏幕之间的任何位置)之前,它都可以正常工作。请提供代码或其他想法的帮助。

RaycastHit hit;
int maxBuildDist = 10;
public GameObject Block;
Vector3 BlockPos;

void Update(){

if(Physics.Raycast(Camera.main.ScreenPointToRay(                                                
    new Vector3((Screen.width / 2 ),(Screen.height / 2),0)),out hit, maxBuildDist)){

        BlockPos = new Vector3(hit.normal.x,hit.normal.y,hit.normal.z);  

        Block.transform.position = (hit.transform.position + BlockPos)/2;                         
    }
}

}

1 个答案:

答案 0 :(得分:2)

更新您的Physics.Raycast调用以仅击中您感兴趣的对象。有关Physics.Raycast参数的layerMask文档,以了解如何执行此操作:https://docs.unity3d.com/ScriptReference/Physics.Raycast.html

1。创建一个图层,并在预制块上设置

使用预制的“检查器”窗口中的下拉菜单:

Dropdown menu in top-right of Inspector window highlighted

2。更新对Physics.Raycast的呼叫

假设您创建了一个名为“ BlockLayer”的新图层。您可以将Update函数更改为此:

// Find the layer based on its name.
var layerId = LayerMask.NameToLayer("BlockLayer");

// Set our mask to "ignore everything except for blocks".
var layerMask = ~layerId;

// Update the Physics.Raycast call - pass in the layer mask
if(Physics.Raycast(
  Camera.main.ScreenPointToRay(new Vector3((Screen.width / 2 ),(Screen.height / 2),0)),
  out hit,
  maxBuildDist,
  layerMask))
{
    // This code will only be reached if the raycast hit a block.
    BlockPos = new Vector3(hit.normal.x,hit.normal.y,hit.normal.z);  
    Block.transform.position = (hit.transform.position + BlockPos)/2;                         
}