从同一个类中的方法调用方法

时间:2015-09-01 03:53:50

标签: methods collision-detection method-call

我有一个平台游戏类,可以创建一个窗口并生成平台和一个"字符"。它使用另一个类平台来制作平台。这个角色应该跳起并降落在平台上。我使用getBoundsgetTopY函数进行碰撞检测,但它们仅适用于第一个平台。我怎样才能让他们在多个平台上工作?

public class Platformer extends JPanel {
    Platform platform = new Platform(this);
    Character character = new Character(this);

    public Platformer() {
        addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
                character.keyTyped(e);
            }

            @Override
            public void keyReleased(KeyEvent e) {
                character.keyReleased(e);
            }

            @Override
            public void keyPressed(KeyEvent e) {
                character.keyPressed(e);
            }
        });

        setFocusable(true);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        platform.Location(150,200);
        platform.paint(g2d);

        platform.Location(200,120);
        platform.paint(g2d);

        character.paint(g2d);
    }

    private void move(){
        character.move();
    }

    public static void main(String args[]){
        JFrame frame = new JFrame("Mini Tennis");

        //create new game
        Platformer platformer = new Platformer();                

        //add game
        frame.add(platformer);

        //size
        frame.setSize(400, 400);            
        frame.setVisible(true);

        //set close condition
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        while (true) {          
            platformer.move();
            platformer.repaint();

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

public class Platform {
    private static final int Height = 10;
    private static final int Width = 60;
    int x;
    int Y;
    private Platformer platformer;

    public Platform(Platformer platformer) {
        this.platformer = platformer;
    }

    public void Location(int xin, int yin) {
        x = xin;
        Y = yin;
    }

    public void paint(Graphics2D g) {       
        g.fillRect(x, Y, Width, Height);       
    }

    public Rectangle getBounds() {
        return new Rectangle(x, Y, Width, Height);
    }

    public int getTopPlat() {
        return Y;
    }
}

1 个答案:

答案 0 :(得分:0)

实际上你只有一个平台。并且您在不同的地方绘制了这个平台两次(paint中的Platformer函数):

platform.Location(150,200);
platform.paint(g2d);

platform.Location(200,120);
platform.paint(g2d);

因此我想你只处理一个平台(坐标为200和120)。您必须保留所有平台并分别处理每个平台。