- Home /
use mouse click to pause/stop a transform rotate script on gameobject
use mouse click to pause/stop a transform rotate script on gameobject I've got the simple script below which allows a continuous rotation of my gameobject. Is there a script that i can use that will pause or stop the gameobject rotation when i click on the gameobject?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class RotatingItem : MonoBehaviour { // Start is called before the first frame update void Start() {
}
// Update is called once per frame
void Update()
{
transform.Rotate(new Vector3(0f,50f,0f) * Time.deltaTime);
}
}
Answer by highpockets · Jun 19, 2019 at 10:10 PM
You can simply write up some logic for that:
bool isRotating = true;
void Update()
{
//if left click check if the game object is hit by the mouse and if so, stop it
if (Input.GetMouseButtonDown(0))
{
Vector3 screenPos = Camera.main.WorldToScreenPoint(transform.position);
float allowableVariance = 50.0f;
//if the click is within 50 pixels of the object, stop rotating
if (Mathf.Abs((Input.mousePosition - screenPos).magnitude) <= allowableVariance)
{
if (isRotating)
{
isRotating = false;
}
else
{
isRotating = true;
}
}
}
if (isRotating)
{
transform.Rotate(new Vector3(0,50,0) * Time.deltaTime);
}
}
That script will toggle it (rotation on, rotation off) every time you click close to it.
Your answer
![](https://koobas.hobune.stream/wayback/20220612203437im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Rotate object by clicking on it with animation 1 Answer
What Should i use rigidbody.AddTorque() or Quaternions ? 1 Answer
Max Mouse Clicks Question 0 Answers
Select and save object 1 Answer
Load new scene on object click 1 Answer