简体   繁体   English

比较Libgdx中的精灵

[英]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." 根据Libgdx文档: new Sprite(Sprite sprite) ...“创建一个sprite,它是指定sprite的每种方式副本 。”

But if 'a' is a copy of sprGuy and 'b' is a copy of sprGuy , why a.equals(b) is false? 但是,如果“ a”sprGuy的副本,而“ b”sprGuy的副本,为什么a.equals(b)是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 . 如您在libGDX Sprite.java源文件中看到的那样,尚未为Sprite实现equals()方法。

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. 因此,您正在调用Java Object类的默认equals()方法,该方法仅比较引用,这对于代码中的两个对象而言是不同的。

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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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