You can get the GML script here. This post will explain the code.
When I was developing enemies in Yxi, I was trying to get turrets to aim at you, but I didn’t want them to possess “instant aim”. I wanted them to rotate towards you given a maximum rotation speed. If you move too fast, it should turn towards you gradually, not instantly.
It seems that it wasn’t as simple as I thought it was. I had the basic algorithm down, but because of the way Game Maker handled angles, the turrets would behave strangely when you would hover around the 0°/360° point with respect to the turret.
I figured a tutorial would be necessary for something that isn’t so obvious to implement. This only pertains to Game Maker and thus uses the GML language.
There are three steps involved when gradually rotating an object (let’s call it a turret for now) towards a target object:
- Calculate the target’s direction with respect to the turret’s position.
- Calculate the angle difference between the direction derived from step 1 (let’s call “target direction”) and the turret’s facing direction.
- Apply angular rotation towards the target so that the target direction is the facing direction.