SHOW CASE
SHOW CASE

Reputation: 39

unity2d character y position equal bird y position

I want the bird to give my character coin if the character y position equal the bird y position I did this code but it's not work

    public Transform target;
public GameObject Coin;

void Update () {
    transform.Translate (Vector2.left * 10f * Time.deltaTime);
    if (transform.position.y == target.position.y) {
        Instantiate (Coin, transform.position, Quaternion.identity);
    }

}

Upvotes: 0

Views: 35

Answers (2)

SHOW CASE
SHOW CASE

Reputation: 39

the answer is putting x not the y this code answer the question

void Update () {
        transform.Translate (Vector2.left * 10f * Time.deltaTime);
        if (transform.position.x <= target.position.x&&coin==false) {
            Instantiate (EvilEgg, transform.position, Quaternion.identity);
            coin=true;
                    }

        }

Upvotes: 0

bastingup
bastingup

Reputation: 149

You have answered it yourself in the comments. The character is never EXACTLY the same y-pos like the bird, so you gotta check whether the character is above the bird. Try this:

public Transform target;
public GameObject Coin;
private bool _birdGaveCoin = false;

void Update()
{
    transform.Translate(Vector2.left * 10f * Time.deltaTime);
    if (transform.position.y <= target.position.y && !_birdGaveCoin)
    {
        Instantiate(Coin, transform.position, Quaternion.identity);
        _birdGaveCoin = !_birdGaveCoin;
    }
}

So to wrap it up: floats are crazy precise. So can be that one frame your character is at 3.99999f and the bird is at 4.00000f and the next frame the player is at 4.00001f, so it's technically not the same.

Upvotes: 1

Related Questions