在按钮上连续旋转对象,单击Unity3D [英] Rotate object continuously on button click Unity3D
问题描述
我有一个button
和PlayerObject
.当我单击按钮时,对象必须连续旋转,而当我再次单击同一按钮时,对象必须停止旋转.目前,我正在使用下面给出的代码.它使对象仅旋转一次到某个角度.
I have a button
and a PlayerObject
. When I click the button, the object must rotate continuously, and when I click the same button again, the object must stop rotating. Currently, I am using the code given below. It makes the object only rotate once to a certain angle.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
int a=1;
public void CubeRotate () {
a++;
transform.Rotate (new Vector3 (150, 300, 60) * Time.deltaTime);
if (a%2==0) {
Debug.Log(a);
transform.Rotate (new Vector3 (150, 300, 60) * Time.deltaTime);
}
}
}
请帮助.预先感谢.
推荐答案
您需要的是一个非常简单的切换.旋转之所以如此笨拙,是因为它仅在调用CubeRotate()
时运行旋转命令,因此不会像您计划的那样连续旋转 .而是将旋转命令移到Update()
方法中,该方法在每一帧上运行.
What you need is a very simple toggle. The reason your rotation is so clunky though is because it only runs the rotate command when CubeRotate()
is called, thus not rotating continuously like you planned. Instead move the rotation command out into an Update()
method, which runs on every frame.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
protected bool rotate = false;
public void CubeRotate () {
rotate = !rotate;
}
public void Update() {
if(rotate)
{
transform.Rotate (new Vector3 (150, 300, 60) * Time.deltaTime);
}
}
}
这篇关于在按钮上连续旋转对象,单击Unity3D的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!