所以,在LibGDX中,我使用的是box2d,我有一个联系人听力课程。我需要在不创建类对象的情况下获取我的玩家的身体,因为它将第二次调用构造函数。并且静态变量不是一个选项。我该怎么做?
这是GameContacts类:
package com.platformer.managers;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.Manifold;
/**
* Created by Oliverss on 24/04/2015.
*/
public class GameContacts implements ContactListener {
private int onGround;
private int onHouse;
public static int mobCanJump;
public static int mobOnGround;
public void beginContact(Contact contact) {
Fixture fa=contact.getFixtureA();
Fixture fb=contact.getFixtureB();
if(fb.getUserData().equals("player_sensor")){
onGround++;
}
if(fa.getUserData().equals("house")&&fb.getUserData().equals("player")){
onHouse++;
}
if(fa.getUserData().equals("block") &&fb.getUserData().equals("mob_sensor")){
mobCanJump++;
}
if(fa.getUserData().equals("block") &&fb.getUserData().equals("mob_sensor_ground")){
mobOnGround++;
}
if(fb.getUserData().equals("player")&&fa.getUserData().equals("one_way_block")){
Vector2 vel= //here i need to get the body variable
if(vel.y>0)contact.setEnabled(false);
}
}
public void endContact(Contact contact) {
Fixture fa=contact.getFixtureA();
Fixture fb=contact.getFixtureB();
if(fb.getUserData().equals("player_sensor")){
onGround--;
}
if(fa.getUserData().equals("house")&&fb.getUserData().equals("player")){
onHouse--;
}
if(fa.getUserData().equals("block") &&fb.getUserData().equals("mob_sensor")){
mobCanJump--;
}
if(fa.getUserData().equals("block") &&fb.getUserData().equals("mob_sensor_ground")){
mobOnGround--;
}
}
public boolean isPlayerOnGround(){return onGround>0;}
public boolean isOnHouse(){return onHouse>0;}
public void preSolve(Contact contact, Manifold oldManifold) {}
public void postSolve(Contact contact, ContactImpulse impulse) {}
}
答案 0 :(得分:0)
如果你想要参与碰撞的物体(玩家)的身体,你可以使用以下方法从夹具中取出它:
contact.getFixtureA().getBody();
否则,如果你有一个名为"播放器"的自定义类。并且你想要参与碰撞的那个类的对象,你可以在UserData中保存玩家对象的引用而不是字符串" player"。像:
第一次调用构造函数时,保存对象的引用而不是" player"字符串:
setUserData(this);
然后在GameContacts类中,改为使用这些:
Object objectA=contact.getFixtureA().getUserData();
..
...
if(objectA instanceof Player){//instead of fb.getUserData().equals("player")
((Player) objectA)//Get object of class using casting
}