2013-02-21 21 views
1

我有一只猫在屏幕上运行,并停止在屏幕中间划伤两次。我当前的代码看起来像无论如何缩短,如果其他语句,而不是圈出

private void scratch(){ 
for (int i = xPos; i < getWidth(); i+=0) { 
    xPos = i; 
    // swap images 
    if (currentImage == nekoPics[0]) 
     currentImage = nekoPics[2]; 
    else if (currentImage == nekoPics[2]) 
     currentImage = nekoPics[4]; 
    else if (currentImage == nekoPics[4]) 
     currentImage = nekoPics[5]; 
    else if (currentImage == nekoPics[5]) 
     currentImage = nekoPics[4]; 
    else if (currentImage == nekoPics[4]) 
     currentImage = nekoPics[5]; 
    else 
     currentImage = nekoPics[0] 

有没有做出是否else语句不是让他们在这样一个巨大的圆圈会更简单的方法?

在此先感谢 (PS:我想你可以用某种形式的反做到这一点,但我不是如何去这个这么肯定,任何帮助表示赞赏)

+4

您可以使用'switch-case'。 – 2013-02-21 11:59:50

+1

i + = 0是什么意思? – BobTheBuilder 2013-02-21 12:00:03

+1

第五个'if'因为你在第三个'if'中检查过,所以总是评估为false。 – Navin 2013-02-21 12:02:12

回答

2

您可以保留当前图像的索引,并且增加它在每次迭代中,例如:

currentImage = nekoPics[currentIndex%6]; 
currentIndex++; 

currentImage = nekoPics[currentIndex]; 
if (++currentIndex==6) currentIndex=0; 

这要求在nekoPics图像进行排序艾科rding到动画的顺序。

+0

做到了这一点,工作没问题,这是一种方法,我如何得到这个喜欢停止运行,让其他方法开始运行,所以猫会在划痕后再次运行到屏幕的末端?基本上它开始与公共无效moveIn运行,然后得到从零开始,然后我有一个moveOut方法也使它运行到最后,但我无法得到它开始后,其完成经历了划痕 – Sim 2013-02-21 12:19:53

0

它可能是更容易,如果你在你的屏幕前获得停止猫的代码......

严重的是,虽然,你可以通过使定义你的照片序列中的对象解决这个问题。

1

除了在其他地方建议的地图,您可以只使用一个数组;你需要保留当前图像的索引的轨迹:

int[5] nextImageList 
    = { 2, ?, 4, 5, 4 } 

next = nextImageList[currentImageIndex]; 
currentImage = nekoPics[next]; 
currentImageIndex = next; 

没有“如果”你需要初始化currentImage和currentImageIndex后。我不确定1是否是一个有效的索引,如果不是的话,任何事情都可以在阵列中的1个插槽中进行。

+0

可能是最简单的答案初学者。我建议编辑,因为阵列由(至少)6个插槽组成,而不是5.第三个插槽也是未知的。 – afsantos 2013-02-21 12:29:59

0

我打算用一个数组发布类似于rcook的答案。我认为它是理解最简单的解决方案。

但是,他的回答在数组维度上有一个小小的错误。我发布这个完整性,但信用应该指向他。

// Elsewhere, in your initialization: 
int currentImageIndex = 0; // Assuming [0] is your first image. 
int[] nextImageList = { 2, -1, 4, -1, 5, 4 }; 
// Given the current index, this array will direct you 
// to the next image index. Those -1 are unknown (to us). 
// Set them to the values you need. 

private void scratch() { 
    for (int i = xPos; i < getWidth();) { 
     xPos = i; 

     // Swap images. 
     currentImageIndex = nextImageList[currentImageIndex]; 
     currentImage = nekoPics[currentImageIndex]; 

     // What else you were doing here. 
    } 
} 
+0

感谢真的帮助这一项工作,欢呼的人 – Sim 2013-02-22 13:30:29