The problem is that you're starting another instance of the coroutine on every frame. This means that you've got a bunch of updates of the newPos and oldPos variables all the time, which will cause a bunch of problems. You'll want to cut the coroutine entirely, and do this instead:
void Update () {
newPos = transform.position;
Direction ();
oldPos = transform.position;
}
In that way, when you run the Direction method, oldPos will be the value of your position on the last frame, and newPos will be the position on this frame. To make that work, you'll want to make your code framerate independent - which means that you need to replace 0.2 with (0.2 * [Time.deltaTime][1]):
if (oldPos.y < newPos.y && (newPos.y - oldPos.y) > 0.2 * Time.deltaTime) {
direction = 1;
}
Also, if you care, there is a completely unrelated bugs in your code; for Down and Right, you're doing this:
//Down
if (oldPos.y > newPos.y && (newPos.y + oldPos.y) > 0.2) {
direction = 2;
}
If oldPos.y = 50.0000001 and newPos.y = 50, that if will evaluate to true, as newPos.y + oldPos.y = 100.0000001. You want (oldPos.y - newPos.y) instead.
Another issue, if your game has diagonal movement, all diagonal movement will be registered as either right or left. Since you check those after up and down, those will overwrite the direction value. If that's a problem, you're going to have to rethink things.
Finally, I'd recommend replacing integers representing the direction with a proper Enum; see the Unity [tutorial][2] or the official microsoft C# [docs][3]
[1]: http://docs.unity3d.com/ScriptReference/Time-deltaTime.html
[2]: http://unity3d.com/learn/tutorials/modules/beginner/scripting/enumerations
[3]: http://msdn.microsoft.com/en-us/library/sbbt4032.aspx
↧