如何移动背景图片,使其与角色一起移动?

6ju8rftf  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(286)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JPanel;

public class Screen extends JPanel implements KeyListener, ActionListener, MouseListener, MouseMotionListener {

    private JButton playB;

    private BufferedImage myImage;

    private boolean win = false;

    private Background background;
    private Mario mario;

    public Dimension getPreferredSize() {
        return new Dimension(860, 600);
    }

    public Screen() {

        background = new Background();
        mario = new Mario(50, 475);

        setFocusable(true);
        addKeyListener(this);
        addMouseMotionListener(this);
        addMouseListener(this);
        this.requestFocusInWindow();
    }

    public void paintComponent(Graphics g) {

        super.paintComponent(g);

        background.drawBackground(g);
        mario.drawMario(g);

        repaint();

    }

    public void animate() {

        while (true) {

            try {
                Thread.sleep(10);
            }
            catch(InterruptedException ex) {
                Thread.currentThread().interrupt();
            }

            if (mario.getHealth() > 0) mario.tick();

            repaint();
        }
    }

    public void keyTyped(KeyEvent e) {

    }

    public void keyPressed(KeyEvent e) {

        if (mario.getHealth() > 0 && !win) {

            if (e.getKeyCode() == KeyEvent.VK_A) {
                mario.setVelX(-2);
            }
            else if (e.getKeyCode() == KeyEvent.VK_D) {
                mario.setVelX(2);
            }
            else if (e.getKeyCode() == KeyEvent.VK_A && e.getKeyCode() == KeyEvent.VK_D) {
                mario.setVelX(0);
            }
        }
    }

    public void keyReleased(KeyEvent e) {

        if (mario.getHealth() > 0 && !win) {

            if (e.getKeyCode() == KeyEvent.VK_A) {
                mario.setVelX(0);
            }
            else if (e.getKeyCode() == KeyEvent.VK_D) {
                mario.setVelX(0);
            }
            else if (e.getKeyCode() == KeyEvent.VK_A && e.getKeyCode() == KeyEvent.VK_D) {
                mario.setVelX(0);
            }
        }
    }

每当我移动我的角色我想移动的背景图片以及,我有完整的抓取水平的图片,这样我就可以削减它的碎片和改变图片一旦字符到达最右边的面板,但我想移动它作为我的角色移动。我也很恼火,每当我同时按下两个键(a,d)字符停留在一个地方一秒钟,然后移动,如果不是很难解决,我真的很感谢这里的帮助。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题