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]

有没有比让它们像这样大圈子更简单的方法来制作 if else 语句?

在此先感谢(PS:我假设您可以使用某种计数器来执行此操作,但我不太确定如何进行此操作,感谢您的帮助)

4

4 回答 4

2

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

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

或者

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

这就要求 nekoPics 中的图像按照动画的顺序进行排序。

于 2013-02-21T12:00:02.357 回答
1

除了其他地方建议的地图之外,您可以只使用一个数组;您需要跟踪当前图像的索引:

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

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

初始化 currentImage 和 currentImageIndex 后不需要“if”。我不确定 1 是否是任何地方的有效索引,如果不是,任何东西都可以进入数组的 1 插槽。

于 2013-02-21T12:10:23.567 回答
0

如果你阻止那只猫出现在你的屏幕前,编码可能会更容易......

不过说真的,您可以通过制作一个定义图片序列的对象来解决这个问题。

于 2013-02-21T12:00:12.093 回答
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.
    }
}
于 2013-02-21T15:21:46.750 回答