I assume it doesn’t work for you, because the Vector2’s would have to be really really close together.
You can roll your own implementation to better fit your requirements.
For example:
public static class MyMath
{
public static bool Equal(Vector2 _v1, Vector2 _v2, Vector2 _e)
{
return System.Math.Abs(_v1.x - _v2.x) <= _e.x &&
System.Math.Abs(_v1.y - _v2.y) <= _e.y;
}
}
Then use it like this:
void Update()
{
Vector2 character = GameObject.Find("Idle").transform.position;
Vector2 objects = new Vector2(0.0f, 0.0f);
Vector2 maxOffset = new Vector2(0.5f, 0.5f);
if(MyMath.Equal(character, objects, maxOffset))
{
Debug.Log("Character and Objects are closer than maxOffset.");
}
}
If you want to check close distance then I would compare the magnitude of the difference to some given threshold. Also worth noting that Unity’s Mathf has an Approximately method that checks against epsilon already. So you could do this
wow, It’s very very confused to me. This is correct ? Please, explain me step by step ok.
First, my current code: What is it wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class coin : MonoBehaviour {
void Update()
{
Vector2 character = GameObject.Find("Idle").transform.position;
Vector2 objects = new Vector2(0.0f, 0.0f);
Vector2 maxOffset = new Vector2(0.5f, 0.5f);
if(MyMath.Equal(character, objects, maxOffset)
{
Debug.Log("Character and Objects are closer than maxOffset.");
}
}
}
You are probably missing the other code i posted, namely the MyMath class.
Just put that into another script file somewhere in your project.
You can then access it from anywhere, since it is a static class with a static method.
Approximately? scoffs like an elitist That function can generate garbage. I find that to be a big deal for a simple math operation, thus I simply check against float.Epsilon.
substract the two positions together then see if result.sqrMagnitude is less than maxOffset*maxOffset. if so the 2 positions are within the maxoffset.