我有一个游戏课,我正在做所有的创作和绘画,但我不知道如何获得子弹生成时的起点(x,y)。因为x y总是在变化。我有想法创建一个子弹类,但我不知道如何更改mygame以适应它。我需要的只是产生子弹的简单x,y coordiante以任何方式来保存它?我认为我的子弹课应该是这样的:
public class Bullet {
private Circle circle;
private int startX;
private int startY;
public Bullet(int startX, int startY){
circle = //create circle from startX and startY
this.startX = startX;
this.startY = startY;
}
//getters and setters here...
}
这是我的游戏类
public class MyGame extends ApplicationAdapter {
SpriteBatch batch;
Texture ballImage, bulletImage;
OrthographicCamera cam;
Circle ball;
Array <Circle> bullets;
//long lastShot;
@Override
public void create ()
{
System.out.println("game created");
ballImage = new Texture(Gdx.files.internal("ball.png"));
bulletImage = new Texture(Gdx.files.internal("bullet.png"));
cam = new OrthographicCamera();
cam.setToOrtho(true,320,480);//true starts top left false starts bottom left
batch = new SpriteBatch();
ball = new Circle();
ball.radius=20;
ball.x=320/2-ball.radius; // half screen size - half image
ball.y=480/2-ball.radius;
bullets = new Array<Circle>();
spawnBullet();
}
public void spawnBullet()
{
Circle bullet = new Circle();
bullet.radius=8;
bullet.x=bullet.radius; // half screen size - half image
bullet.y=MathUtils.random(0, 480-bullet.radius);
bullets.add(bullet);
System.out.println("x: "+bullet.x+" Y: "+bullet.y);
}
@Override
public void render ()
{
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
cam.update();
batch.setProjectionMatrix(cam.combined);
batch.begin();
batch.draw(ballImage,ball.x-ball.radius,ball.y-ball.radius);
for(Circle bullet: bullets)
{
batch.draw(bulletImage, bullet.x-bullet.radius, bullet.y-bullet.radius);
}
batch.end();
if(Gdx.input.isTouched())
{
Vector3 pos = new Vector3();
pos.set(Gdx.input.getX(), Gdx.input.getY(),0);
cam.unproject(pos);
ball.y = pos.y ;
}
if(ball.y<0+ball.radius)ball.y=ball.radius;
if(ball.y>480-ball.radius)ball.y=480-ball.radius;
Iterator<Circle> i = bullets.iterator();
while(i.hasNext())
{
Circle bullet = i.next();
//System.out.println("x2: "+bullet.x+" Y2: "+bullet.y);
if(bullet.y>240){
bullet.x++;
bullet.y--;}
bullet.x++;
//right border collision
if(bullet.x>320)
{
i.remove();
spawnBullet();
}
//circle collision
if(ball.overlaps(bullet))
{
i.remove();
spawnBullet();
}
}
}
}
答案 0 :(得分:0)
首先,你根本不使用Bullet类。你的子弹类应该扩展Circle,然后你可以在你的主类而不是Circle中使用它。
public class Bullet extends Circle {
private int startX;
private int startY;
public Bullet(int startX, int startY){
super();
this.startX = startX;
this.startY = startY;
}
// I added some constructors.
public Bullet(Circle circle, int startX, int startY){
super(circle);
this.startX = startX;
this.startY = startY;
}
public Bullet(float x, float y, float radius, int startX, int startY){
super(x, y, radius);
this.startX = startX;
this.startY = startY;
}
public Bullet(Vector2 position, float radius, int startX, int startY){
super(position, radius);
this.startX = startX;
this.startY = startY;
}
//getters and setters here...
}