Rotate object continuously on button click Unity3D

2019-08-30 04:09发布

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条回答
狗以群分
2楼-- · 2019-08-30 04:44

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);
        }
    }
}
查看更多
登录 后发表回答