i have this code, which checks for if the target is behind or in front, but was wondering how can i check if it is to the left or the right of me ( i need it so i can play a certain animation).
Vector3 dir = (target.transform.position - transform.position).normalized;
float direction = Vector3.Dot (dir, transform.forward);
if (direction < 0.3f) {// stuff here
}
Get the Dot product of the transform.right vector and the direction vector. Same deal, negative value is to the left and positive is to the right.
using System.Collections;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour {
public Transform target;
private Vector2 mypos;
void Start () {
mypos = transform.position;
var targetPos = target.position;
if (target.position.x < mypos.x && changed(mypos.y,targetPos.y)) {
print ("Right");
} else if(changed(mypos.y,targetPos.y)){
print ("Left");
}
if(target.position.y < mypos.y && changed(mypos.x,targetPos.x)){
print("Up");
}else if(changed(mypos.x,targetPos.x)){
print("Down");
}
}
bool changed(float a,float b){
if((int)a == (int)b){
return true;
}else{
return false;
}
}
}
if(Vector3.Dot(transform.right, transform.position) > 0) {
//Is moving right
} else {
//Is moving left
}