我目前正在尝试自学Java编程,我正在使用eclipse,我有一个创建pong的教程,但它是如何丢失的。我唯一遇到麻烦的部分是完成球类课程。我已经让它渲染并在窗口中正确显示,但实际上并没有做任何事情,它只是保持静止。这是因为我不知道我需要什么代码,所有的谷歌搜索结果都是对不能工作的代码的失望。
到目前为止,这就是我在球课上学到的全部内容。
import java.awt.Color;
import java.awt.Graphics;
public class Ball extends Entity {
public Ball(int x, int y, Color color) {
super(x, y, color);
this.width = 15;
this.height = 15;
int yspeed = 1;
int xspeed = 2;
}
public void render( Graphics g ) {
super.render( g );
}
public void update() {
if (y <= 0) {
y = 0;
}
if (y >= window.HEIGHT - height - 32 ) {
y = window.HEIGHT - height -32;
}
}任何建议都将不胜感激。
发布于 2013-06-11 22:03:23
到目前为止,您的ball类看起来很好,您已经编写(或从教程中复制)。你遗漏了把“生活”放在里面的代码,例如,让球移动的代码。您有一些字段,如xspeed和yspeed,但没有代码将增量从一个时间单位实际应用到另一个时间单位。(我希望)定期调用的update()方法应该将这两个值应用于x和y字段:
public void update() {
x += xspeed;
y += yspeed;
if (y <= 0) {
y = 0;
}
if (y >= window.HEIGHT - height - 32 ) {
y = window.HEIGHT - height -32;
}
}这就是update部件所需要的。下一个重要的事情是实现当球击中墙壁或球拍时会发生什么的逻辑。对于这样的事件,您需要操作xspeed和yspeed变量。
发布于 2013-06-11 22:03:49
显而易见的一步是:
public void update() {
x += xspeed;
y += yspeed;
if (y <= 0) {
y = 0;
}
if (y >= window.HEIGHT - height - 32 ) {
y = window.HEIGHT - height -32;
}
// TODO: Code to change the direction of the ball (i.e. xspeed and yspeed)
// when it hits a wall or paddle.
}而且,在调用render()之前,您一定不要忘记调用update()。
https://stackoverflow.com/questions/17045929
复制相似问题