- Home /
Other
Clamp rotation of object - Door
Ive tried to find the answer here, but i was not able solve it myself. First of all, im a novice at coding. Trying out Unity for architecture visualization.
Here is what im trying to achive : I use the FPSController to walk around in the scene. I first made a script for opening doors with keydown and animation, with help from a tutorial. Then i figured i wanted to open doors an other way, so i tried makeing a new script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OpenDoorWithScroll : MonoBehaviour
{
public UnityStandardAssets.Characters.FirstPerson.FirstPersonController controller;
public float RotationSpeed = 4f;
public float MaxRotation = -90f;
public float MinRotation = 0f;
void Start()
{
}
void OnMouseDrag()
{
float rotY = Input.GetAxis("Mouse X") * RotationSpeed * Mathf.Deg2Rad;
rotY = (Mathf.Clamp(rotY, -45.0F, 45.0F));
transform.RotateAround(Vector3.up, -rotY);
Debug.Log(rotY);
}
}
The rotation works, but i cant clamp it. So it rotates 360 degrees aroud pivot. The Debug returns low numbers, like : 0.135435 and so on. I would like to clamp it at 90 and 0 as the Variables says, and i would like to add that i have to hold down "E", while dragging, not just drag.
I also want to access the FPSController, to turn off the rotation in the MouseLook script when i start dragging the door open. I figured i could turn off X and Y Sensitivity, but somehow i cant access anything on the FPSController, Except "FPSController.SetActive" when FPScontroller is added as public GameObject. If i dont disable rotation here, the cam turns away from the door while im opening it.
Hopefully someone could give me a hand with this.
Thanks.
Answer by HarshadK · Aug 07, 2017 at 08:45 AM
It is a problem due to unit mismatch. Your rotY
is a value in radian
as you are multiplying your RotationSpeed
with Mathf.Deg2Rad
and you are trying to clamp the rotation in degrees. So you need to clamp the rotation angle in radian itself. So you can multiply your 45 with Mathf.Deg2Rad or use the value of 45 degrees in radian directly, which is pi/4 (i.e. 0.78539816339). So your clamp statement becomes:
rotY = (Mathf.Clamp(rotY, -45.0f * Mathf.Deg2Rad, 45.0f * Mathf.Deg2Rad));
Thank you, for your answer. It still rotates 360 degrees, it kind of only incrased rotation speed when i drag the door.
It tried changing "-45.0f", with the $$anonymous$$ax and $$anonymous$$inRotation Variables, to see if it had any effect when i tried changing the numbers. If i set one to 0, and the other to 90, it would go fast in one direction without dragging it open, just clicking, and no rotation the other direction.
Thank you agein for your time
Works... kinda. It's not you, it's my code. It's spagetti. :P Thank you for being the only person on this platform to have an answer to this problem! :D