简体   繁体   中英

comparing sprites in Libgdx

This is my code:

    private Sprite sprGuy;

    sprGuy  = atlas.createSprite("guy");

    Sprite a = new Sprite(sprGuy);
    Sprite b = new Sprite(sprGuy);

    if (a.equals(b)) {
        System.out.println("a is equal to b");
    }

According to Libgdx documentation: new Sprite(Sprite sprite) ... "Creates a sprite that is a copy in every way of the specified sprite."

But if 'a' is a copy of sprGuy and 'b' is a copy of sprGuy , why a.equals(b) is false?

How should I check if sprites are from the same "father"?

As you can see in the libGDX Sprite.java source file, the equals() method hasn't been implemented for Sprite .

So you're calling the default equals() method of the Java Object class which just compares the references, which are different for the two objects in your code.

if it is for something simple and have control over the assignment of texture in the sprite, you can use this example:

private Sprite sprGuy;

sprGuy  = atlas.createSprite("guy");

Sprite a = new Sprite(sprGuy);
Sprite b = new Sprite(sprGuy);

if (a.getTexture().equals(b.getTexture())) {
    System.out.println("a is equal to b");
}

This is my new approach:

First, I created this new class:

public class SpriteAux {

    public String name;
    public Sprite sprite;

    public SpriteAux(Sprite sprite, String name) {
        this.sprite = sprite;
        this.name = name;       
    }

}

So, creating new objects containing sprite and name, we can get and compare the names:

private Sprite sprGuy;
private Sprite sprBoss;

sprGuy  = atlas.createSprite("guy");
sprBoss  = atlas.createSprite("boss");

SpriteAux a = new SpriteAux(sprGuy, "guy");
SpriteAux b = new SpriteAux(sprGuy, "guy");
SpriteAux c = new SpriteAux(sprBoss, "boss");

if (a.name.equals(b.name)) {                  //This is true!
    System.out.println("a is equal to b");
}

if (a.name.equals(c.name)) {                  //This is false!
    System.out.println("a is equal to c");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM