【发布时间】:2018-02-28 14:35:55
【问题描述】:
我知道这个问题是重复的,但我已经尝试了所有其他解决方案,但找不到解决这个问题的方法。我有一堆立方体在一个圆圈中统一设置,我的目标是当有人按住鼠标然后捕捉到某个位置时集体旋转它们。由于有 20 个立方体,我需要它去最近的 18 度(360/20),以便在与原圆相同的位置有一个立方体,只是整个圆都转动了。
我已经让立方体一起旋转,但是当我尝试将它们捕捉到最近的 18 度时,它会捕捉到一个看似随机的点。我尝试过使用不同的方法,但我不知道我哪里出错了!请帮忙!
这是我的代码控制旋转,然后在用户放手后尝试捕捉它(圆圈是所有立方体的父级):
GameObject circle;
void Update(){
if (circle != null) { //if the circle has been assigned, rotate it
circle.transform.Rotate(cam.up, -Input.GetAxis("Mouse X") * rotationSpeed, Space.World);
}
else if (Input.GetMouseButtonDown(0)) { //if clicked, assign the circle
circle = this.GameObject.transform.parent;
}
if (circle != null && Input.GetMouseButtonUp(0)) { //supposed to snap to the right spot, this is the part that isn't working
var rotate = circle.transform.rotation.y;
var newRotate = Mathf.Round((rotate * 360) / 18) * 18;
if (newRotate > 360) { newRotate -= 360; }
else if (newRotate < 0) { newRotate += 360; }
circle.transform.eulerAngles = new Vector3(0, newRotate, 0);
}
}
【问题讨论】:
-
我注意到您从未将
circle设置为 null,即使您放手,第一个if也会始终运行。 -
也许尝试更改本地旋转而不是旋转? docs.unity3d.com/ScriptReference/Transform-localRotation.html