Hi,
I’m making a lego style VR game using the unity XR framework.
I’ve been struggling for quite a while on how to snap the bricks together, but I’ve come up with an idea of using multiple raycasts emitted from the bottom of the bricks and multiple “pin” colliders on the top to set the snapped bricks at the correct locations. I’ve come up with the following script which works fine, just so long as the bricks rotation is width-way around… When I rotate the brick length-way around the coordinates are all messed up…
using UnityEngine;
public class BlockRaycastTest : MonoBehaviour
{
int layerMask = 1 << 9;
private Vector3 ray1 = new Vector3(-0.012f, 0, -0.004f);
private Vector3 ray2 = new Vector3(-0.012f, 0, 0.004f);
private Vector3 ray3 = new Vector3(-0.004f, 0, -0.004f);
private Vector3 ray4 = new Vector3(-0.004f, 0, 0.004f);
private Vector3 ray5 = new Vector3(0.004f, 0, -0.004f);
private Vector3 ray6 = new Vector3(0.004f, 0, 0.004f);
private Vector3 ray7 = new Vector3(0.012f, 0, -0.004f);
private Vector3 ray8 = new Vector3(0.012f, 0, 0.004f);
public GameObject highlightBrick;
int i;
public RaycastHit[] hit;
public Vector3[] rayPositions;
FixedJoint joint;
void Update()
{
hit = new RaycastHit[8];
rayPositions = new Vector3[] { ray1, ray2, ray3, ray4, ray5, ray6, ray7, ray8 };
i = hit.Length; while (i > 0)
{
i--;
Debug.DrawRay(transform.position + rayPositions[i], transform.TransformDirection(Vector3.down) * 0.01f, Color.green);
if (Physics.Raycast(transform.position + rayPositions[i], Vector3.down, out hit[i], 0.01f, layerMask))
{
Vector3 hitCollider = hit[i].collider.transform.localPosition;
highlightBrick.transform.parent = hit[i].collider.transform.parent;
highlightBrick.transform.localPosition = Vector3.zero;
highlightBrick.transform.localPosition += hitCollider - rayPositions[i];
}
}
}
}
Scene Hierarchy:
XR Rig
2x4_Brick_Prefab (RaycastTest script attached)
. > pin1 (Box Collider (-0.012f, 0, -0.004f))
. > pin2 (Box Collider (-0.012f, 0, 0.004f))
. > pin3 (Box Collider (-0.004f, 0, -0.004f))
. > pin4 (Box Collider (-0.004f, 0, 0.004f))
. > pin5 (Box Collider (-0.004f, 0, 0.004f))
. > pin6 (Box Collider (0.004f, 0, 0.004f))
. > pin7 (Box Collider (0.012f, 0, -0.004f))
. > pin8 (Box Collider (0.012f, 0, 0.004f))
HighlightBrick
