我对Java和编程非常陌生,所以我尝试编写一个简单的程序,其唯一的工作就是使用箭头键移动球并使用空格按钮跳转。程序编译但球不动。
我可能没有完全理解Applet的原则,你能解释一下我犯的错误吗?
小程序:
package test_game;
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Starting_Point extends Applet implements Runnable, KeyListener {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 700;
private static final int HEIGHT = 300;
Character Phil;
Thread thread;
@Override
public void init() {
setSize(WIDTH,HEIGHT);
Phil = new Character(50, 200);
}
@Override
public void start() {
thread = new Thread(this);
thread.start();
}
public void run() {
while (true) {
repaint();
}
}
@Override
public void paint(Graphics arg0) {
Phil.paint(arg0);
}
@Override
public void keyPressed(KeyEvent arg0) {
switch (arg0.getKeyCode()) {
case (KeyEvent.VK_LEFT): Phil.setX(Phil.getX() - Phil.getDx());
break;
case (KeyEvent.VK_RIGHT): Phil.setX(Phil.getX() + Phil.getDx());
break;
case (KeyEvent.VK_SPACE): Phil.setDy(Character.gravity * Character.dt);
Phil.setY(Phil.getY() + .5*Character.gravity*Character.dt*Character.dt + Phil.getDy()*Character.dt + Character.jump);
break;
}
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
角色等级:
package test_game;
import java.awt.Color;
import java.awt.Graphics;
public class Character {
private int x;
private int y;
private int radius = 10;
Graphics g;
public static final int gravity = 15;
private static final double dx = 4;
public double dy;
public static final double dt = .2;
public static final int jump = 30;
public Character(int x, int y) {
this.x = x;
this.y = y;
}
public void setX(double d) {
this.x = (int) d;
}
public void setY(double d) {
this.y = (int) d;
}
public double getDx() {
return dx;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setDy(double dy) {
this.dy = dy;
}
public double getDy() {
return dy;
}
public void paint(Graphics g) {
g.setColor(Color.black);
g.fillOval(x, y, radius, radius);
}
}
答案 0 :(得分:1)
您已在代码中定义了KeyListener
。但是,您忘记将此事件侦听器注册到组件,因此它永远不会被调用。
如何注册KeyListener:
将以下代码放入start()
:
this.addKeyListener(this);
这解决了角色向左或向右移动的问题,但是跳跃没有被修复,修复跳跃需要更多代码来计算你需要的正确y +,当前代码总是加0(当你按空格时,使用你使用的(int)四舍五入到y坐标。