- Home /
Question by
KloverGames · Aug 22, 2019 at 03:59 PM ·
rotationrotatemathf.clamp
rotation won't rotate properly
So I want the spaceship to rotate to a certain point and not be able to go further, the problem is whenever I try to rotate back to my default rotation, it just snaps back to -45 degrees and I cant rotate to 45 degrees
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControlScript : MonoBehaviour
{
//RigidBody Controller
public Rigidbody player;
private float leftSpeed = -10f;
private float rightSpeed = 10f;
//Blaster Controller
public GameObject MissileOne;
public Transform MissilePosOne;
private float MissileReload;
void Start()
{
//Blaster Controller
MissileReload = 0f;
}
void FixedUpdate()
{
//RigidBody Controller
if(Input.GetKey("d"))
{
transform.Rotate(-Vector3.forward * 3f);
player.AddForce(rightSpeed, 0, 0);
}
if(Input.GetKey("a"))
{
transform.Rotate(Vector3.forward * 3f);
player.AddForce(leftSpeed, 0, 0);
}
float minRotation = -45;
float maxRotation = 45;
Vector3 currentRotation = transform.localRotation.eulerAngles;
currentRotation.z = Mathf.Clamp(currentRotation.z, minRotation, maxRotation);
transform.localRotation = Quaternion.Euler(currentRotation);
Comment
Answer by Namey5 · Aug 23, 2019 at 06:10 AM
This is because Euler angles are actually in the range of [0,360], rather than [-180,180]. In order to clamp them, you need to remap them into the right range;
Vector3 currentRotation = transform.localRotation.eulerAngles;
currentRotation.z = currentRotation.z > 180f ? -(360f - currentRotation.z) : currentRotation.z;
currentRotation.z = Mathf.Clamp(currentRotation.z, minRotation, maxRotation);
Your answer
Follow this Question
Related Questions
Make sphere rotate when controlled 7 Answers
Strange rotation pattern. 0 Answers
different axis for different objects? 1 Answer
Rotating wrong 0 Answers
How can I rotate an object without moving it up or down? 0 Answers