问题在于,当我按下向下按钮时,图像(蓝色图片)消失了,它也没有向上移动但它可以左右移动,我不明白为什么?请帮忙。 (我正在使用RealJ)。 如果有一个网站可以帮助我进行2D侧滚动游戏,这对我也有帮助。
import java.applet.Applet;
import java.awt.event.*;
import java.awt.*;
public class projectblue extends Applet implements ActionListener,KeyListener,MouseListener {
Image blueboy,trees; //image variable
int size = 4,jump = 50, cx = 1, cy = 1;
public void init() {
blueboy = getImage(getDocumentBase(),"png.png");
trees= getImage(getDocumentBase(),"background.jpg");
addKeyListener( this );
addMouseListener( this );
}
public void paint(Graphics g)
{
int width = trees.getWidth(this);
int height = trees.getHeight(this);
//System.out.println("" + cx +","+ cy);
//The later images are drawn on top of the earlier ones.
g.drawImage(trees, 1 ,1, width*size,height*7,this);
g.drawImage(blueboy, cx, cy, this);
}
public void actionPerformed(ActionEvent e) {
repaint();
}
public void left(){
cx = cx -100;
// blueboy moves left
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
System.out.println("key pressed");
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
left();
}
if (key == KeyEvent.VK_RIGHT) {
cx = cx + 100;
//blueboy moves right
}
if (key == KeyEvent.VK_UP) {
while (cy >= 0 && cy <=1000)
cy = cy - 100;
if (cy < 0){
cy = 1;
//blueboy moves up, but if it goes out of bounds it goes back to the top
}
}
if (key == KeyEvent.VK_DOWN) {
while (cy >= 0 && cy <=1000)
cy = cy + 100;
if (cy > 1001){
cy = 999;
}
//blueboy moves down, but if it goes out of bounds it goes back to the bottim
}
repaint();
}
public void keyReleased(KeyEvent e) {
}
public void mouseEntered( MouseEvent e ) { }
public void mouseExited( MouseEvent e ) { }
public void mousePressed( MouseEvent e ) { }
public void mouseReleased( MouseEvent e ) { }
public void mouseClicked( MouseEvent e ) {
int x = getX();
int y = getY();
System.out.println("clicked at (" + x + ", " + y + ")");
} }
答案 0 :(得分:2)
那些while循环将占用你的GUI线程,使你的动画无用。相反,它们不应该是块吗?此外,您应该在花括号中包含所有块。你的缩进对你说谎,大括号会告诉你原因。
此外,您还需要在油漆覆盖中调用super.paint(g)
方法。
另外,这是一个赋值,如果是,你需要使用AWT / Applets而不是Swing进行编码吗?