Ways to make a good tower defense tower

I have been developing a simple tower defense game in plain java for the past month. I want to make my game a little better so I am adding a cannon, which needs to be able to rotate according to the enemy’s position on the screen. Thats my big problem… I have made 8 images of the tower in different positions and I am not sure whether or not I can actually use Java to rotate a single image, or do I have to have a sprite sheet of the tower in different directions? Also, how do I detect which way for it to face? I was thinking about comparing the slope of the x and y coordinates of the enemy and the tower, but I wasnt sure if that was efficient, so I came here. Help is appreciated
cMp

Yes, you can use java to rotate the image.

Use Google.

Yeah, for this one you’re going to have to use trigonometry. More specifically, the atan2 function.

So, what you need to do is get the closest enemy, and calculate the angle to it. To do this, do:


double angle = Math.atan2(target.x - this.x, target.y, - this.y);

That will be in radians, of course, so put a Math.toDegrees(x) around that for degrees.

Now, it’ll be easier to do in degrees, so you should convert to that. We have to divide 360 into 8 parts, which is 45. So what you’re going to do is something like this


if(angle >= 0 && angle < 45) {
    sprite is this
} else if(angle >= 45 && angle < 90) {
    sprite is that
}

But then again, it all matters on perspective, this way would be useful in basically all possible perspectives, but your game has a bird-eye view, it would be easier to rotate the image.

yes, it has a birds eye view, so I am guessing that I would use the same concept but for rotation?

You can use graphics.rotate() or glRotatef() (depending on your rendering) to rotate the image.

He said “plain java” which I assume means Java2D…in that case better to use AffineTransform, then you can rotate individual images as opposed to the entire graphics object

I will research both of the methods. Thank you very much for all of your help!

Bingo. Exactly what I was searching for. Agro, I swear you are a super human genius your awesome!

Nah, its just that just 2 days ago, we learned what sin, cos, and tan were, so I got a much better understanding of it than I had before. I also worked on an isometric tower defense game before this and I had your same problems, and I just give you the solutions I got, but a bit different since I had isometric.