gpt4 book ai didi

Java 动画不工作

转载 作者:太空宇宙 更新时间:2023-11-04 12:45:47 25 4
gpt4 key购买 nike

我正在尝试用 Java 制作一个正方形的动画,但是当我按下按键时,正方形会在后面留下一条痕迹。我希望方 block 本身移动时不会像蛇一样留下痕迹。

我该如何解决这个问题?我能做些什么来解决这个问题吗?

这是我的代码:

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;

import javax.swing.JFrame;

public class Main extends Canvas implements KeyListener, Runnable {

Thread t;
boolean running = false;

int x = 200;
int y = 200;
int velx;
int vely;

public Main() {
setFocusable(true);
requestFocus();
addKeyListener(this);
}

public void run() {
while (running) {
render();
tick();
}
stop();
}

synchronized void start() {
if (running) return;

running = true;
t = new Thread(this);
t.start();
}

synchronized void stop() {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.exit(1);
}

public void render() {

BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();

g.setColor(Color.CYAN);
g.fillRect(x, y, 300, 300);

g.dispose();
bs.show();

}

public void tick() {
x += velx;
y += vely;
}

@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_RIGHT) {
velx += 5;
} else if (key == KeyEvent.VK_LEFT) {
velx -= 5;
} else if (key == KeyEvent.VK_DOWN) {
vely += 5;
} else if (key == KeyEvent.VK_UP) {
vely -= 5;
}
}

@Override
public void keyTyped(KeyEvent e) {}

@Override
public void keyReleased(KeyEvent e) {
velx = 0;
vely = 0;
}

public static void main (String args[]){

JFrame frame = new JFrame("Animation");
Main main = new Main();

frame.setSize(1200, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(main);
frame.setResizable(false);
frame.setVisible(true);

main.start();

}

}

最佳答案

在绘制具有更新坐标的新正方形之前,您应该始终删除 Canvas 上已绘制的正方形(即用背景颜色覆盖它)。为此,您可以按如下方式修改代码:

int prevX, prevY;

public void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();

// erase the previous square
g.setColor(getBackground());
g.fillRect(prevX, prevY, 300, 300);

// draw the new square
g.setColor(Color.CYAN);
g.fillRect(x, y, 300, 300);

g.dispose();
bs.show();
}

public void tick() {
// backup the previous coordinates
prevX = x;
prevY = y;

x += velx;
y += vely;
}

关于Java 动画不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36348113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com