首页 > 解决方案 > 在 Java 中移动 GObject

问题描述

大家早上好,我是Java新手,因此希望您能帮助我。所以,这就是我面临的问题。顺便说一句,我应该使用 ASM Graphics。

那是我的 Gobject 类

package objects;

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

import acm.graphics.*;

public class Mario extends GCompound implements ActionListener{
public static double dx;
public static double dy;
public static GImage mario;
private static int x = 40;
private static int y = 350;
private final int min = 350;
private final int gravity = 5;
private final int speed = 5;
private final int max_jump = min - 220;
private int direction;
private int number = 1;
public static boolean standing = true;

public Mario () {
    if (standing == true) {
        mario = new GImage("Mario_Big_Right_Still.png");
        mario.setSize(60, 105);
    }
    else {
        mario = new GImage("Mario_Big_Crouch_Left.png");
        mario.setSize(60, 95);
    }
    mario.setLocation(x + dx, y + dy);
    add(mario);
}

public boolean onBottom() {
        if (mario.getLocation().getY() >= min ) return true;
    return false;
}

public void keyPressed(KeyEvent e) {

    int key = e.getKeyCode();

    if (key == KeyEvent.VK_LEFT) {
            dx = -5;
    }
    if (key == KeyEvent.VK_RIGHT) {
            dx = 5;
    }
    if (key == KeyEvent.VK_UP) {
            dy = -5;
    }
    if (key == KeyEvent.VK_DOWN) {
            standing = false;
    }
}

public void keyReleased(KeyEvent e) {

    int key = e.getKeyCode();

    if (key == KeyEvent.VK_LEFT) {
            dx = 0;
    }

    if (key == KeyEvent.VK_RIGHT) {
            dx = 0;
    }

    if (key == KeyEvent.VK_UP) {
            dy = 5;
    }

    if (key == KeyEvent.VK_DOWN) {
            standing = true;
    }
}

@Override
public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub

}
}

这是应用程序文件

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

import acm.graphics.*;
import acm.program.*;
import objects.Mario;

public class Application extends GraphicsProgram implements ActionListener {
private static final long serialVersionUID = 1L;

public static final int WINDOW_WiDTH = 800;
public static final int WINDOW_HEIGHT = 600;
public static final int REFRESH = 60;
public int dx;
public int dy;

public void run () {
    setSize(WINDOW_WiDTH, WINDOW_HEIGHT);
    addKeyListeners();
    while (true) {
        Mario mario = new Mario();
        add(mario);
        mario.setLocation(mario.getLocation().getX() + dx, mario.getLocation().getY() + dy);
        pause(REFRESH);
    }
}
}

此外,我还需要能够更改图像。任何建议都非常受欢迎。提前致谢。

标签: java

解决方案


推荐阅读