如何让这个玩家移动?

时间:2016-03-16 22:13:58

标签: java swing jframe

所以我想制作自己的Pong游戏版本。我对这个程序的问题在于我的播放器无法移动。我认为我犯了一个错误,但因为我对java很陌生,所以我不能完全理解代码中的游戏机制。你们其中一个人可以仔细检查我的代码并告诉我什么是错的以及如何纠正它。另外,你们其中一个人会告诉我你在哪里学习或者我在哪里可以学习使用Java进行游戏开发。你的答案将非常感激。

窗口类

import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;

public class Window{
  public Window(){
    JFrame window = new JFrame();
    GamePanel gamePanel = new GamePanel();
    window.setSize(720, 480);
    window.setResizable(true);
    window.setTitle("2DGame");
    window.add(gamePanel);
    window.setUndecorated(false);
    window.setLocationRelativeTo(null);
    window.getContentPane().setBackground(Color.BLACK);
    window.setVisible(true);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setMinimumSize(new Dimension(720, 480));
  }
}

GamePanel Class

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class GamePanel extends JPanel{
  Wall wall = new Wall();
  Player player = new Player();
  public GamePanel(){
    setBackground(new Color(16, 16, 16));
  }
  public void paintComponent(Graphics g){
    super.paintComponent(g);
    wall.paintComponent(g);
    player.paintComponent(g);
  }
}

玩家类

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Player extends JPanel implements ActionListener, KeyListener{
  Timer t = new Timer(5, this);
  private int x = 28;
  private int y = 190;
  private int ydirection;
  private int speed = 1;
  public Player(){
    t.start();
    addKeyListener(this);
    setFocusable(true);
    setFocusTraversalKeysEnabled(false);
  }
  public void paintComponent(Graphics g){
    g.setColor(Color.WHITE);
    g.fillRect(x, y, 20, 100);
  }
  public void actionPerformed(ActionEvent e){
    y += ydirection;
    repaint();
  }
  public void keyPressed(KeyEvent e){
    int KeyCode = e.getKeyCode();
    if(KeyCode == KeyEvent.VK_W){
      ydirection -= speed;
    }
    if(KeyCode == KeyEvent.VK_S){
      ydirection += speed;
    }
  }
  public void keyReleased(KeyEvent e){
    int KeyCode = e.getKeyCode();
    if(KeyCode == KeyEvent.VK_W){
      ydirection = 0;;
    }
    if(KeyCode == KeyEvent.VK_S){
      ydirection = 0;
    }
  }
  public void keyTyped(KeyEvent e){}
}

0 个答案:

没有答案