Reputation: 25
this is my code in Unity, I've been trying to see if the rb's position is equal to cameraPos position but it doesn't work(nothing happends)
public Rigidbody2D rb;
Vector2 cameraPos;
void Start ()
{
cameraPos = new Vector2(0f, -3f);
}
if (rb.position == cameraPos)
{
print("Continue");
}
Upvotes: 1
Views: 315
Reputation: 90630
Note that two positions might never be exactly equal especially if using RigidBody
without a PlayerController
because movements might actually "jump" between to frames.
The ==
operator you are currently using actually uses approximation but only to an accuracy of 1e-5
(0.00001
) of the float values. This can lead to a little misunderstanding but it only means that e.g. (0.99999, 0.99999, 0.99999) == (1,1,1)
. Anything more appart won't match.
You should rather use an approximation instead e.g. using Vector3.Distance for checking if the objects are less then X meters appart where you can make X now greater or also smaller than 1e-5. In this example it should match if the objects are closer than 10cm:
public Rigidbody2D rb;
Vector2 cameraPos;
// Set the threshold in meters
public float Threshold = 0.1f;
void Start ()
{
cameraPos = new Vector2(0f, -3f);
}
if (Vector3.Distance(rb.position, cameraPos) <= Threshold)
{
print("Continue");
}
Depending on your needs you can than adjust the Threshold
to be wider or more exact.
Alternatively you could as well use Collisions / Rigidbody.OnCollisionEnter
for tracking if certain objects are "close enough" / touching each other. Advantage of this approach is that you don't only know if the positions are close but also with which velocity both objects met.
Upvotes: 2