gpt4 book ai didi

安卓(和引擎): Sprite with body attached going up and down

转载 作者:行者123 更新时间:2023-11-29 21:59:19 24 4
gpt4 key购买 nike

我试图让游戏中的敌人上下移动;因为我使用的是一个带有 Sprite 的物理体,所以我不能使用实体修饰符,所以我决定在每次它的 sprite 达到某个点时使用 .setLinearVelocity(float x, float y) 方法给 body 一点推力在屏幕上。

只有一个 body 效果很好,但我需要让其他敌人(相同的 Sprite ,不同的 body )每 5 秒产生一次并做同样的事情,但我不知道如何追踪它们......我的意思是,我不知道如何控制每个物体是否彼此独立地到达 Y 位置...

比如现在的代码是这样的:

private void add_Box_Face()
{
float random_x = (float) (28 + (int)(Math.random() * ((this.CAMERA_WIDTH - 28*2) + 1)));

final Body rectangle_face_body;

final Sprite rectangle_face = new Sprite(random_x, this.y, this.mRectangleFaceTextureRegion, this.getVertexBufferObjectManager());

rectangle_face_body = PhysicsFactory.createBoxBody(this.m_PhysicsWorld, rectangle_face, BodyType.DynamicBody, this.BOX_FIXTURE_DEF);

rectangle_face_body.setUserData("target");

//I give the body a initial push
rectangle_face_body.setLinearVelocity(0, -5);

//I register an update handler to the sprite to control if it reaches a certain Y value
rectangle_face.registerUpdateHandler(new IUpdateHandler()
{
@Override
public void onUpdate(float pSecondsElapsed)
{

if (rectangle_face.getY() >= y-50)
{
//Here I just use a flag so that later on below I can do the push
MyApp.this.setLinearVelocity = true;
}
}

@Override
public void reset()
{
// TODO Auto-generated method stub
}

});

//Here I register the physic connector and if the flag permits it, I push the body up
this.m_PhysicsWorld.registerPhysicsConnector(new PhysicsConnector(rectangle_face, rectangle_face_body, true, false)
{
@Override
public void onUpdate(float pSecondsElapsed)
{
super.onUpdate(pSecondsElapsed);

if(MyApp.this.setLinearVelocity)
{
rectangle_face_body.setLinearVelocity(0, -3);
MyApp.this.setLinearVelocity = false;
}



}
});

this.mscene.attachChild(rectangle_face);

}

使用这样的代码,第一个物体按照计划进行,它上下移动,但一旦另一个物体弹出,它就会掉下来,另一个物体上升,因为 bool 值 setLinearVelocity 始终设置为 true,所以不断向上插入;当第三个 body 进来时,第二个 body 也掉下来,最后一个代替它上升

对于这段代码,我并没有期望太多...但我不知道我还能尝试什么...我该如何控制它?

提前致谢:)

编辑:在下面的答案中添加了工作代码

最佳答案

我建议您将敌人的代码与更新处理程序的代码分开。创建一个包含 Sprite 和 Body 的 Enemy 类,将您的 Enemies 保存在一个数组中并覆盖 PhysicsWorld 的 onUpdate 方法,以便它遍历 Enemies 数组并对所有敌人执行您想要的操作。

这是一个代码 fragment ,展示了一种非常简单的方法:

mEngine.registerUpdateHandler(new IUpdateHandler() {
@Override
public void reset() {}

@Override
public void onUpdate(float pSecondsElapsed) {
for (Enemy e : enemies) {
e.checkPositionAndBounce();
}
}
});

请注意,这可能不是一个好主意,因为这段代码可能会在与物理引擎不同的线程上运行,这可能会导致各种问题。更好的方法是覆盖 PhysicsWorld 的 onUpdate 方法:

@Override
public void onUpdate(final float pSecondsElapsed) {
super.onUpdate();
for (Enemy e : enemies) {
e.checkPositionAndBounce();
}
}

如果您不确定第一个 fragment 的含义,请查找“匿名内部类”。

关于安卓(和引擎): Sprite with body attached going up and down,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12372492/

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