简体   繁体   English

在unity3d中使用raycast进行块放置

[英]block placement with raycast in unity3d

I'm trying a game like Space Engineers/Minecraft. 我正在尝试太空工程师/我的世界之类的游戏。 with this code, I place a block on the side of a block already placed using raycast. 使用此代码,我将一个块放置在已经使用raycast放置的块的侧面。 It works well until I add a collider(then it place the block anywhere between block and screen). 直到我添加对撞机(然后将块放置在块与屏幕之间的任何位置)之前,它都可以正常工作。 Help with code or another idea, please. 请提供代码或其他想法的帮助。

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

void Update(){ 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;                         
    }
}

} }

Update your Physics.Raycast call to only hit the objects you're interested in. Check the Physics.Raycast documentation about the layerMask parameter to learn how to do this: https://docs.unity3d.com/ScriptReference/Physics.Raycast.html 更新您的Physics.Raycast调用以仅击中您感兴趣的对象。有关layerMask参数的信息,请参阅Physics.Raycast文档,以了解如何执行此操作: https : layerMask 。 HTML

1. Create a layer, and set on block prefab 1.创建一个图层,然后在预制块上进行设置

Use the dropdown menu in the prefab's Inspector window: 使用预制的“检查器”窗口中的下拉菜单:

检查器窗口右上方的下拉菜单突出显示

2. Update call to Physics.Raycast 2.更新对Physics.Raycast的调用

Say you created a new layer named "BlockLayer". 假设您创建了一个名为“ BlockLayer”的新图层。 You would change your Update function to this: 您可以将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;                         
}

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

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