In this post, I add damage and a bit of sound, and provide a playable demo.

### Damage

How do you calculate damage to a ship from a gun shot? An obvious way is to calculate how close the shot came to the ship, and use that. But I want a bit more accuracy. I want to know which part of the ship was hit.

So I am using the ship vertices. After making the ship, I create

• a table of unique vertex positions in the ship mesh
• a table of vertex positions for each gun
• and calculate the minimum & maximum x,y,z positions of all these vertices to create a “box” that contains the ship

If a shot passes into this “box”, I treat it as having exploded, and I calculate the distance d to each of the ship vertices, and add damage simply as max(0,D – d), where D is the maximum damage I want to cause, eg 5. So a single shot can damage several vertices.

This also works for each of the guns.

Then I set a health figure for the ship, and for each of the guns, which means that guns can get knocked out, as well as the ship being sunk. You lose if either your ship sinks or all your guns get knocked out.

What I like about this system is that it allows me (if I choose) to allocate damage to different parts of the ship, so if I mark some vertices as “hull” or “rudder”, then I can specifically damage them.

It did cost me a bit of work. When I made the ship vertices, I didn’t space them evenly, and only put them where I needed them. If I’m using them for damage, I can’t have big gaps between vertices, so I had to add some extra vertices to make them more even.

### HUD Display and User Interface

I want to keep things really simple. Right now, you simply steer with the joystick and touch the screen to shoot. I am still thinking about the best way to let the user aim the guns – right now, all the guns are aimed automatically for you.

I am providing several “view” options at the bottom, as you can see below. The health of both ships is shown at bottom right with green bars (enemy on top), and the state of each gun is shown with a dot (green=ready, yellow=reloading, red=disabled).

### To do

I need to

• prevent gun shots going right through islands
• let the user aim the guns (but probably not control elevation – ie the angle of the barrels – that is too hard)
• give the enemy ship some AI so it can sail and attack, without hitting islands

All of these are hard.

### Playable Demo

Anyway, here is the code I have at the moment. It isn’t as tidy as I’d like, but it works (with an occasional glitch, like getting stuck in an island). It is self contained and doesn’t require any image downloads.

Just put this in a new Codea program and run it

```function setup()
http.request("http://bit.ly/1gh0Qoh",