我正在为我的XNA项目创建一个简单的AI。
我的敌人应该在短时间内从右向左移动。
不幸的是,我的代码跳过了第一次和第二次,所以我的敌人不会移动:< 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;
}发布于 2016-06-25 15:14:13
问题在于,初始while循环的迭代速度非常快,以至于with循环在usedTimeRight = timer > 0之前就退出了。这意味着您的第一个和第二个如果状态将是假的,因为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;
}发布于 2016-06-27 12:09:42
我会高度推荐初学者,只有在你真正需要的时候才使用when循环,因为它可以阻止你的游戏,或者给你意想不到的结果(通常是这个问题中的东西),因为最初很难理解游戏的内部逻辑是如何工作的。
如果你需要你的敌人做5秒的事情,当它开始你想要的动作时,只需保存一个变量gameTime.ElapsedGameTime.totalMilliseconds,然后签入一个如果你的savedGameTime小于游戏总时间-减去你想要的时间。
如果正确的话,你想让你的敌人向左移动5秒钟,然后向右移动5秒钟?要做到这一点,您必须这样做:
float delayBetweenMoves = 5f;
float lastMoveTime = 0f;
bool isMovingLeft;
public void Update(GameTime gameTime)
{
Move(gameTime);
enemy.Position += (enemy.VelocityX * enemy.Speed);
}
private void Move(GameTime gameTime)
{
if(lastMoveTime < gameTime.TotalGameTime.TotalMiliseconds - TimeSpan.FromSeconds(delayBetweenMoves))
{
lastMoveTime = gameTime.TotalGameTime.TotalMiliseconds;
if (isMovingLeft)
{
enemy.VelocityX = -1;
isMovingLeft = false;
}
else
{
enemy.VelocityX = +1;
}
}
}https://stackoverflow.com/questions/38029783
复制相似问题