gpt4 book ai didi

java - 更改 FixtureDef 属性 Java Libgdx

转载 作者:行者123 更新时间:2023-12-01 09:41:23 26 4
gpt4 key购买 nike

我使用工厂模式在游戏中创建 Box2D 主体。这是创建主体的代码:

public static HashMap<String, Object> createAndGet(Vector2 position, Vector2 dimensions,
BodyType type, boolean isCircle){
HashMap<String, Object> bodyObjectsHash = new HashMap<String, Object>();

BodyDef bodyDef = new BodyDef();
bodyDef.type = type;
bodyDef.position.set(new Vector2(position.x, position.y));

Body body = EntityManager.createBody(bodyDef, dimensions);

FixtureDef fixtureDef = new FixtureDef();
Fixture fixture;
if(isCircle){
CircleShape circle = new CircleShape();
circle.setRadius(dimensions.x);
fixtureDef.shape = circle;
fixture = body.createFixture(fixtureDef);
circle.dispose();
}else{
PolygonShape rectangle = new PolygonShape();
rectangle.setAsBox(dimensions.x, dimensions.y);
fixtureDef.shape = rectangle;
fixture = body.createFixture(fixtureDef);
rectangle.dispose();
}


bodyObjectsHash.put(BodyReferences.BODY, body);
bodyObjectsHash.put(BodyReferences.BODY_DEF, bodyDef);
bodyObjectsHash.put(BodyReferences.FIXTURE, fixture);
bodyObjectsHash.put(BodyReferences.FIXTURE_DEF, fixtureDef);


return bodyObjectsHash;


}

现在,您将看到它返回一个 HashMap。键是字符串并返回一个对象。这样就可以完成这样的代码:

public void attachNewSprite(String internalPath){
entitySprite = new Sprite(new Texture(Gdx.files.internal(internalPath)));
((Body)bodyObjects.get(BodyReferences.BODY)).setUserData(entitySprite);
}

返回的HashMap存储在bodyObjects

但是您会注意到,在创建实体的静态方法中,没有设置密度和摩擦力等属性。这是因为我认为通过返回对象我可以编辑它们。以下是我假设编辑 FixtureDef 的方式:

public void addFixtureDefProperties(float density, float friction, float restitution){
((FixtureDef)(bodyObjects.get(BodyReferences.FIXTURE_DEF))).density = density;
((FixtureDef)(bodyObjects.get(BodyReferences.FIXTURE_DEF))).friction = friction;
((FixtureDef)(bodyObjects.get(BodyReferences.FIXTURE_DEF))).restitution = restitution;

/*This line will be discussed */
((Body)(bodyObjects.get(BodyReferences.BODY))).getFixtureList().removeRange(0, ((Body)(bodyObjects.get(BodyReferences.BODY))).getFixtureList().size - 1);
((Body)(bodyObjects.get(BodyReferences.BODY))).createFixture(((FixtureDef)(bodyObjects.get(BodyReferences.FIXTURE_DEF))));
}

所以我基本上设置了新属性,从主体中删除fixturedef,然后添加新属性。执行此操作时,我收到 fatal error 。我删除了删除fixturedef 的行并得到相同的 fatal error 。这是 fatal error :

enter image description here

有人可以帮我找到一种方法来编辑这些属性,这样我就不必用更多参数淹没我的静态 createBody 方法。谢谢!

最佳答案

您可以使用夹具的 setter 方法来更改夹具的属性,但形状除外。您可以使用 getter 方法获取所有属性。仔细看看 Fixture API。因此您不需要保存fixtureDef 对象。 BodyDef 和 Body 的关系类似。

关于java - 更改 FixtureDef 属性 Java Libgdx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38419712/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com