Can't detect transform

Hi. Im trying to make a game but my code isn’t running when the transform is 14. This is my code

using UnityEngine;

public class Taco : MonoBehaviour
{

    public Rigidbody2D rigidbody;
    public float MoveSpeed = 100f;
    public int Movecount = 0;

    void Update()
    {
        if(transform.position.x == 14f)
        {
            Debug.Log("Y = 14");
        }
    }

    void FixedUpdate()
    {
        if(Movecount <= 5)
        {
            rigidbody.AddForce(transform.right * MoveSpeed);
            Movecount = Movecount + 1;
        }
    }

}

You should not compare floating point values like this as small errors or inability to exactly represent certain numbers using floating point will cause problems. For instance, it might be 14.00002.

This is why functions like the following are important: Mathf.Approximately

Its still not working but I might not be doing to right this is my new script

using UnityEngine;

public class Taco : MonoBehaviour
{

    public Rigidbody2D rigidbody;
    public float MoveSpeed = 100f;
    public int Movecount = 0;

    void Update()
    {
        if(Mathf.Approximately(transform.position.x, 15f / 15f))
        {
            Debug.Log("Y = 14");
        }
    }

    void FixedUpdate()
    {
        if(Movecount <= 5)
        {
            rigidbody.AddForce(transform.right * MoveSpeed);
            Movecount = Movecount + 1;
        }
    }

}

I don’t think that is how you use MathfApproximately, as 15f/15f would be 1f and not the 14 that you are expecting for your x position.
You should be able to do it a couple of different ways:

void Update()
    {
        if(Mathf.Approximately(1f, transform.position.x / 14f))
        {
            Debug.Log("Y = 14");
        }
    }

Or even simpler:

void Update()
    {
        if(Mathf.Approximately(transform.position.x, 14f))
        {
            Debug.Log("Y = 14");
        }
    }

Yes, you’ve taken the example literally but seem to have not read the associated description. You simply put in the two values you want to compare. The example which puts in 10.0f / 10.0f demonstrates how float operations might not give you exactly what you want. It might not be 1.0f but 1.0001f etc.

// Is the X position 14?
if(Mathf.Approximately(transform.position.x, 14f))

The thing is, your code is pretty sensitive. Why would it be exactly 14? It’s more likely you want to check:

if (transform.position.x >= 14f)

or check a range. Working with exact values is going to make it sensitive which is why when working with floats you work with small ranges or thresholds.

if (transform.position.x >= 14f && transform.position.x <= 15f )

That would do the thing :smile:

I fixed the script. Thanks! :slight_smile:

1 Like