- Home /
Question by
theleonn · Dec 19, 2016 at 08:52 PM ·
2drotate objectclamped rotationz axis
Limit rotation of z axis of a 2d object which rotates with mouse click and drag
I have the following script which rotates a 2d object z axis with mouse click and drag, but want to limitate the rotation between 0 and -160...
using UnityEngine;
using System.Collections;
public class ButtonController3 : MonoBehaviour {
private Camera myCam;
private Vector3 screenPos;
private float angleOffset;
void Start () {
myCam = Camera.main;
}
void Update () {
//This fires only on the frame the button is clicked
if (Input.GetMouseButtonDown (0)) {
screenPos = myCam.WorldToScreenPoint (transform.position);
Vector3 v3 = Input.mousePosition - screenPos;
angleOffset = (Mathf.Atan2 (transform.right.y, transform.right.x) - Mathf.Atan2 (v3.y, v3.x)) * Mathf.Rad2Deg;
}
//This fires while the button is pressed down
if (Input.GetMouseButton (0)) {
Vector3 v3 = Input.mousePosition - screenPos;
float angle = Mathf.Atan2 (v3.y, v3.x) * Mathf.Rad2Deg;
transform.eulerAngles = new Vector3 (0, 0, angle + angleOffset);
}
}
}
Comment
Answer by acharyashri · Jul 12, 2018 at 03:22 PM
@theleonn just add a check for value of (angle + angleOffset) before applying the rotation.
using UnityEngine;
using System.Collections;
public class ButtonController3 : MonoBehaviour {
private Camera myCam;
private Vector3 screenPos;
private float angleOffset;
void Start () {
myCam = Camera.main;
}
void Update () {
//This fires only on the frame the button is clicked
if (Input.GetMouseButtonDown (0)) {
screenPos = myCam.WorldToScreenPoint (transform.position);
Vector3 v3 = Input.mousePosition - screenPos;
angleOffset = (Mathf.Atan2 (transform.right.y, transform.right.x) - Mathf.Atan2 (v3.y, v3.x)) * Mathf.Rad2Deg;
}
//This fires while the button is pressed down
if (Input.GetMouseButton (0)) {
Vector3 v3 = Input.mousePosition - screenPos;
float angle = Mathf.Atan2 (v3.y, v3.x) * Mathf.Rad2Deg;
float newAngle = angle + angleOffset;
if (newAngle < 0f && newAngle > -160f)
{
transform.eulerAngles = new Vector3(0, 0, angle + angleOffset);
}
}
}
}