我最近用 java 构建了我的第一个简单的横向滚动游戏,但我遇到了一些延迟,我不知道为什么。当我侧身移动我的角色时,它似乎在改变速度,大部分时间速度很快,但有时速度变慢。这让游戏的感觉非常奇怪。我希望有人可以在这里为我指明正确的方向,我将在下面发布我的课程:
主类:
public class MainGame {
public static void main(String[] args) {
Frame frame = new Frame();
}
}
框架类:
import javax.swing.JFrame;
public class Frame extends JFrame{
public Frame(){
add(new Board());
setTitle("2-D Test Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800,325);
this.setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
}
板级:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Board extends JPanel implements ActionListener{
private Player p;
private Timer timer;
private Image background;
public Board(){
super();
p = new Player();
addKeyListener(new ActionListener());
setFocusable(true);
ImageIcon i = new ImageIcon("C:/test.png");
background = i.getImage();
timer = new Timer(5,this);
timer.start();
}
public void actionPerformed(ActionEvent arg0) {
p.move();
repaint();
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(background,p.nx,0,null);
g2d.drawImage(p.getImage(), 350, p.getY(), null);
}
private class ActionListener extends KeyAdapter{
public void keyReleased(KeyEvent e){
p.keyReleased(e);
}
public void keyPressed(KeyEvent e){
p.keyPressed(e);
}
}
}
玩家等级:
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Player {
private Image img;
int x,y,dx,dy,nx;
long time;
private final int SPEED = 2;
private final int GRAV = 1;
boolean left,right,isJumping;
public Player(){
ImageIcon i = new ImageIcon("C:/plager.png");
img = i.getImage();
x = 350;
y = 160;
dx = 0;
dy = 0;
nx = 0;
left = false;
right = false;
isJumping = false;
}
public void move(){
x += dx;
nx = (nx-dx);
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public Image getImage(){
return img;
}
public void keyReleased(KeyEvent e) {
int code = e.getKeyCode();
if(code == KeyEvent.VK_LEFT){
left = false;
if(right){
dx = SPEED;
}else{
dx = 0;
}
}else if(code == KeyEvent.VK_RIGHT){
right = false;
if(left){
dx = -SPEED;
}else{
dx = 0;
}
}
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if(code == KeyEvent.VK_LEFT){
left = true;
dx = -SPEED;
}else if(code == KeyEvent.VK_RIGHT){
right = true;
dx = SPEED;
}
}
}