Rotate object continuously on button click Unity3D

主宰稳场 提交于 2019-12-25 04:33:56

问题


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);

            }
    }
}

Please help. Thanks in advance.


回答1:


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);
        }
    }
}


来源:https://stackoverflow.com/questions/31063088/rotate-object-continuously-on-button-click-unity3d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!