[英]Adding tail to snake game [c++ sfml]
I want to move the snake's tail by filling the gap it creates each time the head moves:我想通过填充每次头部移动时产生的间隙来移动蛇的尾巴:
. . o oox ØOOX
.ooo x .ooo x
. . oo o x OO○×
So basically the last element moves into the gap.所以基本上最后一个元素移动到间隙中。 I can get the position of gap and create a tail there but as soon as I have more than 1 tail object it doesn't work correct.我可以得到间隙的位置并在那里创建一条尾巴,但是一旦我有超过 1 个尾巴对象,它就无法正常工作。 I believe it creates the new tail object on the same position as other tails, so the gap.我相信它会在与其他尾巴相同的位置创建新的尾巴对象,所以间隙。 Tail = rep尾巴 = 代表
For tail尾巴用
//If tail exists
if(imamoRep)
{
rep[repCount-1].setPosition(gap);
temp[0] = rep[repCount-1]; //Remember last element
for(int i=1;i<repCount;i++)
{
rep[i] = rep[i-1];
}
rep[0]=temp[0]; //assign last element to first
}
Drawing画画
for(int i=0; i<repCount; i++)
{
window.draw(rep[i]);
}
I'm guessing I did something wrong with arrays, the last element should become first and all others should move to left, so there's a new last tail.我猜我对数组做错了,最后一个元素应该成为第一个元素,所有其他元素都应该向左移动,所以有一个新的最后一个尾巴。 I created 100 tail elements in the beggining so I only need to draw them correctly.我在开始时创建了 100 个尾部元素,所以我只需要正确绘制它们。 If I remove the tail code except the first line that sets position then I get this result:如果我删除除设置位置的第一行之外的尾部代码,则会得到以下结果:
Tails are left behind, because only the position of last element changes, otherwise as said before all tails are on the same position.尾巴被留下了,因为只有最后一个元素的位置发生了变化,否则所有的尾巴都在同一个位置上。 I would really appriciate help.我真的很感激帮助。
You almost had it.你几乎拥有它。 Think of what this loop is doing to your positions:想想这个循环对你的位置做了什么:
for(int i = 1; i < repCount; ++i)
{
rep[i] = rep[i - 1];
}
Starting at i=1
it'll assign rep[1]
the value of rep[0]
.从i=1
开始,它将为rep[1]
分配rep[0]
的值。 Next for i=2
it'll assign rep[2]
the value of rep[1]
which was overwritten with rep[0]
on the previous iteration.接着为i=2
,它会分配rep[2]
所述的值rep[1]
将其用覆盖rep[0]
的前一迭代。 And so on...等等...
What you need to do is invert the loop writing the element at i+1
before writing the element at i
:你需要做的是逆变回路写在元素i+1
在写元素之前i
:
for(int i = repCount - 1; i > 0; --i)
{
rep[i] = rep[i - 1];
}
Note that std::copy_backward generically implements this behaviour.请注意std::copy_backward一般实现此行为。 Ie you can rewrite the loop above as:即您可以将上面的循环重写为:
if(repCount > 0)
{
// Assuming rep is a std::vector using std::vector::begin
std::copy_backward(rep.begin(), rep.begin() + repCount - 1, rep.begin() + repCount);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.