bool PreviewEdition() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { int layerPlug = LayerMask.NameToLayer("Plug"); if (hit.collider.gameObject.layer == layerPlug) { if (previewedObject != null) { return(true); } Transform attachedElement = hit.collider.gameObject.transform.parent; Transform plugPrefab = currentSelection.transform.GetChild(currentPlugIndex); Transform plugged = hit.collider.transform; Vector3 newElementPosition = plugged.position - plugPrefab.position; Vector3 normalPlug = plugPrefab.forward; Vector3 normalPlugged = plugged.forward; Vector3 axisRotation = Vector3.Cross(normalPlug, normalPlugged); if (Vector3.Cross(normalPlug, normalPlugged) == Vector3.zero)//if the forward vectors are in the same direction, any orthogonal axis is valid { /*if(normalPlug != Vector3.up && normalPlug != -Vector3.up) * axisRotation = -Vector3.up; * else * axisRotation = -Vector3.left;*/ if (normalPlug.x != 0) { axisRotation = new Vector3(normalPlug.z / normalPlug.x, 0, 1); } else if (normalPlug.y != 0) { axisRotation = new Vector3(0, normalPlug.z / normalPlug.y, 1); } else//normalPlug.z has to be != 0 { axisRotation = new Vector3(0, 1, normalPlug.y / normalPlug.z); } } previewedObject = Instantiate(currentSelection, newElementPosition, Quaternion.identity); SetObjectKinematic(previewedObject, true); previewedObject.transform.RotateAround(plugged.position, axisRotation, -Vector3.Angle(-normalPlugged, normalPlug)); Transform plug = previewedObject.transform.GetChild(currentPlugIndex); FixedJoint newJoint = plug.gameObject.AddComponent <FixedJoint>(); newJoint.connectedBody = hit.collider.attachedRigidbody; return(true); } else { if (previewedObject != null) { if (!previewedObject.CanInstantiate()) { return(false); } } if (hit.collider.gameObject.name == "Terrain") { return(false); } return(true); } } return(false); }