[英]Why doesn't the ball move around in my applet when I press a button?
我對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);
}
}
您已經在代碼內部定義了KeyListener
。 但是,您忘了將此事件偵聽器注冊到組件,因此它從未被調用。
如何注冊您的KeyListener:
將以下代碼放入start()
:
this.addKeyListener(this);
這解決了字符從左右移動的問題,但是跳轉並沒有固定,解決跳轉需要更多代碼來計算所需的正確y +,當前代碼始終加0(使用(int)(您使用的整數)到按空格鍵時的y坐標。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.