下面显示的代码是一个绿色的球,墙上有碰撞检测。
有什么方法可以改进吗?
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class Launcher extends Applet implements Runnable {
private static final long serialVersionUID = 1L;
private final int WIDTH = 50;
private final int HIEGHT = 50;
private int x = 5, velX = 1;
private int y = 5, velY = 1;
public void init() {
this.setSize(800, 600);
}
public void run() {
while (true) {
if (x > this.getWidth() - WIDTH) {
velX = -velX;
}
if (x < 0 + WIDTH / 2) {
x = 0 + WIDTH / 2;
velX = -velX;
} else {
x += velX;
}
if (y > this.getHeight() - HIEGHT) {
velY = -velY;
}
if (y < 0 + HIEGHT / 2) {
y = 0 + HIEGHT / 2;
velY = -velY;
} else {
y += velY;
}
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void start() {
Thread thread = new Thread(this);
thread.start();
}
public void stop() {
}
public void destroy() {
}
public void paint(Graphics g) {
g.setColor(Color.GREEN);
g.fillOval(x, y, WIDTH, HIEGHT);
}
}
答案 0 :(得分:1)
update(Graphics)
方法并且只是清除球的位置,那么重绘的次数就会少得多,而且(有点)更顺畅。像这样:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class Test extends Applet implements Runnable {
private static final long serialVersionUID = 1L;
private final int SIZE = 50;
private final int VELOCITY = 1;
private int x = 5, velX = VELOCITY;
private int y = 5, velY = VELOCITY;
@Override
public void init() {
this.setSize(800, 600);
}
@Override
public void run() {
while (true) {
x += velX;
if (x > this.getWidth() - SIZE) {
x = 2*(this.getWidth() - SIZE)-x;
velX = -velX;
}
else if (x < 0) {
x = -x;
velX = -velX;
}
y += velY;
if (y > this.getHeight() - SIZE) {
y = 2*(this.getHeight() - SIZE)-y;
velY = -velY;
}
else if (y < 0) {
y = -y;
velY = -velY;
}
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void start() {
new Thread(this).start();
}
@Override
public void stop() {
}
@Override
public void destroy() {
}
@Override
public void update(Graphics g)
{
g.clearRect(
x - VELOCITY,
y - VELOCITY,
SIZE+2*VELOCITY,
SIZE+2*VELOCITY
);
paint(g);
}
@Override
public void paint(Graphics g) {
g.setColor(Color.GREEN);
g.fillOval(x, y, SIZE, SIZE);
}
}