程序检测左右箭头键。如果按下这些键中的任何一个,我的 Knight 对象(GImage 类的实例)将遍历一个字符串数组(这些字符串是我的 Knight 对象动画的目录路径。
我的代码的问题在于,我似乎无法用我想出的java代码找到合适的流畅动画。当我按下箭头键时,动画快速循环,然后减慢速度,但是当我抬起箭头键并再次按下时,它的动画仍然快速循环,然后变慢。
每个运动动画有 4 帧动画。
这是对我正在使用的库的引用http://jtf.acm.org/javadoc/student/acm/graphics/GObject.html#pause%28double%29
任何提示都值得赞赏。
import java.awt.event.KeyEvent;
import acm.graphics.GImage;
import acm.program.GraphicsProgram;
public class Castlevania extends GraphicsProgram {
public void init(){
setGameBackground();
knight = new Knight("knight anim/knightFaceLeft/knight1.png", 500, 500);
add(knight);
setSize(APPLICATION_WIDTH, APPLICATION_HEIGHT);
addKeyListeners();
}
private void setGameBackground() {
// TODO Auto-generated method stub
gameBackgroundImage = new GImage("link sprites/zelda_background.png");
add(gameBackgroundImage);
}
public void keyPressed(KeyEvent e){
/* Knight's Movement
*
*/
int knightMovementKey = e.getKeyCode();
if(knightMovementKey == KeyEvent.VK_LEFT)
{
this.xSpeed = 10;
ySpeed = 0;
knight.setImage(KnightFaceLeft[knightFrame]);
knight.move(-xSpeed, ySpeed);
knightFrame ++;
if(knightFrame >= KnightFaceLeft.length)
{
knightFrame = 0;
}
}
else if(knightMovementKey == KeyEvent.VK_RIGHT){
knight.setImage(KnightFaceRight[knightFrame]);
knight.move(xSpeed,ySpeed);
knightFrame++;
this.xSpeed = 10;
ySpeed = 0;
if(knightFrame>=KnightFaceRight.length){
knightFrame = 0;
}
}
knight.pause(DELAY);
}
private String[] KnightFaceLeft = {"knight anim/knightFaceLeft/knight1.png","knight anim/knightFaceLeft/knight2.png","knight anim/knightFaceLeft/knight3.png","knight anim/knightFaceLeft/knight4.png"}; //Add in as many images as you want for your animation
private String[] KnightFaceRight = {"knight anim/knightFaceRight/knight1.png","knight anim/knightFaceRight/knight2.png","knight anim/knightFaceRight/knight3.png","knight anim/knightFaceRight/knight4.png"};
private GImage gameBackgroundImage;
private Knight knight;
private final int APPLICATION_WIDTH = 1200;
private final int APPLICATION_HEIGHT = 800;
private int knightFrame = 0;
private int xSpeed ; //the number of pixels to move in x
private int ySpeed = 0; //0 so you only move horiontally
private double DELAY = 35;
}
import acm.graphics.GImage.*;
public class Knight extends GImage {
public Knight(String imageDirectory, double knight_Location_XCoord, double knight_Location_YCoord) {
super(imageDirectory,knight_Location_XCoord, knight_Location_YCoord);
}
}
您对 pause()
的调用正在阻止事件调度线程。在此上下文中,请使用 acm.util.SwingTimer
在计时器的ActionListener
中调整动画的节奏。