我在为我的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循环迭代速度太快,以至于在usedTimeRight = timer
> 0之前就退出了while循环。这意味着你的第一个和第二个if语句将为假,因为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; }