Java精灵掉落? [英] Java sprite falling?

查看:21
本文介绍了Java精灵掉落?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,我不知道如何用好标题.但我正在制作一个 Java 游戏,你在屏幕底部有一个桨,你可以左右移动它以避免小行星坠落.我有桨在工作,但我不知道如何使小行星坠落.小行星现在只是一个矩形.我还希望能够调整速度和小行星坠落的数量.这是我的代码:

Sorry, I did not know how to word the title well. But I am making a Java game where you have a paddle at the bottom of your screen and you can move it left and right in order to avoid falling asteroids. I have the paddle working, but I do not know how to make a falling asteroid. The asteroid will just be a rectangle for now. I also would like to be able to adjust the speed and how many asteroids fall. Here is my code:

public class Main extends Applet implements KeyListener, MouseListener {
private Rectangle rect;
private Rectangle asteroidrect;
private ArrayList<Integer> keysDown;
private Image dbImage;
private Graphics dbg;
Random randomGenerator = new Random();
int speed = 8;
int level = 1;     // change to 0 once start menu works
int xpos, ypos; 
int blockx = 0;
int blocky = 0;
int width = 1024;
int height = 768;
String version = "0.0.1";
public static final int START_X_POS = 160;
public static final int START_Y_POS = 160;
public static final int START_WIDTH = 256;
public static final int START_HEIGHT = 64;
boolean startClicked; 
boolean asteroid = false;


public void init() {
    setSize(width, height); 
    addKeyListener(this);
    addMouseListener(this);
    setBackground(Color.black); 
    Frame c = (Frame)this.getParent().getParent();
    c.setTitle("Asteroid Attack - Version " + version);
    keysDown = new ArrayList<Integer>();
    rect = new Rectangle(460, 700, 64, 12);
    asteroidrect = new Rectangle(0, 0, 48, 48);
    addAsteroid();
}

public void update(Graphics g) {
    dbImage = createImage(this.getSize().width, this.getSize().height);
    dbg = dbImage.getGraphics ();
    if (dbImage == null) {}
    dbg.setColor(getBackground ());
    dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
    dbg.setColor(getForeground());
    paint(dbg);
    g.drawImage(dbImage, 0, 0, this);
}


public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;
    if (level != 0) {
        g2.setPaint(Color.gray);
        g2.fill(rect);
        //if (asteroid == true) {
            g2.setPaint(Color.red);
            g2.fill(asteroidrect);
        //}
    }
}

@Override
public void keyPressed(KeyEvent e) {
    if (!keysDown.contains(e.getKeyCode()))
        keysDown.add(new Integer(e.getKeyCode()));
    moveChar();
}

@Override
public void keyReleased(KeyEvent e) {
    keysDown.remove(new Integer(e.getKeyCode()));
}

public void moveChar() {
    if (level != 0) {
        int x = rect.x;
        int y = rect.y;
        if (keysDown.contains(KeyEvent.VK_LEFT)) {
            x -= speed;
        }
        if (keysDown.contains(KeyEvent.VK_RIGHT)) {
            x += speed;
        }
        rect.setLocation(x, y);
        repaint(); 
    }
}

public void addAsteroid() {
    asteroid = true;    
}

@Override
public void keyTyped(KeyEvent e) {}

@Override
public void mouseClicked(MouseEvent me) {
    if (level == 0) {
        xpos = me.getX(); 
        ypos = me.getY();
        if (xpos >= START_X_POS && ypos >= START_Y_POS && xpos <= START_X_POS + START_WIDTH && ypos <= START_X_POS + START_HEIGHT ) {
            level = 1;
        }
    }
}

@Override
public void mouseEntered(MouseEvent me) {}

@Override
public void mouseExited(MouseEvent me) {}

@Override
public void mouseReleased(MouseEvent me) {}

@Override
public void mousePressed(MouseEvent me) {}
}

如您所见,我已经添加了一个小行星对象和矩形.

As you can see, I have already added an asteroid object, and the rectangle.

推荐答案

查看此示例.我使用了三个具有不同 x 和 y 点的不同小行星(矩形).我用不同的偏移量绘制它们.我使用了一个 Sing Timer 来设置重绘的延迟.当每隔这么多毫秒时,y 位置将更改并重新绘制.我还添加了上下键绑定以减慢或加快延迟.如果您有任何问题,请告诉我.

Check out this example. I used three different asteroids (rectangles) with different x and y points. I paint them with different offsets. I Used a Sing Timer to set the delay of repaint. When every so many milliseconds, the y locations will change and and repaint. I also added key binding for up and down to slow or speed up the delay. Let me know if you have any questions.

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Asteroids extends JPanel {
    int astr1X = 50;
    int astr1Y = 30;
    int astr2X = 150;        // x and y for 3 different asteriods
    int astr2Y = 60;
    int astr3X = 250;
    int astr3Y = 45;
    private final static int OFFSET = 5;
    private final static int WIDTH = 20;
    private final static int HEIGHT = 20;
    private Timer timer = null;

    public Asteroids() {
        timer = new Timer(300, new ActionListener() {     // timer with 150 millisecond delay
            public void actionPerformed(ActionEvent e) {
                astr1Y += OFFSET;                         // add 5 t the y poistion
                astr2Y += OFFSET;
                astr3Y += OFFSET;

                if (astr1Y > 590)        // if  y is size of screen
                    astr1Y = 10;         // make it 0. This brings 
                if (astr2Y > 590)        // asteroid back to top
                    astr2Y = 10;
                if (astr3Y > 590) 
                    astr3Y = 10;

                repaint();
            }
        });
        timer.start();

        Action downAction = new AbstractAction() {        // slows down the timer
            public void actionPerformed(ActionEvent e) {
                int delay = timer.getDelay();
                if (delay < 1000) {
                    delay += 100;
                    timer.setDelay(delay);
                }
            }
        };

        Action upAction = new AbstractAction() {         // speeds up the timer
            public void actionPerformed(ActionEvent e) {
                int delay = timer.getDelay();
                if (delay > 100) {
                    delay -= 100;
                    timer.setDelay(delay);
                }
            }
        };

        getInputMap().put(KeyStroke.getKeyStroke("UP"), "upAction");  // up key binding
        getActionMap().put("upAction", upAction);
        getInputMap().put(KeyStroke.getKeyStroke("DOWN"), "downAction");  // down key binding
        getActionMap().put("downAction", downAction);
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame();
        frame.add(new Asteroids());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

    }

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

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.fillRect(astr1X, astr1Y, WIDTH, HEIGHT);
        g.fillRect(astr2X, astr2Y, WIDTH, HEIGHT);
        g.fillRect(astr3X, astr3Y, WIDTH, HEIGHT);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

这篇关于Java精灵掉落?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆