I am using a CharacterController on AI controlled mobs in my game. The AI follows a simple waypoint system I made by targeting a waypoint and turning towards it and running forward using
Here is a snippet of my code that moves the AI:
This works fine, unless there is a lagspike, which causes all of the AI controlled characters in the game to wildly fly off screen. This can be reproduced 100% of the time by playtesting inside the unity editor, then holding left click on the top window bar of the unity editor (as if you were dragging the editor window around your screen, which causes the game to freeze) then letting go.
My game is being run through the web player, and it also happens there whenever any sort of FPS drop occurs from outside lag sources (such as having the game open in the browser, then clicking the play button inside unity to playtest there at the same time).
I tried to workaround this by resetting the position of the characters to their last visited waypoint if they don't reach their destination within 10 seconds, however their velocity from being thrown around stays with them and they continue to fly around after resetting position.
Is there something I'm doing wrong in my movement script? Is there a way to fix this?
Change Time.deltaTime to Time.smoothDeltaTime. smoothDeltaTime is smoothed over multiple frames.
Time.deltaTime does make your game framerate independent, but not time independent. Time.deltaTime is nothing else then the time it took for the last frame to render. So at 60 fps it would be 1/60 = 0.016. At 10 fps the value would be 0.1. This value you then multiply with your normal movement, which makes it basically movement per second.
What happens, is that the deltaTime becomes a huge number because of the spike, which causes huge movement. For example, a 3 second spike causes a deltatTime of 3 seconds. Which means you move your character 3 seconds worth of time. Which is not what you want most of the time.
Another solution would be to have a max for your deltaTime with Mathf.Min(deltaTime, maxDeltaTime).