java如何使具有纹理的libgdx精灵与box2d主体同时创建?
我已经研究这个问题一段时间了,决定在这个问题上寻求帮助。
总结:
我有一个bullet
类,它扩展了Actor
,还有一个makeBullet
方法,它生成了box2d
主体和固定装置。
在我的bullet
类的draw方法中,我有一个if/else语句,检查我的shootButton
是否被按下,如果被按下,调用makeBullet
方法,用纹理创建一个新的Sprite
,将位置设置为box2d
子弹,并对我的子弹应用线性脉冲
问题:
只有当我按下shootButton
键时,精灵的纹理才会出现,并且只出现在播放器旁边,但是box2d
子弹似乎工作正常。如何将图像附加到每个项目符号
对不起,如果我不太清楚,我很乐意进一步详细解释或给出更多代码
bullet
类:
package com.mygdx.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Actor;
import static com.badlogic.gdx.physics.box2d.BodyDef.BodyType.DynamicBody;
public class bullet extends Actor{
static BodyDef bodyDef;
static Body body;
static FixtureDef fixtureDef;
static PolygonShape groundBox;
Sprite bulletThing;
//method that makes box2d bullet bodies, takes world and direction from main class, MyGdxGame
public static void makeBullet(World world, int direction) {
//makes body def
bodyDef = new BodyDef();
bodyDef.type = DynamicBody;
// sets bullet at player (MyActor)'s location
bodyDef.position.set(MyActor.body.getPosition().x, MyActor.body.getPosition().y);
// put body in the world
body = world.createBody(bodyDef);
// makes fixture for bullet body
fixtureDef = new FixtureDef();
groundBox = new PolygonShape();
fixtureDef.shape = groundBox;
fixtureDef.density = 0.9f;
fixtureDef.friction = 0.6f;
fixtureDef.restitution = 0.1f;
groundBox.setAsBox(1f, 1f);
// attach fixture to body
body.createFixture(fixtureDef);
}
@Override
public void draw(Batch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
if (MyGdxGame.shootButton.isPressed()) { // if my shootButton is pressed
//makes a bullet, takes the direction from main class
bullet.makeBullet(MyGdxGame.world, MyGdxGame.direction);
// makes texture for sprite
Pixmap pixmap = new Pixmap(1, 1, Pixmap.Format.RGBA8888);
pixmap.setColor(Color.WHITE);
pixmap.fill();
bulletThing = new Sprite(new Texture(pixmap));
// sets sprite texture to box2d bullet, supposedly
bulletThing.setBounds(bullet.body.getPosition().x - bulletThing.getWidth()/2, bullet.body.getPosition().y - bulletThing.getHeight()/2, 4f, 4f);
bulletThing.setRotation(MathUtils.radiansToDegrees * bullet.body.getAngle());
bulletThing.setOriginCenter();
bulletThing.draw(batch);
//fires the bullet
body.applyLinearImpulse(MyGdxGame.direction * 1f,0,body.getWorldCenter().x, body.getWorldCenter().y, true);
}
}
}
如果需要,可以使用主类。谢谢你的帮助
共 (0) 个答案