- Home /
Restricting rotation on an axis
Okay, So I have a turret. On this turret the base rotates around the Y axis, facing the target and the GUN the sort of barrel of the turret which is a separate game object rotates on the X axis facing the target. This works beautifully, my only issue comes in when I try to restrict the turrets rotation. If you look at the photo I included (Sorry it's so rough) I want the turret to be able to look at the target from 0-45 X so that it doesn't look into the floor and so that it never has to look straight up.
Here is my Code:
using UnityEngine;
using System.Collections;
public class TurretTargeting : MonoBehaviour {
GameObject turretBase;
GameObject turretGun;
public Transform target;
public bool clamp;
public float c1, c2;
private float x = 0.0f;
// Use this for initialization
void Start()
{
turretBase = transform.FindChild("Turret_Base").gameObject;
turretGun = turretBase.transform.FindChild("Turret_Gun").gameObject;
x = turretGun.transform.eulerAngles.x;
}
// Update is called once per frame
void Update()
{
if (target != null)
{
Vector3 dir = target.transform.position - turretBase.transform.position;
Vector3 dir1 = target.transform.position - turretGun.transform.position;
Quaternion lookRot = Quaternion.LookRotation(dir);
Quaternion lookRot1 = Quaternion.LookRotation(dir1);
//This doesnt work at all.
if (clamp)
{
x = ClampAngle(x, -c1, c2);
lookRot1.x = x;
}
turretBase.transform.rotation = Quaternion.Euler(0, lookRot.eulerAngles.y, 0);
turretGun.transform.localRotation = Quaternion.Euler(lookRot1.eulerAngles.x, 0, 0);
//-----------------------
}
else
{
turretBase.transform.rotation = new Quaternion(0, 0, 0, 0);
turretGun.transform.rotation = new Quaternion(0, 0, 0, 0);
}
}
float ClampAngle(float angle, float min, float max)
{
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp(angle, min, max);
}
}
I have been trying to wrap my head around this for hours with no results, so if anyone has any solutions please help.
Photo I Mentioned.
Your answer
Follow this Question
Related Questions
Rotating a character along the x and z-axis to align with a vector3 direction. 1 Answer
Making an object realistically rebound off walls 1 Answer
How to make a gameobject have a rotation constraint? 1 Answer
How can I replace this Vector3 with a float? 2 Answers
How do I align my player transform to waypoints and without restricting Z Axis rotation? 2 Answers