我正在寻找一个游戏对象在按下眼球上的触发器时旋转,但只有这样,我有以下代码。不幸的是,即使我把手指从触发器上移开,这也会持续不断
public GameObject dummyrotate;
private bool rotate = false;
float rotationAmount = .3f;
float delaySpeed = .1f;
public void rotateAntiClockwise()
{
StartCoroutine(SlowSpin2());
}
public IEnumerator SlowSpin2()
{
float count = 0;
while (count <= 90)
{
dummyrotate.transform.Rotate(new Vector3(0,-rotationAmount,0));
count += rotationAmount;
yield return new WaitForSeconds(delaySpeed);
}
}
非常感谢Jono
如果你只是想在按住触发器时旋转它,那就不要使用协程。协同程序将一直运行,直到它们完成,所以改为尝试这样的事情:
public GameObject dummyrotate;
private bool rotate = false;
float rotationAmount = .3f;
float delaySpeed = .1f;
void Update()
{
SlowSpin2();
}
public void SlowSpin2()
{
if (rotate == true) {
dummyrotate.transform.Rotate(new Vector3(0,-rotationAmount,0));
count += rotationAmount;
}
}
那么问题是,一旦你触发旋转,你需要30秒来完成你的coroutine
因为你的while循环。而当你再次触发它时,你会开始另一个coroutine
,这将永远像这样继续。我假设每次按下触发器时都会调用rotateAntiClockwise
方法。
我也假设您想要在y轴上旋转90度,您可以像这样实现:
bool isRunning = false;
//Make sure this variable is true when triggered and false when not
bool isTrigger = false;
float rotationAmount = 0.3f;
public IEnumerator SlowSpin2()
{
isRunning = true;
//This will rotate the object continuously until isTriggered is false
while (isTriggered)
{
Debug.Log("Rotating");
transform.Rotate(new Vector3(0, -rotationAmount, 0));
yield return null;
}
Debug.Log(Time.time);
isRunning = false;
}
此脚本将在2秒内将对象从0缓慢旋转到90。
然后你必须像这样修改你的rotateAntiClockwise
,所以当这个已经运行时你不会启动另一个协同程序。
public void rotateAntiClockwise()
{
if(!isRunning)
StartCoroutine(SlowSpin2());
}