Transform.LookAt also changes position
Title says it all.
I provided an NPC with the following script, which should make him look and bark at the player. When the player comes into the NPC's reach, however, the NPC starts walking towards the player instead of just facing him.
Any thoughts?
using UnityEngine;
public class Barking : MonoBehaviour {
public AudioSource barkingAudio;
private GameObject player;
private bool barking;
void Start () {
player = GameObject.FindGameObjectWithTag("Player");
barking = false;
}
void Update () {
if (barking)
lookAtPlayer();
}
private void lookAtPlayer()
{
transform.LookAt(player.transform.position, Vector3.up);
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject == player)
{
barking = true;
barkingAudio.mute = false;
barkingAudio.Play();
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject == player) {
barking = false;
barkingAudio.mute = true;
barkingAudio.Stop();
}
}
}
Answer by Kattoor · Oct 28, 2015 at 09:41 AM
Solution:
Replacing the transform.lookAt with:
var qTo = Quaternion.LookRotation(player.transform.position - transform.position);
qTo = Quaternion.Slerp(transform.rotation, qTo, 10 * Time.deltaTime);
GetComponent<Rigidbody>().MoveRotation(qTo);
The weird behaviour had something to do with using a rigidbody AND manually changing the transform (via lookAt).
Your answer
Follow this Question
Related Questions
How to make the front, left, right, or the back of a gameobject look at a target? 1 Answer
enemy look at GameObject player? unity ver. 5.2 C# 0 Answers
How do i make my enemy look at player on only one axis? 1 Answer
Shader Graph: Rotate texture to look at 'camera' 1 Answer
Help for Realistic car Chase/Pursuit 1 Answer