做一个精灵跳

时间:2017-01-25 06:51:15

标签: java swing keylistener

我正在为学校制作一个2D战斗游戏(想想粉碎兄弟),我无法弄清楚如何使用速度为y进行精灵跳跃。这是我的KeyPressed代码:

if (key == KeyEvent.VK_LEFT)
    {
        p2.setVelX(-3);
    }

    else if (key == KeyEvent.VK_RIGHT) {
        p2.setVelX(3);
   }

    else if (key == KeyEvent.VK_UP) {
        p2.setVelY(-3);
    }        

    else if (key == KeyEvent.VK_DOWN)
    {
        p2.setVelY(3);
    }

这里有一些来自玩家:

public class Player {
private double x; 
private double y;
private BufferedImage player;

private double velX = 0;
private double velY = 0;
public Player(double x, double y, Game game) {
    this.x = x;
    this.y = y;
    SpriteSheet ss =  new SpriteSheet(game.getSpriteSheet());
    player = ss.grabImage(1,1,32,32);
}

private void initPlayer() {

}

public void tick()
{
    x+=velX;
    y+=velY;

    if(x <= 0)
        x=0;

    if (x >= 940-32)
        x=940-32;

    if(y <= 0)
        y=0;

    if (y >= 370-64)
        y=370-64;
}

public void render(Graphics g)
{
    g.drawImage(resize(player,64,64), (int)x, (int)y, null);
}

public double getX() {
    return x;
}

public double getY() {
    return y;
}

public void setX(double x)
{
    this.x = x;
}

public void setY(double y)
{
    this.y = y;
}

public void setVelX(double velX)
{
    this.velX = velX;
}

public void setVelY(double velY)
{
    this.velY = velY;
}
public static BufferedImage resize(BufferedImage img, int newW, int newH) { 
    Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
    BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2d = dimg.createGraphics();
    g2d.drawImage(tmp, 0, 0, null);
    g2d.dispose();

    return dimg;
} 

}

我为VK_UP if()语句添加了什么?我是否必须使用swing和KeyStroke而不是关键的监听器?感谢。

0 个答案:

没有答案