- Home /
Question by
theUndeadEmo · May 07, 2012 at 11:38 PM ·
transformleftright
how to check if the target is to the left or the right?
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
}
Comment
Best Answer
Answer by Mortoc · May 07, 2012 at 11:51 PM
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.
Answer by Seyed_Morteza_Kamaly · Jun 10, 2017 at 07:26 PM
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;
}
}
}
Answer by italoha · Jul 18, 2019 at 03:08 AM
if(Vector3.Dot(transform.right, transform.position) > 0) {
//Is moving right
} else {
//Is moving left
}
Your answer
Follow this Question
Related Questions
How do you make an object go left and right? 1 Answer
How to Make an Endless Runner Move from track to track smoothly 0 Answers
Auto walk 2 Answers