我正在尝试为我的计算机学习课程制作一个平台游戏,现在我只是将角色的运动降下来,也就是跳跃和从一边到另一边移动。我得到了跳转,并且从构造函数调用时它工作正常,但是,当从事件监听器调用它时,框架不会更新,并且角色只是从一个地方跳转到另一个地方而没有任何类型的动画。我不知道为什么会这样,任何帮助都会非常感激,如果您对制作这类游戏有任何建议,我会非常乐意接受它。
提前致谢。
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或油漆中制作一个糟糕的样子。
答案 0 :(得分:1)
ActionListener
实施到任何没有此类监听器的组件null
布局并使用setBounds(x, y, width, height)
设置尺寸提示。正确学习layout managers。 JFrame
。相反,在布局组件并将其添加到内容窗格后,在其上调用pack()
。Thread.sleep(milSecond)
,因此它可能会阻止EDT。答案 1 :(得分:0)
尝试拨打
repaint();
刷新JFrame的显示