我有一只猫跑过屏幕,并在屏幕中间两次停止划伤。我当前的代码看起来像
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:我认为你可以用某种类型的计数器做到这一点,但我不太确定如何解决这个问题,任何帮助都表示赞赏)
答案 0 :(得分:2)
您可以保留当前图像的索引,并在每次迭代时递增它,例如:
currentImage = nekoPics[currentIndex%6];
currentIndex++;
或
currentImage = nekoPics[currentIndex];
if (++currentIndex==6) currentIndex=0;
这需要根据动画的顺序对nekoPics中的图像进行排序。
答案 1 :(得分:1)
除了在其他地方建议的Map之外,你可以使用一个数组;你需要跟踪当前图像的索引:
int[5] nextImageList
= { 2, ?, 4, 5, 4 }
next = nextImageList[currentImageIndex];
currentImage = nekoPics[next];
currentImageIndex = next;
初始化currentImage和currentImageIndex后不需要'if'。我不确定1是否是任何地方的有效索引,如果没有,任何东西都可以进入数组的1个插槽。
答案 2 :(得分:0)
如果你阻止那只猫走到你的屏幕前,它可能会更容易编码......
但是,说真的,你可以通过制作一个定义你的图片序列的对象来解决这个问题。
答案 3 :(得分: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.
}
}