我创建了一个 Bullet 类,使用 vector 绘制子弹并将它们存储在数组中。 我已经尝试过,但无法弄清楚如何检测与这些子弹的碰撞。
这是 Bullet 类:
public void render(GameContainer gc, Graphics g) throws SlickException {
if(active) {
g.setColor(Color.red);
g.fillOval(pos.getX()-10, pos.getY()-10, 20, 20);
g.drawString("BulletX: "+pos.getX(), 400, 100);
g.drawString("BulletY: "+pos.getY(), 400, 120);
}
}
public void update(int t) {
if(active) {
Vector2f realSpeed = speed.copy();
pos.add(speed.copy().scale(t/1000.0f));
pos.add(realSpeed);
lived += t;
if(lived > MAX_LIFETIME) {
active = false;
}
}
}
这是 Play 类:
我已经使用以下代码在 init 方法中填充了数组:
bullets = new Bullet[8];
for(int i=0; i<bullets.length; i++) {
bullets[i] = new Bullet();
}
在更新类中,我使用此代码在玩家选择开火时显示子弹:
if(t > FIRE_RATE && gc.getInput().isKeyDown(Input.KEY_SPACE)) {
if(player == movingUp) {
bullets[current] = new Bullet(new Vector2f(420,295), new Vector2f(0,-1));
current++;
if(current >= bullets.length) current = 0;
t = 0;
}
这是玩家和敌人的移动
//up
if(input.isKeyDown(Input.KEY_UP)) {
player = movingUp;
playerPositionY += delta * .3f; //moves world
enemyPositionY += delta * .3f;
if(playerPositionY > 273) { //collision detection
playerPositionY -= delta * .3f;
enemyPositionY -= delta * .3f;
}
}
if(enemyPositionY > shiftY) {
enemyPositionY -= delta *.1f;
}
if((enemyPositionX >= 355 && enemyPositionX <= 440) && (enemyPositionY >= 230 && enemyPositionY <= 310)) {
enemyPositionX = playerPositionX;
enemyPositionY = playerPositionY;
lives--;
}
您能帮我了解如何检测这些子弹的碰撞吗?
最佳答案
您是否尝试过在项目符号类中的项目符号中添加矩形属性(事先初始化它并在更新方法中更新位置)?类似的东西
bulletRectangle = new Rectangle(pos.getX(), pos.getY(), 20, 20);
然后为玩家创建矩形,例如playerRectangle,然后使用 intersect 函数循环检查碰撞。
collision = false;
for(int i = 0; i < bullets.length; i++){
if(playerRectangle.intersects(bullet[i].getBulletRectangle())){
collision = true;
}
//perform whatever you want to happen if bullet collides with player
就个人而言,我会使用数组列表,因为您不必将项目符号数量设置为特定数字,但这应该可以正常工作。
关于java - slick2d 中的子弹数组碰撞检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16793656/