I am implementing my code on an object and the player’s hand is the origin to detect if it is in the direction of right/left/up/down.
So far the code is working to detect all 4 axis but there is a problem. If the direction is left/right, it prints both “Left” and “Up”, similarly “Right” and “Up”. Can it be just “Left” or “Right” and not print the y axis along with it?
How do I fix this?
public GameObject playersHand;
private Transform targetOrigin;
private Vector2 targetPos;
private Vector2 mypos;
void Start()
{
targetOrigin = this.gameObject.transform;
}
void Update()
{
mypos = playersHand.transform.position;
targetPos = targetOrigin.position;
if (targetOrigin.position.x < mypos.x && changed(mypos.y, targetPos.y))
{
print ("Right");
}
else if (changed(mypos.y, targetPos.y))
{
print ("Left");
}
if (targetOrigin.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;
}
}