我正在使用Andengine / Box2D物理插件制作游戏。我在世界步骤计算过程中因为box2d体的添加/移动/删除而经历了随机崩溃,所以我实现了使用setUserData方法标记sprite / body以进行删除的代码 - 我将JSON对象附加到每个body并且sprite为包含精灵的类型,正文和精灵本身及其删除状态:
private JSONObject makeUserData(int type, Body body, Object sprite)
{
JSONObject myObject = new JSONObject();
try {
myObject.put("type", type);
myObject.put("sprite", sprite);
myObject.put("body", body);
myObject.put("deleteStatus", false);
} catch (JSONException e) {
Log.d(TAG,"Exception creating user data:"+e);
}
return myObject;
}
然后在更新线程中迭代遍历我世界中所有寻找这些标志的实体并删除带有标志的精灵/物体。正确删除了正文,但精灵删除似乎删除了该特定sprite的每个实例,而不是删除我标记为删除的特定实例!当我的玩家与不可见的物体碰撞时,我可以告诉身体仍然没有精灵!以下是删除代码:
private void removeObjectsSetForDestruction()
{
if(this.mPhysicsWorld!=null)
{
Iterator<Body> allMyBodies = this.mPhysicsWorld.getBodies();
boolean isDelete = false;
JSONObject currentBodyData;
while(allMyBodies.hasNext())
{
try {
currentBodyData = (JSONObject)allMyBodies.next().getUserData();
if(currentBodyData!=null)
{
isDelete = (Boolean) currentBodyData.get("deleteStatus");
if(isDelete)
{
destroyObstruction((Body) currentBodyData.get("body"));
}
}
} catch (JSONException e) {
Log.d(TAG,"Error getting world bodies data:"+e);
}
}
}
}
private void destroyObstruction(Body obstructionBody) throws JSONException
{
obstructionBody.setActive(false);
JSONObject secondBodyData = null;
if(obstructionBody.getUserData()!=null)
{
secondBodyData=(JSONObject) obstructionBody.getUserData();
//explodeObstruction(((IEntity) secondBodyData.get("sprite")).getX(),((IEntity) secondBodyData.get("sprite")).getY());
if(secondBodyData.get("sprite") instanceof AnimatedSprite)
{
removeObject((AnimatedSprite) secondBodyData.get("sprite"));
}
else
{
removeObject((Sprite) secondBodyData.get("sprite"));
}
}
}
private void removeObject(final AnimatedSprite myAnimSprite)
{
final PhysicsConnector myPhysicsConnector = this.mPhysicsWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(myAnimSprite);
this.mPhysicsWorld.unregisterPhysicsConnector(myPhysicsConnector);
this.mPhysicsWorld.destroyBody(myPhysicsConnector.getBody());
this.mScene.unregisterTouchArea(myAnimSprite);
this.mScene.detachChild(myAnimSprite);
System.gc();
}
private void removeObject(final Sprite mySprite)
{
final PhysicsConnector myPhysicsConnector = this.mPhysicsWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(mySprite);
this.mPhysicsWorld.unregisterPhysicsConnector(myPhysicsConnector);
this.mPhysicsWorld.destroyBody(myPhysicsConnector.getBody());
this.mScene.unregisterTouchArea(mySprite);
this.mScene.detachChild(mySprite);
System.gc();
}
答案 0 :(得分:1)
我想看一下创建代码的对象。我假设每个精灵都使用相同的TextureRegion
,所以当一个精灵的区域被改变时 - 其他精灵上的相同区域也会因Android架构细节而改变。对于具有相同TextureRegion
的每个精灵,您应该使用textureRegion.clone()
作为构造函数的最后一个参数。希望这会有所帮助。