gpt4 book ai didi

Java,在最后一个图像结束的同一点重绘滚动背景图像

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

我的问题是我有一个长度为 X 的图像,我想让它在我的游戏背景中不断滚动。

为了做到这一点,对于玩家来说,下一个背景图像必须在上一个图像结束的位置重新绘制并不明显,这是我无法弄清楚的。

目前我可以连续重绘图像,但是当旧图像结束时,新图像会在 (0,0) 处绘制,因此很明显背景正在被重绘。

我知道问题是什么,但解决办法就是避开我。问题是,当我重新绘制图像时,我将位置重置为 0。目前我无法找到另一种方法来执行此操作,所以也许有人可以以某种方式帮助我。

顺便说明一下,JPanel 的宽度为 1000。

这是到目前为止的代码:

package cje.chris.edwards.game;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.*;

public class Board extends JPanel implements ActionListener{

Player player;
Image background;
Timer timer;
private int scrollSpeed, location;

public Board(){

player = new Player();
this.addKeyListener(new Listener());
setFocusable(true);
ImageIcon img_ic = new ImageIcon("map.png");
background= img_ic.getImage();
location = 0;
//5 milliseconds
scrollSpeed = -2;
timer = new Timer(5, this);
timer.start();


}

@Override
public void actionPerformed(ActionEvent e) {
//called using timer.start() and its delay
repaint();

}

public void paint(Graphics g){
super.paint(g);
Graphics2D graphics_2d = (Graphics2D) g;

//This is the section where my problem lies.
if(location != 0 && Math.abs(location) % (background.getWidth(null) - 1000) == 0){
graphics_2d.drawImage(background, 1000, 0, null);
location = 0;
}
graphics_2d.drawImage(background, location += scrollSpeed, 0, null);
graphics_2d.drawImage(player.getImage(), 50, 100, null);

System.out.println(location);
}

private class Listener extends KeyAdapter{


public void keyPressed(KeyEvent e){
scrollSpeed = -1;

player.move(e);
}



}

}

有没有办法可以将位置重置到最后一张图像的末尾?所以它看起来完全无缝。再次感谢!

这是我正在使用的图像,以防万一有人想尝试我的代码: https://warosu.org/data/ic/img/0015/95/1385339455019.png

最佳答案

试试这个

public void paint(Graphics g){
super.paint(g);
Graphics2D graphics_2d = (Graphics2D) g;

// define bounds by width of image
while (location > background.getWidth(null)){
location -= background.getWidth(null);
}
while (location < -background.getWidth(null)){
location += background.getWidth(null);
}
// draw image twice to handle any overlap
graphics_2d.drawImage(background, location += scrollSpeed, 0, null);
graphics_2d.drawImage(background, location + background.getWidth(null), 0, null);

System.out.println(location);
}

关于Java,在最后一个图像结束的同一点重绘滚动背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24375716/

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