- Home /
Need Help Limiting Rotation on Object's X axis
In my game I have 3d tanks and this script controls the up and down of the gun barrel. And i do not want the gun barrel to rotate all the way around, and i want it to stop at certain points, so how would I go about doing that?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class GunMovement : MonoBehaviour {
public GameObject bobject;
void FixedUpdate () {
if (Input.GetKey ("down")) {
bobject.transform.Rotate (1, 0, 0);
}
if (Input.GetKey ("up")) {
bobject.transform.Rotate (-1, 0, 0);
}
}
}
Answer by Arkaid · Feb 23, 2018 at 04:56 AM
Instead of using relative rotations (that is, rotating one degree up and down from your previous position), use an absolute value with a delta.
Here's something that works. start
is the local rotation at the beginning of the script, xRotation
is the delta value you can rotate from start
. On each update, you clamp the amount rotated by a maximum and minimum value:
public class GunMovement : MonoBehaviour {
public GameObject bobject;
private Quaternion start;
private int xRotation;
private void Start()
{
start = bobject.transform.localRotation;
xRotation = 0;
}
void FixedUpdate()
{
if (Input.GetKey("down"))
{
xRotation++;
}
if (Input.GetKey("up"))
{
xRotation--;
}
// limit the rotation here!
const int MaxAngle = 20;
const int MinAngle = -5;
xRotation = Mathf.Clamp(xRotation, MinAngle, MaxAngle);
// the final rotation will be the start rotation
// combined with the delta values
bobject.transform.localRotation = start * Quaternion.Euler(xRotation, 0, 0);
}
}
If this answer solved your problem, then please mark it as the answer so that this thread can be closed. :-)
Your answer
![](https://koobas.hobune.stream/wayback/20220612153223im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do i rotate player (aeroplane) using A/D keys while moving Left/Right at the same time 1 Answer
How to get all gameObjects with a script on them 1 Answer
How to make an object rotate to raycast hit from mouse? Unity 3D 1 Answer
Smoothly rotating an object to a specific rotation. 1 Answer
What is more efficient for assign rotation with euler angles? 2 Answers