Advertisement
KRecordZ

UnityRotateToObject2

Apr 9th, 2020
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.16 KB | None | 0 0
  1.  using UnityEngine;
  2.      using System.Collections;
  3.      
  4.      public class Test : MonoBehaviour
  5.      {
  6.      
  7.          public GameObject[] target;
  8.          public float objectDistance;
  9.          public float rotationDamping;
  10.      
  11.          void Start()
  12.          {
  13.      
  14.              target = GameObject.FindGameObjectsWithTag("Enemy");     //It will look for all objects tagged as "Enemy"
  15.      
  16.          }
  17.      
  18.          void Update()
  19.          {
  20.              for (var i = 0; i < target.Length; i++)
  21.              {
  22.                  objectDistance = Vector3.Distance(target[i].transform.position, transform.position);
  23.      
  24.                  if (objectDistance < 20f)
  25.                  {
  26.                      lookAtPlayer();
  27.                  }
  28.              }
  29.          }
  30.      
  31.          void lookAtPlayer()
  32.          {
  33.              for (var i = 0; i < target.Length; i++)
  34.              {
  35.                  Quaternion rotation = Quaternion.LookRotation(target[i].transform.position - transform.position);
  36.                  transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * rotationDamping);
  37.              }
  38.          }
  39.      }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement