英文:
Basic Animation With Arrow Keys
问题
PImage[] p = new PImage[16];
int frameCounter = 0;
int current;
int walkTo = 15;
int walkFrom;
void setup(){
frameRate(60);
size(200,200);
imageMode(CENTER);
ashWalk();
}
void draw() {
background(255);
image(p[current], width/2, height/2);
if(frameCounter % 8 == 0) {
if (current > walkTo-1)current = walkFrom;
current++;
}
frameCounter++;
}
void ashWalk(){
for(int i = 0; i < walkTo+1; i++){
p[i] = loadImage("Pokemon"+i+".png");
}
}
void keyPressed() {
ashWalk();
if (key == CODED) {
if (keyCode == DOWN){
walkFrom = 0;
walkTo = 3;
}
else if(keyCode == LEFT){
walkFrom = 4; //what I would possibly want is to start looping in this number
walkTo = 7;
}
else if(keyCode == RIGHT){
walkFrom = 8;
walkTo = 11;
}
else if(keyCode == UP){
walkFrom = 12;
walkTo = 15;
}
}
}
英文:
My goal is to cycle the character from:
0-3 when DOWN key is pressed |
4-7 when LEFT key is pressed |
8-11 when RIGHT key is pressed |
12-15 when UP key is pressed |
My program is responding with the arrow key now especially with "DOWN key" but it starts looping from [0] every time it finishes the entire loop. What could I possibly do to fix this?
PImage[] p = new PImage[16];
int frameCounter = 0;
int current;
int walkTo = 15;
int walkFrom;
void setup(){
frameRate(60);
size(200,200);
imageMode(CENTER);
ashWalk();
}
void draw() {
background(255);
image(p[current], width/2, height/2);
if(frameCounter % 8 == 0) {
if (current > walkTo-1)current = walkFrom;
current++;
}
frameCounter++;
}
void ashWalk(){
for(int i = 0; i < walkTo+1; i++){
p[i] = loadImage("Pokemon"+i+".png");
}
}
void keyPressed() {
ashWalk();
if (key == CODED) {
if (keyCode == DOWN){
walkFrom = 0;
walkTo = 3;
}
else if(keyCode == LEFT){
walkFrom = 4; //what I would possibly want is to start looping in this number
walkTo = 7;
}
else if(keyCode == RIGHT){
walkFrom = 8;
walkTo = 11;
}
else if(keyCode == UP){
walkFrom = 12;
walkTo = 15;
}
}
}
答案1
得分: 2
在我的理解中,ashWalk
负责初始化图像数组[0-15]。所以我不认为在 keyPressed
中每次都需要调用它。
在 draw
中,您需要验证当前是否仍然在范围[walkFrom-walkTo]内。
如果不在范围内(这可能是在按键时更新walkFrom-walkTo时的情况),则您需要使用walkFrom重置current:
if (current >= walkTo || current < walkFrom)
current = walkFrom;
else
current++;
如果您在绘制当前图像之前计算这个条件,current始终会保持在正确的范围内。
英文:
In my understanding ashWalk
is responsible for initialising the image array[0-15].
So I don't see a need to call it each time in keyPressed
.
In draw
you have to verify if current is still in the range of [walkFrom-walkTo].
If not (this can be the case when walkFrom-walkTo is updated by a keypress) you have to reset current with walkFrom:
if (current >= walkTo || current < walkFrom)
current = walkFrom;
else
current++;
if you calculate this before you draw the current image, current is always within the correct range.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论