Hi!
I am trying to realize a Lego-like constructor. It will work with cubes with different materials. I made a prefab for a cube with this script:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(BoxCollider))]
[RequireComponent(typeof(Rigidbody))]
public class StickScript : MonoBehaviour
{
private Rigidbody myRigid;
public void Start()
{
myRigid = gameObject.GetComponent<Rigidbody>();
}
public void OnCollisionEnter(Collision collision)
{
// all sticky objects have this tag
if (collision.gameObject.tag != "Sticky")
return;
// if we are not connected to other object
foreach (FixedJoint fj in collision.gameObject.GetComponents<FixedJoint>())
{
if (fj.connectedBody == myRigid)
return;
}
var otherRigid = collision.gameObject.GetComponent<Rigidbody>();
// if we didn't connected other object
foreach (FixedJoint fj in gameObject.GetComponents<FixedJoint>())
{
if (fj.connectedBody == otherRigid)
return;
}
// Connecting
collision.gameObject.transform.rotation = gameObject.transform.rotation; // rotating
var joint = gameObject.AddComponent<FixedJoint>();
joint.connectedBody = collision.rigidbody;
}
}
I am rotating the cubes, so they aligned properly… But i didn’t understand how to make cubes to stick aligned: cubes must be connected by edges. Without this, I am getting this:
Can you help me with the position transformation when sticking?
With best regards
P. S. The mechanism of connecting: I am moving this blocks by using Leap Motion - they are rigidbodies, so I can move them by hands