- Home /
Issue with checking to see whether the Bounds value's of two game objects equal each other
Hi there,
So basically I have two game objects in a scene - one is just a rectangle shaped game object and the other is a wall. Both game object have BoxCollider2D components attached to them. The rectangle has a Dynamic Rigidbody2D attached to it.
Basically I have code that makes the rectangle travel horizontally to the right towards the wall. I have an if statement that states when the X value of the Bounds.Max position of the rectangle touches the X value of the Bounds.Min position of the wall a message should pop up in the console.
Here is the code that I have:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerNew : MonoBehaviour
{
private Rigidbody2D _rb;
private BoxCollider2D _col2D;
private float X_force = 25f;
public Vector2 newPosition;
public Vector2 bottomRight;
public Vector2 wallBoundsMin;
// Start is called before the first frame update
void Start()
{
_rb = GetComponent<Rigidbody2D>();
_col2D = GetComponent<BoxCollider2D>();
wallBoundsMin = GameObject.Find("Wall").GetComponent<BoxCollider2D>().bounds.min;
}
// Update is called once per frame
void Update()
{
bottomRight = new Vector2(_col2D.bounds.max.x,_col2D.bounds.min.x);
newPosition = new Vector2(X_force,0);
_rb.MovePosition(_rb.position + newPosition * Time.deltaTime);
if(bottomRight.x == wallBoundsMin.x){
Debug.Log("Bounds have collided with one another");
}
}
}
However nothing appears in the console when the rectangle crosses the wall. But the message actually does appear in the console if I change the if statement to the following:
if(bottomRight.x >= wallBoundsMin.x){
I'm confused as to why the message wont appear when I just check to see when the two X value's equate to one another? I don't think I've written the code incorrectly? Here is a video of the issue: https://www.youtube.com/watch?v=J9g-kF8WR9g&ab_channel=segoviate
Any help would be appreciated. Thanks
Answer by GSGregory · May 04, 2021 at 06:22 AM
Floats are an inaccurate number. Don't compare floats with ==. For example. 0001 and .0002 are not equal to a computer. So basically when the comparison is called they are both not exactly the same value. I think there is a way to ignore a certain level of discrepancy but you are probably better off just calling > or >=
Another example is if you divide 10f by 3 you might get 3.333332, or 3.333334 ect
Your answer
Follow this Question
Related Questions
Question about raycast collision detection involving Kinematic Rigidbody2D 1 Answer
Switching from kinematic to dynamic without stutter 0 Answers
Object passes through collider even when isTrigger is turned off. 2 Answers
How do I make collisions where both objects are moving but pass through each other? 0 Answers
Is the bounds.size and the GetComponent.BoxCollider2D.size of a GameObject meant to be the same? 1 Answer