[英]Unity2d: How to rotate a parent object from within a child object?
我正在構建允許拖動和旋轉對象的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;
}
}
您不需要存儲對父對象的引用。 您可以像這樣在旅途中使用它:
void OnMouseDown()
{
initialRotation = transform.parent.rotation;
}
void OnMouseDrag()
{
transform.parent.rotation = Quaternion.Euler(0f, 0f, rotationZ - (90 + offset));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.