【发布时间】:2013-12-30 03:10:18
【问题描述】:
我正在尝试为我的计算机学习课程制作一个平台游戏,而现在我只是让角色的运动下降,也就是跳跃和左右移动。我得到了跳转,从构造函数调用时它工作正常,但是,当从事件侦听器调用它时,帧不会更新,角色只是从一个地方跳到另一个地方,没有任何动画。我不知道为什么会发生这种情况,任何帮助将不胜感激,如果您对制作此类游戏有任何建议,我将非常乐意接受。
提前致谢。
import java.awt.event.*;
import javax.swing.*;
public class LooperGui extends JFrame implements ActionListener{
//setting up all of the variables and components of the JFrame
private JLabel stick = new JLabel();
JButton g = new JButton("jump");
ImageIcon h = new ImageIcon("src//stickGuy.jpg");
int x = 100, y = 120, maxY = y, minY = 168;
double time = 5;
int fps = 25, frames = (int) (time*fps);
double timePerFrame = (time/frames);
public LooperGui(){
setSize(500, 500);
//setUndecorated(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setLayout(null);
setResizable(false);
stick.setIcon(h);
g.setBounds(10, 10, 100, 30);
g.addActionListener(this);
add(g);
stick.setBounds(x, y, h.getIconWidth(), h.getIconHeight());
add(stick);
jump();//call jump from the constructor and it will be perfectly animated, the exact way that I intended it to be
}
public void jump(){
//I attempted to make the jump as close to reality as possible so I used
//kinematic equations to set the characters height in the air at any given time
//from here it is easy to change the characters side to side movement, as it is simply changing the x value
//the first for loop if for the ascent, and the second one is for the descent
for(double t = time; t>0; t-=timePerFrame){
y = (int) ((9.81*(t*t))/2);
stick.setBounds(x, y, h.getIconWidth(), h.getIconHeight());
x+=1;
//there may be a problem with using thread.sleep(), not really sure
try {
Thread.sleep(4);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
for(double t = 0; t<time; t+=timePerFrame){
y = (int) ((9.81*(t*t))/2);
stick.setBounds(x, y, h.getIconWidth(), h.getIconHeight());
x+=1;
try {
Thread.sleep(4);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == g){
jump();//calling jump from the action performed method makes the character jump positions
}
}
}
我目前正在为角色使用火柴人,无法链接它,因为我没有足够高的代表。但是在 Photoshop 或 Paint 中制作一个看起来很糟糕的照片很容易。
【问题讨论】:
标签: java swing jframe event-listener