我正在为我的 XNA 项目创建一个简单的 AI。
我的敌人应该在短时间后从右移到左。
不幸的是,我的代码跳过了我的第一次和第二次 Do-While,所以我的敌人没有移动:< 5 秒长。所以他只是从 +-1.X 位置跳
while (i <= 1)
{
EnemyVelocity.X += 1f;
timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
usedTimeRight = timer;
i++;
}
if (usedTimeRight != 0)
{
do
{ EnemyVelocity.X -= 1f;
timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
} while ((timer - usedTimeRight) >= 5);
usedTimeLeft = timer;
usedTimeRight = 0;
}
if (usedTimeLeft != 0)
{
do
{ EnemyVelocity.X += 1f;
timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
}
while (timer - usedTimeLeft >= 5);
usedTimeRight = timer;
usedTimeLeft= 0;
}
更新了...~~~~~~~~~~~
那么,现在另一个问题 - 我的敌人一直在向左移动
timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
while (i <= 1)
{
EnemyVelocity.X -= 1f;
timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
usedTimeRight = timer;
i++;
}
if (usedTimeRight != 0 && (timer - usedTimeRight <= 2))
{
int x;
for (x = 0; x <= 3; x++)
{
EnemyVelocity.X = 1;
}
usedTimeLeft = timer;
usedTimeRight = 0;
}
if (usedTimeLeft != 0 && (timer - usedTimeLeft <= 2))
{
int x;
for (x = 0; x <= 3; x++)
{
EnemyVelocity.X = - 1;
}
usedTimeRight = timer;
usedTimeLeft = 0;
}
最佳答案
问题在于初始的 while 循环迭代速度如此之快以致于 while 循环在 usedTimeRight = timer
> 0 之前退出。这意味着您的 fist 和 second if 语句将为 false因为 useTimeLeft
和 useTimeRight
将始终为 0。尝试更改它,以便 Timer
变量在声明时等于 1。
例如:
float timer = 1f;
while (i <= 1 )
{
EnemyVelocity.X += 1f;
timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
usedTimeRight = timer;
i++;
}
if (usedTimeRight != 0)
{
do
{ EnemyVelocity.X -= 1f;
timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
} while ((timer - usedTimeRight) >= 5);
usedTimeLeft = timer;
usedTimeRight = 0;
}
if (usedTimeLeft != 0)
{
do
{ EnemyVelocity.X += 1f;
timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
}
while (timer - usedTimeLeft >= 5);
usedTimeRight = timer;
usedTimeLeft= 0;
}
关于c# - XNA,Do-While 基本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38029783/