Reputation: 5
Well I'm new to LibGDX and Java actually and I'm trying to create a game by watching tutorials about what I need to do.
So here's the question I have specific objects to check collision with and
public void beginContact(Contact contact)
{
if((contact.getFixtureA().getBody().getUserData() == "player" && contact.getFixtureB().getUserData() instanceof InteractiveTileObjects) )
{
Gdx.app.log("Yeah","");
}
that works perfect, but when I go to InteractiveTileObjects the last part of the code is fixture = body.createFixture(fdef); I use it to setUserData to that specific objects. Here is the code:
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);
And this is one of my specific objects below:
public class DreamCatcher extends InteractiveTileObjects {
public DreamCatcher(World world, TiledMap map, Rectangle bounds)
{
super(world, map, bounds);
fixture.setUserData(this);
setCategoryFilter(MainClass.BIT_DCATCHER);
}
As you can see I use
fixture.setUserData(this)
and when I change this to
fixture.setUserData("DreamCatcher")
it doesnt work in my beginContact part because of the instanceof InteractiveTileObjects. But again in begin contact if I change
contact.getFixtureB().getUserData() == "DreamCatcher"
it works perfect again what is that "this" doing to work that instanceof code ? I mean why it's like that ?
I know it's long but I'd be glad if someone can answer these...
Upvotes: 0
Views: 367
Reputation: 4436
1) instanceof:
In java instanceof
operator is used to test whether the object is an instance of the specified type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns false.
example of instanceof operator:
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) this keyword:
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object. Usage of java this keyword
Here is given the 6 usage of java this keyword.
this()
can be used to invoke current class constructor.Changing
fixture.setUserData(this)
tofixture.setUserData("DreamCatcher")
will not work assetUserData()
method expecting object of typeDreamCatcher
and not String.
Upvotes: 2