如何用双缓冲在Java中显示Pacman的张嘴/闭嘴动画?
我试图在我正在制作的一次性吃豆人游戏中展示吃豆人角色著名的张嘴/闭合动画,以自学游戏编程。
我正在做的是绘制张开嘴的图像,然后在完全相同的 (x/y) 位置重新绘制闭合的嘴图像。 但这不起作用,我只看到一直闭着嘴的动画。
如果我将其放入循环中,系统就会冻结,您会看到张开嘴的图像闪烁,但您看不到图像被替换。
我已经测试并确保两个图像都按预期正确加载。
这是我的 startAnim()
函数,当您双击小程序时会调用它:
public void beginGame() //Called from engine.java
{
isRunning=true;
repaint();
pacman.startAnim();
}
public void startAnim() //In different class, pacman.java
{
Image orig;
while (engine.isRunning)
{
orig=this.getCurrentImg();
draw(engine.getGraphics());
this.setCurrImg(currImg2);
this.draw(engine.getGraphics());
this.setCurrImg(orig);
this.draw(engine.getGraphics());
try
{
Thread.sleep(100);
}
catch (InterruptedException e) {}
}
}
public void draw(Graphics g) //Called from engine.paint()
{
g.drawImage(getCurrentImg(), getX(),
getY(), engine);
}
I'm trying to show the famous mouth opening/closing animation of the pacman character in a throwaway pacman game I'm making to teach myself game programming.
What I'm doing is drawing the open mouth image, then redrawing the closed mouth image at the exact same (x/y) location. But this doesn't work, and I just see the closed mouth animation all the time.
If I put this in a loop, the system just freezes and you see flickering where the open mouth image this, but you don't see the images being replaced.
I've tested and made sure that both images are being loaded correctly and as expected.
Here's my startAnim()
function, its called when you double click at the applet:
public void beginGame() //Called from engine.java
{
isRunning=true;
repaint();
pacman.startAnim();
}
public void startAnim() //In different class, pacman.java
{
Image orig;
while (engine.isRunning)
{
orig=this.getCurrentImg();
draw(engine.getGraphics());
this.setCurrImg(currImg2);
this.draw(engine.getGraphics());
this.setCurrImg(orig);
this.draw(engine.getGraphics());
try
{
Thread.sleep(100);
}
catch (InterruptedException e) {}
}
}
public void draw(Graphics g) //Called from engine.paint()
{
g.drawImage(getCurrentImg(), getX(),
getY(), engine);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你必须在两张图片之间睡觉。 否则你只会看到最后绘制的图像。
例如。
像这样的东西:
you have to sleep between the 2 images. otherwise you will only see the last image painted.
eg.
something like this:
正如 sfossen 所说,绘制图像之间需要一段延迟。
还有其他一些需要考虑的事情。
示例(伪代码)
As sfossen said, you need a delay between drawing the images.
A couple of other things to consider.
Example (pseudocode)