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

时间:2014-06-23 22:40:26

标签: java swing paint keylistener imageicon

我的问题是我有一个长度为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

1 个答案:

答案 0 :(得分:1)

试试这个

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);
}