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.