我有一个你需要旋转时钟的游戏。我无法弄清楚如何旋转两个或更多个时钟箭头。箭头不在同一个时钟上。箭头有不同的旋转,他们必须保持旋转差异.IE一个箭头是180另一个90因此在90度转动之后拳头应该是270而另一个是180.这是我的代码:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MoveClock : MonoBehaviour
{
public GameObject root;
public Transform arrow;
public CircleCollider2D circleCollider;
public BoxCollider2D boxColliderTrigger;
public List<MoveClock> connectedClocks;
public GameManger gameManager;
public BoxCollider2D[] colliders;
public int n;
public BoxCollider2D[] disabledTriggers;
public bool equal;
const float initialValue = 90;
static public int k;
public float angle;
public float snapAngle;
public float dif;
public Vector3 mousepos;
public Vector3 dir;
public int[] zAngles;
void Start()
{
zAngles = new int[n];
SetAngles();
CalculateDiffrence();
}
void Update()
{
}
public void MoveArrow(out float snapAngle)
{
snapAngle = 0;
if (Input.GetMouseButton(0))
{
mousepos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
dir = transform.position - mousepos;
angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg + initialValue;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
snapAngle = SnapAngle(angle);
SetAngleTo(angle);
}
}
private void SetAngles()
{
int angle = 360 / n;
for (int i = 0; i < n; i++)
{
zAngles[i] = angle * i;
}
}
private float SnapAngle(float target)
{
float minDiffrence = float.MaxValue;
float closest = float.MaxValue;
for (int i = 0; i < zAngles.Length; i++)
{
float diff = Mathf.Abs(zAngles[i] - target);
if (minDiffrence > diff)
{
minDiffrence = diff;
closest = zAngles[i];
}
}
return closest;
}
public void SetAngleTo(float a)
{
for (int i = 0; i < connectedClocks.Count; i++)
{
if(equal==true)
connectedClocks[i].arrow.rotation = Quaternion.AngleAxis(a, Vector3.forward);
else
connectedClocks[i].arrow.rotation = Quaternion.AngleAxis(a + connectedClocks[i].dif, Vector3.forward);
}
}
public void CalculateDiffrence()
{
for (int i = 0; i < connectedClocks.Count; i++)
{
Vector3 dir = connectedClocks[i].transform.position - transform.position;
dir = connectedClocks[i].transform.InverseTransformDirection(dir);
dif = SnapAngle(Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg+initialValue);
Debug.Log(string.Format("{0} {1}", dif, connectedClocks[i].circleCollider.name));
}
}
}
答案 0 :(得分:1)
只需将其中一个对象作为另一个对象的子对象即可。
A //or B
|__B // |__A
或以编程方式:
A.transform.parent = B.transform; //or
A.transform.SetParent(B.transform);
在此设置中,如果您旋转A任意角度,B将跟随,无需计算并保持代码中的角度差异。