我还是新手编程,所以我只是在玩一个我想做的无限赛跑游戏。我添加了我的角色图像和一个他必须试图克服的移动块。目前我有它,如果角色与块碰撞,他的速度将为0,所以他不能穿过对象。但是我的KeyListener会覆盖它。因此,一旦块击中角色,他就停止移动1个游戏滴答,但是如果你按下键并且他直接穿过块,则KeyListener继续增加他的速度。我无法弄清楚如何解决这个问题。
这是我的玩家类,它处理玩家的移动以及约束。
package runner;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Player implements KeyListener {
public static int playerX = 35;
public static int playerY = 285;
public static int playerWidth = 100;
public static int playerHeight = 100;
public static int playerVX, playerVY;
public static void update() {
playerX += playerVX;
playerY += playerVY;
constrain();
}
public static void paint(Graphics g) {
//g.setColor(Color.white);
//g.fillRect(playerX, playerY, 100,100);
}
public static void constrain() {
if (playerX + playerWidth >= Obstacle.getX() && playerX <=
Obstacle.getX() + Obstacle.width && playerY + playerHeight >=
Obstacle.getY()) {
playerX = 0;
}
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_LEFT) {
playerVX = -5;
}
if(keyCode == KeyEvent.VK_RIGHT) {
playerVX = 5;
}
if(keyCode == KeyEvent.VK_UP) {
playerVY = -5;
}
if(keyCode == KeyEvent.VK_DOWN) {
playerVY = 5;
}
}
@Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_LEFT) {
playerVX = 0;
}
if(keyCode == KeyEvent.VK_RIGHT) {
playerVX = 0;
}
if(keyCode == KeyEvent.VK_UP) {
playerVY = 0;
}
if(keyCode == KeyEvent.VK_DOWN) {
playerVY = 0;
}
}
}
谢谢!
答案 0 :(得分:0)
我正在开发一款游戏并遇到同样的麻烦(我也是游戏编程的新手)。我提出了一些处理碰撞的方法等。
此方法将在您的播放器类中进行:
public void applyBound(Bound bound) {
if (bound.x1 != null) {
if (x <= bound.x1) {
x = bound.x1;
}
}
if (bound.x2 != null) {
if (x >= bound.x2 - width) {
x = bound.x2 - width;
}
}
if (bound.y1 != null) {
if (y <= bound.y1) {
y = bound.y1;
}
}
if (bound.y2 != null) {
if (y >= (bound.y2 - height)) {
y = bound.y2 - height;
}
}
}
界限是:
public class Bound {
public Integer x1, x2, y1, y2;
public Bound(int x1, int x2, int y1, int y2) {
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
}
public Bound(Integer x1, Integer x2, Integer y1, Integer y2) {
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
}
}
“applyBound(boxBounds)”将是每次更新播放器时调用的最后一件事。
Bounds可以为null,因此您不需要例如上限。
在Bound类中,您可以设置屏幕的边界,以便玩家不会离开,或者您可以放入另一个角色的边缘。
您需要使用变量来查看是否按下了键,并在更新方法中添加了速度。
希望这有帮助!