- Home /
Quaternion Look at Target , i have trouble , pls help me !!!!!
Firstly english is not my main language , sorry about my english .
This is my problem :
and here is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FindClosestEnemyScript : MonoBehaviour
{
Vector3 trgt;
void Update()
{
FindClosest();
}
void FindClosest()
{
float distanceToClosestEnemy = Mathf.Infinity;
Enemy closestEnemy = null;
Enemy[] allEnemies = GameObject.FindObjectsOfType<Enemy>();
foreach(Enemy currentEnemy in allEnemies)
{
float distanceToEnemy = (currentEnemy.transform.position - this.transform.position).sqrMagnitude;
if(distanceToEnemy < distanceToClosestEnemy)
{
distanceToClosestEnemy = distanceToEnemy;
closestEnemy = currentEnemy;
}
}
Debug.DrawLine(this.transform.position, closestEnemy.transform.position);
trgt = closestEnemy.transform.position;
Quaternion rotation = Quaternion.LookRotation(trgt, Vector3.up);
transform.rotation = rotation;
}
}
the problem is , my character not rotate against enemy and not properly moving with this codes, if im disable findclosestenemyscript , my movement script work fine , but with findclosestenemy script dont work fine , anyone else help me ??? :/ btw my movement script third person controller script , unity tutorial's
Answer by LeFlop2001 · Jun 19, 2020 at 05:26 PM
the problem youre having is a result of using the targets positionvector as the lookdirection for your player, but the target positionvector is the direction from the world center to the target. to get the direction from your player to the target you have to subtract the players position Quaternion rotation = Quaternion.LookRotation(trgt - transfrom.position, Vector3.up);
also theres a function to calculate the distance between to vectors called Vector3.Distance(), not that it really matters, just letting you know.