Cant Clamp Lerp

Ive tried for very long to do this and really, really cant do it myself because its too complicated and i dont like rotation and stuff. I am making a turret and making it rotate towards a player. The thing is, it is not supposed to look at a certain angle, like be able to rotate between -230 degrees and 30. Its like a dead angle where the turret cant shoot you.

This is my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TurretScript : MonoBehaviour
{
    List<Transform> PeopleList = new List<Transform>();
    List<Transform> TargetList = new List<Transform>();
    Transform Target;
    public LayerMask whatIsPlayer;
    public float range, FireRate, BulletSpeed, MinRot, MaxRot, Dmg, RotationSpeed;
    public Transform Bullet, AttackPoint;
    public ParticleSystem MuzzleFlashFX;
    float RegenCellTimer;
    bool IsReadyToShoot = true;

    public List<AudioClip> SoundList = new List<AudioClip>();
    public AudioSource SoundSource;

    // Update is called once per frame
    void Update()
    {
        Collider[] PlayersHit = Physics.OverlapSphere(transform.position, range, whatIsPlayer);
    
        float minDist = Mathf.Infinity;
        Vector3 currentPos = transform.position;
        if (PlayersHit.Length >= 2) {
            foreach (Collider t in PlayersHit)
            {
                float dist = Vector3.Distance(t.transform.position, currentPos);
                if (dist < minDist)
                {
                    if (t == true) {
                        Target = t.transform;
                    }
                    
                    minDist = dist;
                }
            }
        }
        else if (PlayersHit.Length == 1) {
            Target = PlayersHit[0].transform;
        }
        else {
            Target = null;
        }
        
        
        Vector3 r = Quaternion.LookRotation(Target.position - transform.position, Vector3.up).eulerAngles;
        if (r.x > 180) r.x -= 360;
        r.x = Mathf.Clamp(r.x, MinRot, MaxRot);
        Quaternion TargetRotation = Quaternion.Euler(r.x, r.y, r.z);
        

        // Smoothly rotate towards the target point.
        transform.rotation = Quaternion.Lerp(transform.rotation, TargetRotation, RotationSpeed * Time.deltaTime);
        
        

        if (IsReadyToShoot) {
            
            if (Target) {
                Transform CurrentBullet = Instantiate(Bullet, AttackPoint.position, AttackPoint.rotation);
                CurrentBullet.GetComponent<BulletScript>().SetDmg(Dmg);
                MuzzleFlashFX.Play(true);
                

                CurrentBullet.GetComponent<Rigidbody>().AddForce(CurrentBullet.forward * BulletSpeed, ForceMode.Impulse);
                SoundSource.PlayOneShot(SoundList[Random.Range(0, SoundList.Count)]);
                IsReadyToShoot = false;
                Invoke ("ResetShoot", FireRate);
            }
                
                
        }
        
    }
    void ResetShoot () {
        IsReadyToShoot = true;
    }
}

You can see i tried alot at line 33 and a little downwards. Thanks alot i hope ill get help because i really cant figure it out.

Your best bet is to have local-only float variables to represent traverse and elevation, then change and clamp those floats, and finally drive .localRotation of the parts on their correct Transform axis.

Notes on clamping rotations and NOT using .eulerAngles because of gimbal lock:

All about Euler angles and rotations, by StarManta:

https://starmanta.gitbooks.io/unitytipsredux/content/second-question.html

Shouldn’t you be clamping the Y axis and not the X axis?.

But either way, you should make the turret a child of another object so then when the turret’s local rotation is set to 0,0,0 it will be facing forwards relative to the parent object. This will also allow you to place turrets facing in different directions by rotating the parent objects without effecting each turret’s local rotation.

You can then rotate and clamp the turret’s local rotation like this:

using UnityEngine;
public class LookClamp : MonoBehaviour // Looks towards target but with a limited range.
{
    public Transform target;
    void Update()
    {
        transform.rotation=Quaternion.Slerp(transform.rotation,Quaternion.LookRotation(target.position-transform.position),5*Time.deltaTime);
        transform.localEulerAngles=new Vector3(transform.localEulerAngles.x,Mathf.Clamp(Mathf.DeltaAngle(0,transform.localEulerAngles.y),-70,70),0); // clamp angle y
    }
}

Thanks alot for the suprisingly quick answer but could you show me how it would work in my script? Im not that good at scripting with directions and rotations so i dont exactly understand this gibberish. Could i at least have an example please. Im really stuck so please help.

That’s unfortunate. It’s really pretty easy to understand and it actually all makes sense, but you DO need to make the effort, no matter how long it takes.

Otherwise you’re not really making the game, are you?

I suggest starting with some Youtube tutorials for things like what you contemplate. There are many gun turret and gun AI aiming tutorials out there.

If you are not able to grasp it from a Youtube tutorial, I guarantee you won’t grasp it from this little tiny text box!!!

Two steps to tutorials and / or example code:

  1. do them perfectly, to the letter (zero typos, including punctuation and capitalization)
  2. stop and understand each step to understand what is going on.

If you go past anything that you don’t understand, then you’re just mimicking what you saw without actually learning, essentially wasting your own time. It’s only two steps. Don’t skip either step.

Check my attempt at auto-aiming turrets here.

It’s packed with features (although you can scroll up and see it develop from the beginning), but if it helps what you want is likely in the Update method (rotation quaternion decomposition to pitch & yaw + “clamping”).

Ive already tried and this was my last resort. Ive tried watching tutorials and figuring it out by myself but really couldnt. I need a defenitive answer because I dont have a plan C.