# AI turret rotation

**URL:** <https://forum.kirupa.com/t/ai-turret-rotation/245591>\
**Category:** programming\
**Created:** [December 1, 2007, 11:27am UTC](https://forum.kirupa.com/t/ai-turret-rotation/245591 "2007-12-01T11:27:03Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![fw2803](https://avatars.discourse-cdn.com/v4/letter/f/e5b9ba/32.png) [@fw2803](https://forum.kirupa.com/u/fw2803)\
**Post date:** [December 1, 2007, 11:27am UTC](https://forum.kirupa.com/t/ai-turret-rotation/245591/1 "2007-12-01T11:27:03Z")

</div>

Hi there  
I encounter a problem when working with an AI problem.

```auto

dx = this._x - _root.stnk.co.x
dy = this._y - _root.stnk.co.y
degrees = Math.round(Math.atan2(dy,dx)*180/Math.PI)+180
distance = Math.sqrt((dx*dx)+(dy*dy))
ro = Math.round(this._rotation+this.turret._rotation)
 
if ((distance <= range) and (_root.stnk._alpha >= 100) and (healthC > 0)) {
  if ((degrees-ro<90 and degrees-ro>-90) or (degrees-ro>270) or (degrees-ro<-270)) {
    this.turret._rotation+= turning
  } else if ((degrees-ro<180) or (degrees-ro>-180)) {
    this.turret._rotation -= turning
  }
 
  if ((ro-degrees-90<=4) and (ro-degrees-90>=-4)) {
    turning = 0
  } else {
    turning = 3
  }
 
}
 

```

By using the above code, my turret is able to turn to the player at a constant speed. When the turret reaches the player, i.e. faces the player, however, it vibrates, or you can say occiliates.

I know the cause of this problem.  
\_rotation - degrees can be smaller than the turning rate of the turret so that the turret moves back again and again in order to achieve \_rotation = degrees, which is impossible. But how to solve the problem?

Any help will be highly appreciated.
