Unity3d 按0会导致对象在其y轴上持续旋转,再次按0会停止该对象吗?
我希望按下按钮0以在y轴上旋转整个对象,当它继续旋转时,直到我再次按下0。我该怎么做 这就是我所拥有的,但它只有在按住0而不是按一次时才起作用Unity3d 按0会导致对象在其y轴上持续旋转,再次按0会停止该对象吗?,unity3d,Unity3d,我希望按下按钮0以在y轴上旋转整个对象,当它继续旋转时,直到我再次按下0。我该怎么做 这就是我所拥有的,但它只有在按住0而不是按一次时才起作用 using System.Collections; using System.Collections.Generic; using UnityEngine; public class rotateYAxis : MonoBehaviour { // Use this for initialization void Start() {
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class rotateYAxis : MonoBehaviour {
// Use this for initialization
void Start() {
}
// Update is called once per frame
void Update() {
bool pressed = false;
if (Input.GetKey(KeyCode.Alpha0))
pressed = true;
if (pressed) {
transform.RotateAround(transform.position, (Vector3.up), Time.deltaTime * 90f);
if (Input.GetKey(KeyCode.Alpha0))
{
pressed = false;
}
}
}
}
更新在每一帧上都被调用,因此您需要存储对象是否应该旋转的一些指示。我们称之为“应旋转”。然后在Update函数的开头,我们检查该状态是否应该更改。之后,如果需要,我们会旋转
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class rotateYAxis : MonoBehaviour {
private bool shouldRotate = false; //should not rotate at the beginning
// Update is called once per frame
void Update() {
if (Input.GetKeyDown(KeyCode.Alpha0)) {
shouldRotate = !shouldRotate; //changing true to false and false to true
}
if (shouldRotate) {
transform.RotateAround(transform.position, (Vector3.up), Time.deltaTime * 90f);
}
}
}
注意:我使用了方法GetKeyDown而不是方法GetKey。GetKeyDown仅在第一次按下按键的帧中返回true。否则,按下按钮时,“shouldRotate”的状态将在每一帧中更改。在每一帧上都会调用Update,因此您需要存储一些对象是否应旋转的指示。我们称之为“应旋转”。然后在Update函数的开头,我们检查该状态是否应该更改。之后,如果需要,我们会旋转
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class rotateYAxis : MonoBehaviour {
private bool shouldRotate = false; //should not rotate at the beginning
// Update is called once per frame
void Update() {
if (Input.GetKeyDown(KeyCode.Alpha0)) {
shouldRotate = !shouldRotate; //changing true to false and false to true
}
if (shouldRotate) {
transform.RotateAround(transform.position, (Vector3.up), Time.deltaTime * 90f);
}
}
}
注意:我使用了方法GetKeyDown而不是方法GetKey。GetKeyDown仅在第一次按下按键的帧中返回true。否则,按下按钮时,“shouldRotate”的状态将在每一帧中改变