I have a script that allows you to rotate an object with the right mouse button.
I would like to make it so that there is a limit to the rotation, so that the object cannot be turned upside down. I was planning to use the condition “Vector3.Dot(transform.up, Vector3.up)” for this, but I don’t know how to do it.
public void Rotate()
{
if (Input.GetMouseButton(1))
{
mPosDelta = Input.mousePosition - mPrevPos;
float value = Vector3.Dot(transform.up, Vector3.up);
value = Mathf.Max(value, 0f);
Debug.Log(value);
transform.Rotate(transform.up, -Vector3.Dot(mPosDelta, Camera.main.transform.right) * rotationSpeed, Space.World);
transform.Rotate(Camera.main.transform.right, Vector3.Dot(mPosDelta, Camera.main.transform.up) * rotationSpeed, Space.World);
}
}
I tried something like this, but it blocks movement completely
Sorry, I read wrong first, now editing my reply. You wanted to restrict the final rotation.
If you use transform.Rotate(), this will rotate the existing transform according to given relative rotation. If you want to restrict the angles, you might want to instead set transform.localRotation = Quaternion.Euler(...) to control the absolute rotation instead of adding to the relative rotation. Then just Mathf.Clamp your absolute rotation’s Y axis.
Test first, in Editor, what are the angles between which you want to allow rotation. The value shown in in your transform in the inspector is the local rotation. Once you know min and max rotation, just make sure that the absolute rotation you are setting is between these values.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseRotate : MonoBehaviour
{
float rotationSpeed=5;
void Update()
{
if (Input.GetMouseButton(1))
{
Quaternion rot=transform.rotation;
transform.Rotate(transform.up,-Input.GetAxisRaw("Mouse X")*rotationSpeed, Space.World);
transform.Rotate(Camera.main.transform.right, Input.GetAxisRaw("Mouse Y")*rotationSpeed, Space.World);
if (Vector3.Dot(transform.up,Vector3.up)<0)
transform.rotation=rot;
}
}
}