繁体   English   中英

LibGDX instanceof和这个

[英]LibGDX instanceof and this

好吧,我实际上是LibGDX和Java的新手,我正在尝试通过观看有关我需要做的教程来创建游戏。

所以这是我有特定对象来检查与和的碰撞的问题

    public void beginContact(Contact contact)
    {
        if((contact.getFixtureA().getBody().getUserData() == "player" && contact.getFixtureB().getUserData() instanceof InteractiveTileObjects) )
    {
        Gdx.app.log("Yeah","");
    }

效果很好,但是当我转到InteractiveTileObjects时,代码的最后一部分是fixture = body.createFixture(fdef);。 我使用它来将UserData设置为该特定对象。 这是代码:

bdef.type = BodyDef.BodyType.DynamicBody;
    bdef.position.set((bounds.getX() + bounds.getWidth() / 2) / MainClass.PPM, (bounds.getY() + bounds.getHeight() / 2) / MainClass.PPM);
    body = world.createBody(bdef);
    shape.setAsBox((bounds.getWidth() / 2) / MainClass.PPM, (bounds.getHeight()/ 2) / MainClass.PPM);
    fdef.shape = shape;
    fdef.filter.categoryBits=MainClass.BIT_DCATCHER;
    fixture = body.createFixture(fdef);

这是我下面的特定对象之一:

public class DreamCatcher extends InteractiveTileObjects {

    public DreamCatcher(World world, TiledMap map, Rectangle bounds)
    {
        super(world, map, bounds);

        fixture.setUserData(this);
        setCategoryFilter(MainClass.BIT_DCATCHER);
    }

如您所见,我使用

fixture.setUserData(this) 

当我将其更改为

fixture.setUserData("DreamCatcher")

由于InteractiveTileObjects的实例,它在我的beginContact部分中不起作用。 但是如果我改变了,再次开始联系

contact.getFixtureB().getUserData() == "DreamCatcher"

它再次完美运行,“ this”如何工作该代码实例? 我的意思是为什么会这样?

我知道这很长,但是如果有人能够回答这些问题,我将感到非常高兴。

1) instanceof

在java中, instanceof运算符用于测试对象是否是指定类型(类,子类或接口)的实例。

Java中的instanceof也称为类型比较运算符,因为它会将实例与类型进行比较。 它返回true或false。 如果我们对任何具有null值的变量应用instanceof运算符,则它将返回false。

instanceof运算符的示例:

class Animal{}  
class Dog1 extends Animal{//Dog inherits Animal  

 public static void main(String args[]){  
 Dog1 d=new Dog1();  
 System.out.println(d instanceof Animal);//true  
 }  
}  

2) 关键字:

java this关键字可以有很多用法。 在Java中,这是引用当前对象的参考变量。 java this关键字的用法

这里给出了java this关键字的6种用法。

  • 此关键字可用于引用当前的类实例变量。
  • this()可用于调用当前类的构造函数。
  • 此关键字可用于调用当前类方法(隐式)
  • 这可以作为方法调用中的参数传递。
  • 这可以在构造函数调用中作为参数传递。
  • 此关键字还可以用于返回当前的类实例。

fixture.setUserData(this)更改为setUserData() fixture.setUserData("DreamCatcher")不能作为setUserData()方法使用,期望的对象类型为DreamCatcher而不是String。

暂无
暂无

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

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