I have this code to turn to face a target and move towards them:
var x : Number = _targetPosition.value.x - _position.value.x;
var y : Number = _targetPosition.value.y - _position.value.y;
var targetAngle : Number = Math.atan2(y, x);
_angle.value = targetAngle;
_velocity.value.setXY(Math.cos(targetAngle) * 90, Math.sin(targetAngle) * 90);
How would I instead turn say a couple degrees (or quarter radians or whatever you want to use, I can convert either way) a frame instead? The target might be moving so I can’t use a formula that takes time into consideration… it should simply turn X degrees a frame instead of snapping instantly.
Also if you could show me how to apply that rotation taking into consideration a deltaTime that’d be great too but I can try to figure that out.
Thanks!
Unless you’re forcing your program to run at a fixed time step, any algorithm that fails to take the passage of time into account is going to be potentially incorrect. Depending on the hardware, framerate can vary wildly; a solution that works on your computer at 80 FPS isn’t going to have the same effect on Joe Superuser’s $5000 Alienware running the game at 200 FPS.
You need to calculate the difference between the object’s current angle and its target angle, then increment its angle by some amount based on the difference between those two, multiplied by the time elapsed since the previous frame.
Consider the following (off the top of my head, untested) code:
Whether or not the target is moving is ultimately irrelevant. The question you’re asking with this code is, “Where is the target right now and what do I have to do to face it?” If the target’s position changes in a subsequent frame, then the direction you need to move will also change, and the object will begin rotating in the opposite direction, as I assume you intend.