我正在尝试为我的计算机学习课制作一款平台游戏,而现在我只是让角色的动作下降,也就是跳跃和左右移动。我跳了下来,当从构造函数调用时,它工作正常,但是,从事件侦听器调用时,框架没有更新,角色只是从一个地方跳到另一个地方而没有任何动画。我不知道为什么会这样,任何帮助将不胜感激,如果您对制作此类游戏有任何建议,我将非常高兴收到它。
提前致谢。
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制作看起来很烂的外观很容易。
最佳答案
切勿对没有此类侦听器的任何组件实施ActionListener
要注册侦听器,请使用使用匿名类的方法的内联方法,或实现一个反映侦听器并实例化以分配的新命名类。 Check out the tutorial page。
切勿在null
中使用setBounds(x, y, width, height)
布局和设置大小提示。了解正确的layout managers。
大多数时候,不要将大小设置为JFrame
。而是在布局组件并将其添加到内容窗格之后,在其上调用pack()
。
始终将GUI渲染任务放在EDT using SwingUtilities.invokeLater(Runnable)中。
切勿在Swing GUI或事件任务中调用Thread.sleep(milSecond)
,因此它可能有机会阻止EDT。