How to make turret pointing at an object using 2d frames in tower defense games?

99 Views Asked by At

I'm working on tower defense game and I'm using stencyl.

I want to make 2d tower defense game like (clash of clans), so I want to know how to make a turret pointing at an object using frames like (canon in clash of clans).

I mean when an object enters the range of tower the tower will point at it without rotating the tower but using 2d frames instead by some way using code or mathematical way.

1

There are 1 best solutions below

0
On BEST ANSWER

I've found the solution. Do this :

float Direction = 0;
float FinalDirection = 0;
float DirectionDegree = 0;
int NumberOfDirections = 0; // eg: 24 or 32 or even 128 or anything Directions

DirectionDegree = 360 / NumberOfDirections;

void update() // this will run every frame
{
    Direction = Math.atan2(target.y - tower.y, target.x - tower.x ) * (180 / Math.PI);

    if(Direction < 0)
    {
        Direction += 360;
    }

    FinalDirection = Direction / DirectionDegree;
    tower.frame = FinalDirection;
}