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. 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(){
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
Use the dropdown menu in the prefab's Inspector window:
Say you created a new layer named "BlockLayer". You would change your Update
function to this:
// 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.