GibTreaty

TurretController.cs

Apr 11th, 2015
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.62 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. public class TurretController : MonoBehaviour {
  4.  
  5.     public ShootingPoint shooter;
  6.  
  7.     public Transform pitchPivot;
  8.     public Transform yawPivot;
  9.  
  10.     public float pitchTurnSpeed = 25;
  11.     public float yawTurnSpeed = 25;
  12.     public float aimAhead = 1;
  13.  
  14.     Vector3 lastTargetPosition = Vector3.zero;
  15.     Transform _target;
  16.     public Transform Target {
  17.         get { return _target; }
  18.         set {
  19.             Transform old = _target;
  20.  
  21.             _target = value;
  22.  
  23.             if(old != Target && Target)
  24.                 lastTargetPosition = Target.position;
  25.         }
  26.     }
  27.  
  28.     public Vector3 AimPosition { get; private set; }
  29.  
  30.     public float yawSpeed;
  31.     public float pitchSpeed;
  32.  
  33.     float TargetPitch {
  34.         get {
  35.             return Target ? Vector3.Dot(Vector3.Cross(pitchPivot.forward, (AimPosition - pitchPivot.position).normalized), pitchPivot.right) : 0;
  36.         }
  37.     }
  38.  
  39.     float TargetYaw {
  40.         get {
  41.             return Target ? Vector3.Dot(Vector3.Cross(yawPivot.forward, (AimPosition - yawPivot.position).normalized), yawPivot.up) : 0;
  42.         }
  43.     }
  44.  
  45.     void Update() {
  46.         if(Target) {
  47.             yawPivot.localRotation = yawPivot.localRotation * Quaternion.Euler(0, TargetYaw * yawTurnSpeed * Time.deltaTime, 0);
  48.             pitchPivot.localRotation = pitchPivot.localRotation * Quaternion.Euler(TargetPitch * pitchTurnSpeed * Time.deltaTime, 0, 0);
  49.  
  50.             if(shooter.IsReady)
  51.                 shooter.Shoot();
  52.         }
  53.     }
  54.  
  55.     void LateUpdate() {
  56.         if(Target) {
  57.             AimPosition = Target.position + (Target.position - lastTargetPosition) * aimAhead;
  58.  
  59.             lastTargetPosition = Target.position;
  60.         }
  61.     }
  62.  
  63.     void OnDrawGizmos() {
  64.         if(Target) {
  65.             Gizmos.color = Color.red;
  66.             Gizmos.DrawLine(shooter.transform.position, AimPosition);
  67.         }
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment