Advertisement
JonneOpettaja

Robot.cs

Mar 15th, 2018
401
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.88 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.AI;
  4.  
  5. public class Robot : MonoBehaviour
  6. {
  7.     public float rayLength = 20f;
  8.     GameObject target;
  9.     float startRotation;
  10.     float t = 0;
  11.     public float maxTurnAngle = 45.0f;
  12.     GameObject valonlahde;
  13.     public AudioClip alert;
  14.     GameObject player;
  15.  
  16.     // Use this for initialization
  17.  
  18.     void Start()
  19.     {
  20.         startRotation = transform.rotation.eulerAngles.y;
  21.         valonlahde = GameObject.Find("Hehku");
  22.         player = GameObject.FindWithTag("Player");
  23.     }
  24.  
  25.     // Update is called once per frame
  26.     void Update()
  27.     {
  28.         if (target == null)
  29.         {
  30.             Turn();
  31.             DetectPlayer();
  32.         }
  33.         else
  34.         {
  35.             Move();
  36.         }
  37.     }
  38.  
  39.     void Move()
  40.     {
  41.         NavMeshAgent agent = GetComponent<NavMeshAgent>();
  42.         agent.SetDestination(target.transform.position);
  43.     }
  44.  
  45.     void DetectPlayer()
  46.     {
  47.         Debug.DrawRay(transform.position, transform.forward * rayLength, Color.red);
  48.         RaycastHit hitInfo;
  49.         if (Physics.Raycast(transform.position, transform.forward, out hitInfo, rayLength, 1))
  50.         {
  51.             GameObject hitGameObject = hitInfo.collider.gameObject;
  52.             if (hitGameObject.tag == "Player")
  53.             {
  54.                 target = hitGameObject;
  55.                 valonlahde.GetComponent<Light>().color = Color.red;
  56.                 AudioSource.PlayClipAtPoint(alert, player.transform.position);
  57.             }
  58.         }
  59.     }
  60.  
  61.     void OnCollisionEnter(Collision collision)
  62.     {
  63.         if (collision.gameObject.tag == "Player")
  64.         {
  65.             GameObject.Find("Level").SendMessage("Kill");
  66.         }
  67.     }
  68.  
  69.     void Turn()
  70.     {
  71.         t += Time.deltaTime;
  72.         transform.rotation = Quaternion.Euler(0, startRotation + Mathf.Sin(t) * maxTurnAngle, 0);
  73.     }
  74.  
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement