Rotating a gameObject while MouseButton/Touch is down

Hi everyone, new to Unity. Hopefully I can format the code correctly on this site.

I am using C# and trying to code the object(Cube) to rotate quickly so long as the user has their finger still touching the object(programming for mobile input). I looked around a bit on the answers and some say that mouseclicks == single touch input?

I have two approaches in mind for this.

  1. So long as the user has the mousebuttondown: rotate the cube; else: stop rotating

  2. If the user clicks/taps once : rotate the cube a random angle, but choosing only from certain angles that show a FACE of the cube

My code for the first approach is as follows:

	void Start () {
	}
	
	// Update is called once per frame
	void Update () {
		// rotate at 90 degrees per second
		if(Input.GetMouseButtonDown(0))
		{
			transform.Rotate(Vector3.up *Time.deltaTime*90);
		}
	}
}

The above code only takes the mouse click input once so it rotates very little and I am suspecting Time.deltaTime*90 is not the brightest choice for the kind of rotation I want.

As for the second approach I still have a hard time figuring out how to rotate it by a random angle. I just started learning a bit of C#.

Oh, this was actually a lot easier than I expected, haha.
If you want to rotate as long a you have your MouseButtonDown, then, instead of using “GetMouseButtonDown(0)” (which only calls once per click)
use “GetMouseButton(0)” (which keeps being entered for as long as the button is down)

Which gives you the code:

void Update () {
    // rotate at 90 degrees per second
    if(Input.GetMouseButton(0))
    {
        transform.Rotate(Vector3.up *Time.deltaTime*90);
    }
}

If you’d like a Random Rotation hur and thur, you can use Random.Range.
Let’s also add a RotationSpeed variable so you won’t have to edit it in multiple different places.
Here’s some quick example code:

public float RotationSpeed = 90f;

void Update () {
    // Enter whilst the Left MouseButton is held down
    if(Input.GetMouseButton(0))
    {
        // Rotate over x, y and z with a speed between 0 and 40 * RotationSpeed
        // Warning: This will give some serious wacky rotating
        // You can get rid of some Axis if you want, turning them to 0, to not rotate over that Axis
        transform.Rotate(Random.Range(0,40) * Time.deltaTime * RotationSpeed,
                         Random.Range(0,40) * Time.deltaTime * RotationSpeed,
                         Random.Range(0,40) * Time.deltaTime * RotationSpeed);
    }
}

I hope that helps, if you have any more specific questions, feel free to ask, otherwise, please accept this answer :slight_smile: