gpt4 book ai didi

java - 弹跳矩形(图形g)

转载 作者:行者123 更新时间:2023-12-01 19:43:49 24 4
gpt4 key购买 nike

我正在用 Java 处理图形。目前我有一个从左向右移动的矩形。我希望它在击中 Canvas 右侧时开始向左移动,在击中右侧时向左移动,我已经包含了一个游戏循环,因为这最终将变成我的第一个非常基本的游戏。谢谢。

P.S - 我遵循了此代码不同部分的一些教程,因此为什么它可能有点困惑,我正在处理它:)

主类:

public class Game extends JFrame implements Runnable {

private Canvas canvas = new Canvas();
private RenderHandler renderer;
private boolean running = true;
public static int WIDTH = 1200, HEIGHT = WIDTH / 12*9;
public static int moveX =WIDTH/2;

public Game() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(WIDTH, HEIGHT);
setLocationRelativeTo(null);
setLocationRelativeTo(null);
add(canvas);
setVisible(true);
canvas.createBufferStrategy(3);
renderer = new RenderHandler(getWidth(), getHeight());

}


public void update() {

}


public void render() {
BufferStrategy bufferStrategy = canvas.getBufferStrategy();
Graphics graphics = bufferStrategy.getDrawGraphics();
super.paint(graphics);

renderer.render(graphics);

graphics.dispose();
bufferStrategy.show();
}

public void run() {
BufferStrategy bufferStrategy = canvas.getBufferStrategy();
int FRAMES = 0;
int TICKS = 0;
long lastTime = System.nanoTime();
double unprocessed = 0;
double nsPerSecs = 1000000000 /60.0;
long Timer = System.currentTimeMillis();
while(running) {
long now = System.nanoTime();
unprocessed += (now - lastTime) / nsPerSecs;
lastTime = now;

if(unprocessed >= 1) {
TICKS ++;
update();
unprocessed -= 1;
}
try
{
Thread.sleep(3);
}catch (InterruptedException e) {
e.printStackTrace();
}
FRAMES++;
render();

if(System.currentTimeMillis() - Timer > 1000) {
System.out.println("Ticks: " + TICKS + " FPS: " + FRAMES);
TICKS = 0;
FRAMES = 0;
Timer += 1000;
}
}
}
public static void main(String[] args) {
Game game = new Game();
Thread gameThread = new Thread(game);
gameThread.start();
}

}

绘制图形的类:

public class RenderHandler {
public RenderHandler(int width, int height) {

}

public void render(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, Game.WIDTH, Game.HEIGHT);
g.setColor(Color.RED);
g.fillRect(Game.moveX, Game.HEIGHT/2, 50, 50);
if (Game.moveX >= Game.WIDTH) {
Game.moveX ++;
} else if (Game.moveX <= 0) {
Game.moveX --;
}else { Game.moveX++;
}
}
}

最佳答案

如果您知道如何在屏幕上绘图以及东西如何工作,我认为这更多的是关于逻辑的理解。

我从你的问题中残酷地撕下来的代码片段就在渲染发生的地方旁边(这是一个问题,因为我认为它相当无组织;我建议游戏逻辑和渲染在两个不同的函数中进行)。它基本上是说,如果超出屏幕右侧,它会向右移动,如果没有超出屏幕左侧,它会向左移动,最后,如果没有超出屏幕左侧,它会向左移动。

if (Game.moveX >= Game.WIDTH) {
Game.moveX ++;
} else if (Game.moveX <= 0) {
Game.moveX --;
}else { Game.moveX++;
}

如果您希望它弹跳,则必须使用 boolean 值来跟踪其移动状态,或者,如果您想要更多功能,请使用一对 float 或 double ( float 通常用于 Java 游戏设计)一个是跟踪它的位置,另一个是跟踪它的速度。我现在手头紧,我会回来的。

关于java - 弹跳矩形(图形g),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54356219/

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