Xmas game part 1

I like to do something special for Christmas. Most years I make my own custom Christmas cards. 5 years ago I produced a small game to celebrate and I want to try producing a Christmas themed game again.

Step one is to come up with a concept. I’ve spent a while thinking about this, the game needs to fulfil a few criteria:

  • It needs to be simple enough that I can implement it in a few days
  • The animation needs to be really simple (I have no real animation skills)
  • The game needs to be accessible, suitable for all ages and abilities to play
  • It needs to be fun
  • It needs to have some link to the festive season

After studying a few different types of games and thinking very hard about how I can produce a game I came up with the following idea. A platformer which involves a polar bear jumping between platforms. The game ends when the bear ends up in the water. Points are scored for each jump successfully completed between platforms. The game starts off easy with small gaps and large flat platforms. As the game progresses the gaps get larger, the platforms become smaller, inclined and slippery. The image at the top of the post is my first drawing of the concept.

The next step splits the game into two parts: the game mechanics and the styling. The game mechanics includes all the physics, rules and controls of the game whilst the style includes all the animation of the objects and all the different images and textures needed. Once these two parts are completed we can integrate them and test out the game.

I’m going to start with the game mechanics. There are two objects in this game: the polar bear and the platforms. The platforms will scroll horizontally to give the apparent forward (or backward) motion of the bear whilst the bear will move vertically to give its vertical motion.

There will be 3 inputs to the game, one input will make the bear run faster (accelerate), one will make the bear run slower (decelerate) and one will make the bear jump. The longer the jump control is held down the more powerful the jump. The jump is commenced as soon as the jump control is released.

I can now start putting together the equations to model the behaviour of the bear object. The bear has 4 parameters: horizontal and vertical displacement sx and sy and horizontal and vertical velocity vx and vy. At regular intervals (say 50 times per second) the forces on the bear are calculated and this affects the velocity parameters. The velocity parameters are then used to update the displacement parameters. Once the new displacement parameters are known, collisions can be detected. I’ll come back to collisions.

First lets look at the forces on the bear. When in the air there are two forces affecting the bear: gravity and air resistance. Gravity always acts only on the vertical component and has a constant effect of magnitude g (gravitational acceleration). Air resistance acts proportionally to the velocity of the bear in the direction opposite of the velocity. We can easily split this into a vertical and a horizontal component.

This gives us our two equations:

vxn+1 = a * vxn

vyn+1 = b * (vyn – g)

where a is the horizontal aerodynamic parameter, b is the vertical aerodynamic parameter and g is the gravitational parameter. (a and b can be the same or can be different to give slightly more adjustable physics)

When on a platform there is a further force from the player controlled acceleration/deceleration. We also need to consider the effects of slippery surfaces. The amount of friction between the bear and the surface limits the force in the direction of the surface of the platform.

We can model this as a velocity in the direction of the surface of the platform.

vsn+1 = c * (vsn – g * sin(θ) + d * cos(θ) + e)

where c is platform aerodynamic parameter and d is the friction parameter and e is the player controlled acceleration parameter.

Finally we have a force from jumping, since a jump is instantaneous we simply add an amount of velocity depending on how long the jump control has been pressed for. The jump is always normal to the surface of the platform.

It’s very difficult to give exact numbers for each of the parameters. The parameters give the game it’s feel. We can give more or less gravity, make the bear faster or slower, make the bear more or less responsive and the platforms more slippery. To get a feel for where the game feels right requires some testing.

Finally we have collision detection. If we are currently on the platform we are testing for whether the bear has gone off the edge of the platform. If we are in the air we are testing for if the bear has hit anything. We test if the bottom edge of the bear bounding box has hit the water or the top of a platform and we test if the right hand edge of the bounding box has hit the side of a platform. Only in the case where the bear hits the top of the platform does the game continue. The velocity of the bear in the direction of the surface of the platform is set as the new velocity with the normal component discarded.

This translates to quite a number of rules and equations but put them all together and you get this demo. The platforms are the red objects, the bear is the yellow object. The arrow keys control the acceleration/deceleration and the space bar makes the bear jump. It’s not the finished article by any means but it gives a framework to start from.

Next time I’ll be looking at producing the graphics for the game especially the animation of the bear.

Remembrance and thanks

Today, I went to a memorial service at the magnificent Lancing College chapel ( the right hand building in the photo at the top of this post). It was mostly a service to remember those who died in the Shoreham airshow crash and to recognise the efforts of the emergency services.

It was a bitterly cold day, getting to Lancing I walked over the Old Shoreham bridge. This bridge, once covered in flowers, was now covered in brightly coloured ribbons. To me it was rather chilling to see hundreds of ribbons waving in the breeze. It did remind me of loss. The personal tributes, flowers, mementos and messages had all disappeared, everything was stripped back to these plain unattributable ribbons. It reminded me of the simple grave markers and the bright poppies we use to commemorate those who’ve died in war.

The mood of the service itself was sombre interjected with brief bursts of positivity. Silence was the most powerful aspect of it. A minute silence was held at 1:22pm to mark 3 months since the accident. It was the quietest minute of silence I’ve ever experienced amongst so many people, there were no coughs, no crying children, no rustling of paper, nothing. The thick walls of the chapel and the huge space made the silence feel particularly ominous. It was like being the only person in the building.

There were many more moments of silence only filled by the deep and powerful sounds of the organ. It was clear that everyone was lost in their own thoughts and memories. There was a definite sense of sadness and loss.

For me it was a slightly surreal experience. I didn’t know anything much about the victims being remembered. The service wasn’t a personal one, there were readings by some of the families and friends but there was no indication of who they were or why they had chosen their readings. They probably had a lot of meaning for those who knew the person they were remembering but I struggled to relate.

For me the event was an opportunity to say thank you. After the service I was able to speak to members of the Red Cross who had been at the event. It was nice to see a few familiar faces, people who had helped me that day. I was able to show them that I had recovered thanks in part to their efforts. They joked that it was nice to see me wearing clothes as opposed to being wrapped in a foil blanket!

I also had a chance to speak to members of the ambulance service and police force to thank them for their efforts. For the emergency services, they were just doing their job but I think it’s very important to show gratitude and show them how much their job really means to real people.

A letter to Andy Hill

I’ve been invited to the Shoreham Airshow Memorial Service tomorrow. I don’t think the pilot in that incident, Andy Hill, will be there but I’ve been thinking about what I’d say to him if he were.

In many ways Andy Hill is much luckier than me. Nobody thought any pilot would be able to survive such a horrific crash. I was quite surprised when I heard the news that the pilot had been taken to hospital. I was even more surprised when it was announced that he had been discharged from hospital only a week after I had been discharged.

Planes aren’t really designed to crash into the ground but somehow the impact had so little vertical velocity that it didn’t kill him. And somehow his seat managed to come detached from the main cockpit structure such that he wasn’t badly burnt in the ensuing fire.

I’m sure that he was hugely helped by some excellent emergency responders and the air ambulance which transported him to hospital. As it turned out I believe he was the only person who suffered life threatening injuries.

I don’t think I’ll ever know the full reason why the Hawker Hunter hit the ground in front of me. I’m not an investigator however I know a little about aeroplanes, I’ve watched the videos of the crash many times and I’ve read the preliminary report compiled by the Air Accidents Investigation Branch (AAIB). The report comes to no conclusions about the cause of the accident. The only tiny piece of new information it offers is that there were cameras in the cockpit recording the flight and they seemed to show that the aircraft responded to the pilots inputs.

It’s not my job to investigate the accident nor should I really speculate on the cause as I’m not an expert however my best guess is that the incident was at least partly due to pilot error.

When performing an aerobatic manoeuvre such as that fateful one, the pilot has to make a decision at the highest point of elevation. If the pilot hasn’t achieved the necessary elevation, or there is some sort of malfunction then the pilot simply pulls the plane out of the turn, rolls the plane upright and starts again. Since the pilot didn’t do this, we have to assume 3 options: he was at the necessary elevation with no malfunctions, his elevation was too low but he didn’t realise or a malfunction prevented him from pulling out of the manoeuvre.

The first two options are the only plausible ones given the report which stated the plane was responding to inputs and the fact that in the videos, the pilot still appears to have some measure of control.

If we assume everything was fine at the top of the manoeuvre, then we have to ask what happened between that point and hitting the ground. Loss of power isn’t an issue as the plane is descending and there should be enough elevation to get back to level flight even without power. Loss of control is another option. In the videos I’ve seen it seems like the plane reduces the rate of pitch before it achieves level flight. Again there can be multiple explanations for this: the pilot might have momentarily lost control for some reason (passing out, losing sight, becoming distracted), a control actuator may have broken or the plane may have stalled, this is when the plane is pushed beyond it’s limit and the wings instead of generating more lift generate less lift.

I think we can probably discard a control actuator malfunction or a stall as this would appear at odds with the AAIB statement. In summary we’re left with two plausible options (or a combination of both). The pilot made a mistake about the elevation required to complete the manoeuvre safely or the pilot momentarily lost control of the aircraft.

Even though I think pilot error was probably partly to blame for causing the incident, that does not mean I blame Andy Hill. Most of us make small mistakes every day; I know I make lots of small mistakes at work. On 4 or 5 occasions in my life, I’ve temporarily lost my sight. It doesn’t go instantaneously, the times it’s happened I’ve been able to sit down and wait a minute or so for my sight to come back. I’ve never been to a doctor about this, I don’t think it’s serious enough. But if it happened again at the wrong time, I could be driving a car on the motorway, it could cause someone other than me to get injured.

I’m not sure whether I’m doing the right thing about that, but I don’t want some minor condition affecting what I can and can’t do. I take risks and that day at the airshow, I took a risk, I sat somewhere where planes were flying over my head.

So here’s my letter to Andy Hill:

Dear Andy,

Firstly, I want to say I’m not blaming you for what happened to me that day at the Shoreham airshow. I hope you’re recovering well and you can get to a day in your life when you don’t think about the accident.

You probably know better than anyone what happened just before you hit the ground. I’m interested in what happened simply to satisfy my own curiosity.

I don’t mind if I never get to know but I think it’s right that the investigators know so they can prevent future injuries.

You inadvertently gave me the most thrilling memory of any jet plane. If your Hunter hadn’t hit the ground I’d have probably got an incredible close up photo and a huge rush as it came over my head. Sadly that wasn’t what happened and I wish I could roll back time to prevent it.

Finally, I hope that if you want to, you’ll be able to fly planes again. If you’re ever back in a Hunter again, I’d love to try and get some decent photos!

Best wishes,

Thomas Milburn

Blogging one week on

It’s been just over a week since I started this blog. Even in a week I feel like it’s got easier to write posts. I feel under less pressure to write something good, instead I feel free to write about what I want.

The thing I’ve enjoyed most about my blog is choosing the photos to use at the top of each post. I have a varied collection of photos so it’s not too difficult. It’s nice to have a use for my photos, they’re not the most important part of this blog however they make it feel more personal and add another splash of interest.

To be quite honest, I know nobody has actually read most of the things I’ve written about so far. That doesn’t worry me that much, it takes time to pick up a readership (I haven’t publicised this blog anywhere) and I know that posts from my old blog are still being read a whole 7 years on!

Road running to recovery

I went out for a 9 mile run this evening with my local running club. Foolishly, I started out at the same pace as the fastest guys (whom I usually keep up with) and my leg still isn’t fully recovered. After about 5 miles I could feel my left leg starting to cramp up so I had to lay off the pace. I then had a leisurely jog back home.

It’s my aim to get back to my original level of fitness by the end of November so I’ve been on a fairly intensive exercise regime. I’ve tried to go out running 3 times a week, swim twice a week and a long walk at the weekend. It seems to be working, a month ago I couldn’t really jog at all. 3 weeks ago I was right at the back of the running group, having to walk some of the session. From my run this evening I can see that I’m almost managing to keep up with the fast group. Another two weeks doing this amount of training and I should be right back up there.

Perhaps also foolishly, I’ve entered next year’s Paris Marathon. The marathon website tells me I’ve got 135 days to go (it’s in April). 135 days sounds like a lot however 20 weeks doesn’t sound as much. I’d like to start on a proper marathon training schedule in December.

Marathon training is tough especially when you’re as competitive as I am! I’ve never ran under 3 hours in a marathon (3:01 is my best time) so my aim is to break that elusive 3 hour mark. I know that means a lot of running between now and April. I will probably need to dedicate about 10 hours each week to training and up my mileage to at least 50 miles each week.

It’s a good target to aim for and it’s been good motivation to get me out of my flat when it’s dark and wet.

The moon

It was dark on my way back from work and I could see the moon shining through thin clouds. I decided this would be a good chance to try a little astro-photography. I went out with my camera and after a little wait for the clouds to disappear I snapped this. It doesn’t show a great amount of detail but it’s not bad for a first attempt.

You don’t need a telescope to take a good photo of the moon. The moon is actually a really bright object in the sky. What you do need is a tripod (or something similar to keep your camera still) and a fairly long lens. I have a 300mm lens which is equivalent to a 600mm lens on a standard 35mm camera. The length of the lens is important but for night time photography so is the sensitivity and size of the sensor (both in pixels and physical size).

A smartphone simply doesn’t have the sensor size or length of lens, however a lot of modern bridge cameras (which can be found for less than £100) have very long lenses and relatively large sensors. Photography doesn’t have to be expensive!

Being a survivor

On Friday over 130 people were killed by terrorists but many hundreds, possibly thousands more would class themselves as survivors of those atrocities. There are almost a hundred people still in a critical condition in hospital and presumably many hundreds more recovering from fairly serious injuries.

There are lots of people out there still trying to make sense of what happened to them. Each person will have their own story from Friday evening, their own story of utter terror, of panic, of things that are painful to see, hear and even think about.

I thought I was going to die for a couple of seconds, I can only begin to imagine the terror of having that thought for minutes or hours.

There is no definition of what makes a survivor. There is a clear definition between being alive or dead but no clear definition between a survivor and a mere witness. Was someone who hadn’t yet got to that fateful concert in Paris a survivor? Was someone who escaped that concert through a back entrance a survivor?

For me being a survivor is about how you feel. If you feel like you could have not survived then you probably see yourself as a survivor.

In my incident I saw myself as a survivor initially. As the weeks have passed I no longer feel that attachment to the incident. I’m back to being just an ordinary person who’s used up one of their nine lives.

For the lucky people who are survivors of the Paris attacks they may not feel lucky. It is almost certainly an event that will hugely change their lives. Some will be physically changed, broken limbs, scars, paralysis. Others will be mentally changed, losing friends, losing family, having flashbacks.

For me I had it easy, I had no connection to the 11 people that died, my injuries only affected my life for a couple of months and I’ve managed to mentally get over what happened to me.

Mentally getting over a traumatic incident isn’t easy. For me I had to understand what happened. I was quite thankful that the incident was fairly well documented by film and photographs. I could see roughly what had happened. I still have no idea how close I came to being killed, probably about 5 metres. But I do know that I couldn’t have stopped anyone else from being injured or dying and that gives me a lot of comfort.

To stop the constant thoughts and “what ifs” I had to replace my emotional thoughts of the incident with rational logical thoughts. With armed gunmen fighting for a religious cause I’m not sure there are easy answers and a rational way of thinking about things.

For those who feel like survivors of the Paris attacks (or even of any traumatic incident) some advice for you: people are thinking about you and your well-being, it isn’t just about the friends and family of those who passed away. It feels strange to be thought about by people you don’t know at all but it can be a comforting thought. You need a lot of mental strength as a survivor, especially so if you are badly injured. Make sure you get your friends and family to support you, you will need them even if you don’t realise it. Tell people what happened, telling your story can help to reduce the burden of it. At some point you will probably get back to some form of normality, but that may take months or years. And finally don’t expect answers to all your questions. Some things, despite everyones best efforts, will never be answered.

Flash burns

Before my little incident at an airshow I knew very little about burns. As far as I was concerned hot things against your skin caused burns and they were classed as different degrees depending on how serious they were.

Burns are actually far more complex. Burns are any injury that destroys skin caused by some form of energy. That energy might be contact with a hot object, hot vapour, chemicals, friction or, in the case of flash burns, thermal radiation.

At first I thought I had received fairly minor burns to a good proportion of my body. Large parts of my skin initially turned red as my body tried to cool me down as much as possible. Beyond that I can’t remember what my initial injuries looked like, I was in shock and on painkillers so I wasn’t thinking straight.

It was only when I arrived at hospital over 6 hours after the accident that I could see the extent of my burns. I was burnt predominantly on my left leg and my right arm. Only the areas that faced the source of the heat were burnt. But I distinctly remember being inside the fireball, I would have expected to be burnt everywhere that my skin was exposed.

I set out to investigate exactly what had happened to me. I was in hospital for 10 days and had plenty of spare time so I set out to research flash burns and fireballs.

I suffered what the doctors called partial thickness burns (what most people know as second degree burns). This is where the epidermis is completely destroyed and there is partial loss of the dermis. My burns were slightly deeper on my leg and not very deep at all on my neck and upper arm.

Fireballs produce the most heat from their outer surface. This makes sense, only the portion which is exposed to oxygen can burn in a way which produces the greatest amount of heat. Inside the fireball there is incomplete combustion producing soot. These sooty products then completely combust as they meet oxygen at the edge of the fireball.

I estimate that between 500kg and 1000kg of fuel was burnt in total in the crash. This gives us a ballpark figure to estimate the amount of energy that might have been produced and investigate the thermal radiation.

There were multiple events so taking 200kg as the amount burnt in the fireball that engulfed me. Some rough models suggest that the fireball had a radius of about 16m (32m in diameter) and took 2.2 seconds to burn. This is about right looking at videos of the event. These numbers give an average power of about 4GW of which about 1.3GW was radiated. Further calculating the radiant heat flux was about 400kW/m2. My body had a surface area facing the fireball of about 0.5m2 so I experienced 200kW of heating, the equivalent of 100 2kW heaters.

Studies show that the threshold to receive a partial thickness burn is about 200kJ/m2 of energy and the threshold for a full thickness burn is 400kJ/m2. At most I could have received 880kJ/m2 but in reality being at a distance from the surface of the fireball, being within the fireball and my skin being at an angle to the fireball meant that it’s easily plausible I had between 200 and 400kJ/m2 of heat radiated into my skin.

To get an idea for the black body temperature of this radiation we can use Stefan-Boltzmann’s equation. This gives us an average black body temperature of 1300C. That’s really hot!

At this black body temperature the peak radiation is around 1.8 microns in wavelength. Well into the infrared region of the spectrum.

So why was I the only person (as far as I know) who suffered significant partial thickness burns? I’m not really sure. It probably depends on quite a few things. Many people who were within 20m of the fireball were in their cars. Glas windows reflect infrared radiation so people in cars were unlikely to get burnt. Those also at the side of the road seemed to escape unscathed, possibly due to the fact that more soot was produced at their location absorbing a large amount of the infrared energy.

Simply the angle of the skin to the heat source is enough to dramatically reduce the amount of thermal energy the skin receives. If I had taken a different position on the ground I would have been burnt completely differently.

Level crossings part 1

It’s a horrible wet day so I’ve got to find something productive to keep me occupied. I’ve decided I’m going to try and create something which alerts me to trains approaching the level crossing near my flat. The level crossing is very near. I live just across the road from West Worthing station and at the end of the station is the crossing. If I don’t have music on I can easily hear the sirens when the barriers go down. In fact I’ve just heard them now.

To be honest, the level crossing is a real pain, I have to cross it every day on my way to and from work. Almost inevitably, the barriers are down either going or coming from work. It’s also a busy road so there are long queues and most British drivers, being who they are, like to sit in the queue with their engines idling. The crossing is so hated that it has it’s own spoof twitter account.

I’d like to create a web page which displays when the barriers are expected to be up or down in the near future. Ideally, I’d like it to have a level of precision such that I can predict how long it will be until the barriers go up if they are down.

To do this I need data. I already have a few pieces of data:

  • The barriers always go up 5 seconds after a train passes through.
  • The barriers are always down when a train passes through (obviously)
  • The barriers go up for at least enough time to get one cycle of traffic through them (the crossing is adjacent to a crossroad which has traffic lights)
  • Most trains stop at the station (but not all do)
  • Almost all the trains are ‘Southern’ passenger trains (I think there’s one freight train per day in the early hours of the morning)

What remaining data do I need:

  • The times of the trains passing through the level crossing
  • The length of time before the train that the barriers are lowered for.
  • The length of time for one cycle of traffic at the crossroad

I’ll come back to the times of the trains, that’s the most crucial piece of data.

The length of time before the train that the barriers are lowered for is not easy to find out. The crossing is controlled by an operator using CCTV so the timings are probably quite variable. I need to collect some data to see if I can pick out any trends. Thankfully I can do that from the comfort of my living room with a timer. It’s a bit tedious but I collected the data.There was a wide variation in time, the shortest time was just 83 seconds whilst the longest was almost 5 minutes. The average was around 2.5 minutes.

The length of time for one cycle of traffic can also be found in the same way. I know that it varies depending on the traffic. From a short time collecting data, I found that the average traffic cycle was 65 seconds in length. The shortest cycle I measured was 40 seconds and the longest 110 seconds.

I’ll make the assumption that the barriers don’t open if they are likely to be open for less than a minute.

Finally the most important piece of data is the train timings. The naive approach here would be to simply find a timetable copy and work out when trains should pass through this stretch of track. That would be a good approach to get rough times but it wouldn’t be very accurate for a few reasons: trains get delayed, they get cancelled, extra trains get put on and timetables change slightly every few months, I don’t want to spend time updating the website every few months.

In summary I need real time data about the trains in the near future. Good news for me, Network Rail provides that data. I signed up for a free account and within a few minutes I potentially had access to lots of lovely data.

Of course it wasn’t that simple, I needed to subscribe to the correct data feeds and set up a way of receiving those feeds and turning them into the data that I actually wanted. This process is not simple but there was a useful wiki to help me.

Network rail provides several data feeds, they provide a daily and weekly schedule of trains, they provide short term updates to the schedules and they provide a live feed of trains passing through timing points on the network. In addition they provide reference data about the timing points and estimated time between them for various types of train.

The real time data from network rail is delivered in messages using the STOMP protocol. STOMP is relatively simple however it isn’t trivial to correctly get messages from the server. I’m used to working with PHP to build my websites so I decided to use PHP for this project. After a short search on the internet, I found this STOMP library.

With all this data I need to decide how to present the data to the end user. I’ve decided that mapping out the barrier closures in the next hour probably provides the best amount of data and accuracy. I’ll attempt to update the model in real time as new events come in on the feeds.

A quick wireframe sketch

One of my favourite parts of a project comes from putting together the user interface. I always like to sketch out ideas on paper first, it helps me put together web pages much quicker.

I then went and put together the actual web page. I’ve tried to use colour and scale to highlight the important information.

So the first half of my project is complete but I still need to work out how to properly populate it with data. This means building a suitable database and updating the web page using Ajax. Stay tuned for part 2.

As an aside I’m thinking of getting a webcam which produces a stream of images I can analyse to see how well my predictions stack up to the real data. It was also give me much more accurate data about the train services to further improve my models.

As a second aside, the photo at the beginning of the post is not my level crossing, It’s another (nicer) level crossing that I happened to take a photo of in the summer.