我正在构建一个允许拖动和旋转对象的UI。
旋转脚本有效,但是当附加到子元素(UI箭头图标)时,我无法移动父元素。父对象被正确引用并输出到日志。我是否必须参考某种类型的脊体?
儿童旋转课程
public class DragRotate : MonoBehaviour
{
[Header("Degree of rotation offset. *360")]
[Header("Component must be located inside a Control layer - (parent.parent)")]
public float offset = 0.0f;
Vector3 startDragDir;
Vector3 currentDragDir;
Quaternion initialRotation;
float angleFromStart;
//declare parent object
private GameObject myParent;
void Start()
{
//Set parent object two layers up
myParent = transform.parent.parent.gameObject;
Debug.Log("Rotation Object Parent: " + myParent);
}
void OnMouseDown()
{
//get initial coordinance of object and mouse
startDragDir = Camera.main.ScreenToWorldPoint(Input.mousePosition) - myParent.transform.position;
//set initial rotation variable
initialRotation = myParent.transform.rotation;
}
void OnMouseDrag()
{
//calculate mouse vs object location
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - myParent.transform.position;
//convert the vector to one plane
difference.Normalize();
//trig calculation for radian to degree conversion
float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
//set rotation
myParent.transform.rotation = Quaternion.Euler(0f, 0f, rotationZ - (90 + offset));
}
}
家长运动类别(一切都在这里工作)
[RequireComponent(typeof(BoxCollider2D))]
public class DragComponent : MonoBehaviour
{
[Header("Can be dragged by player?")]
[Tooltip("Disable from player being able to drag?")]
private bool canBeDragged = true;
private Vector3 screenPoint;
private Vector3 offset;
void OnMouseDown()
{
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
Debug.Log("Start Drag of: " + transform.name);
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
}
答案 0 :(得分:0)
您不需要存储对父对象的引用。您可以随意使用它:
EditText