- Home /
Question by
PlasticFrames · Jun 29, 2021 at 02:24 PM ·
transform.positionlookatrotatetowardsquaternion.lookrotationquaternion.slerp
Smooth LookAt OnTriggerEnter for static enemies
Hi,
I've got a very simple setup where enemies are continually rotating until the player enters their range, at which point they need to turn towards the player. I've tried numerous Quaternion rotations and Quaternion.Lerps but the rotation is either instantaneous, in the wrong direction or throws the enemies off their axis entirely.
Any help would be appreciated!
public GameObject player;
[SerializeField] public Vector3 yAngle;
public bool isTriggered = false;
// Start is called before the first frame update
void Start()
{
switchScript = GetComponent<EnemySwitch>();
player = GameObject.FindWithTag("Player");
}
// Update is called once per frame
void Update()
{
if (!isTriggered)
{
transform.Rotate(yAngle, Space.Self);
}
if (isTriggered)
{
transform.LookAt(player.transform.position);
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
isTriggered = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
isTriggered = false;
}
}
Comment
Best Answer
Answer by Hellium · Jun 29, 2021 at 03:51 PM
[SerializeField] private Vector3 yAngle;
[SerializeField] private float targetLookAtRotationSpeed;
private Transform target;
// Update is called once per frame
void Update()
{
if (target != null)
{
Vector3 forward = target.position - transform.position;
forward.y = 0; // Optional but will prevent the object to look up or down
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(forward), targetLookAtRotationSpeed * Time.deltaTime);
}
else
{
transform.Rotate(yAngle * Time.deltaTime);
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
target = other.transform;
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
target = null;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613035626im_/https://answers.unity.com/themes/thub/images/avi.jpg)