Move ship based on angle AS3

Imagine you are writing a game and you have a space ship that needs to move towards a target in a smooth fasion. It needs to turn towards the target, all the while moving forwards. The following is a function/method in a class used to control the movement of the ships in the game. The ships all have home worlds that the ships will head for.

public function ShipControler(e:Event):void {  

   var ss = e.target; // Set ss to the event target. ss is nicer to use than e.target
   
   // Get target x,y of target
   var tx:Number = world[ss.targ].x; // ss.targ is a number. It is the ID of the world the ship is heading for
   var ty:Number = world[ss.targ].y; // ss.targ needs to be defined in the ship's own object
   
   var dist_x:Number = tx - ss.x; // Distance to target on X axis
   var dist_y:Number = ty - ss.y; // Distance to target on Y axis
   var angle:Number = Math.atan2(dist_y, dist_x); // The angle of target relative to ship in radians
   var ta:Number = angle/Math.PI*180; // The angle of target relative to ship in degrees
   var range:Number = Math.sqrt(Math.pow(dist_x,2) + Math.pow(dist_y,2)); // Distance to target
   
   // Calculate closest angle to turn ship
   // There might well be a cleverer way to do this, but my brain started melting so I did this.
   // It works out if the ship needs to turn left or right depending on which every way has the
   // smallest angle. Imagine moving the ship to face angle 0 (facing right) then moving
   // the target so that it still has the same relative position. If the target's angle is
   // less that 0 the ship needs to turn left. If the target's angle is more than 0 the
   // ship needs to turn right.
   
   if (ss.rotation < 0){
    ta = ta + ss.rotation * -1;
    if(ta > 180){ta = ta - 360;}
   }else{
    ta = ta - ss.rotation;
    if(ta < -180){ta = ta + 360;}
   }
   var rot:Number = new Number; // How fast and which direction the ship turns
   if(ta > 0 ){
    rot = 5;
   }else{
    rot = -5;
   }
   if(range < 30){rot = rot * -1;} // Turn ship away if too close to target
   ss.rotation += rot; // Turn the ship
   
   // Move ship forward based on ship's angle
   var ssangle:Number = ss.rotation * Math.PI / 180; // Ship's angle in radians
   var speed:Number = 2; // Set the speed of the ship
   ss.x = ss.x + speed*Math.cos(ssangle); // Move the ship on the X axis
   ss.y = ss.y + speed*Math.sin(ssangle); // Move the ship on the y axis
  }

Leave a Reply