2D ray casting

I haven’t been writing for a while mostly because of my studies and my laziness. But I have spent my free time on game development. In my previous post I mentioned changing my development framework into Libgdx (http://libgdx.badlogicgames.com). Oh and I also finished my first Android application and published it in Google Play (https://play.google.com/store/apps/details?id=com.game.simplewordgame). It has been a good choice and my code quality is now better and I get things done more faster without the horrible learning curve with plain OpenGL ES.

In this blog I’m going to write about 2D ray casting. Ray casting is a test to find out which object intersects first with a ray casted from another object. So basically in game world it would mean which objects block another object’s view and which object is seen by another object.

In 2D strategy games ray casting is needed to tell does the game character see another game character or is something blocking its view. Here is my demonstration of ray casting.

Screenshot at 2013-03-27 14:19:41

Lines representing line casting are the red straight lines fanning out from the game character.Screenshot at 2013-03-27 14:19:56

The game characters turns around and now the casted lines intersect with the other game object thus coming visible for the game character and the player.

Screenshot at 2013-03-27 14:20:08

Here we can see how the wall stops the lines so that we don’t see if there are any game objects behind the walls.

The Code

Basically ray casting is just a loop that checks if the coordinates along the straight line intersect with anything. When ray intersects with an visual obstruction the further point won’t be checked for overlaps so the object behind the obstruction won’t be seen.  In my case it might have been easier if I my game world would have been composed of square or hexagon cells. In that case the loop could go through the cells and be sure if there is anything in the cell or not. But I did it through the hard way. No cells, just plain coordinates in the game world. Here is my loop for ray casting.

//Defines how many rays (I’ve named these as lines)
private final static int LINE_AMOUNT = 10;
// How long the rays are
private float[] lineScale = new float[LINE_AMOUNT];
// Are the lines overlapped with with an object
private boolean[] linesStopped = new boolean[LINE_AMOUNT];
/**
*
* @param actors = objects in libgdx framework
*/
public void countPoint(Array actors){
/**
* makes sure that new calculations are made only if the character
* turns more than 5 degrees so it will be faster and more practical.
*/

if (Math.abs(previousAngle - te.charInTurn.getDirection()) > 5) {
previousAngle = te.charInTurn.getDirection();

falsifyLineStopped();
//Every line has 180 points to be checked between 0.013f
for (int i = 0; i < 180; i++) {
for (int j = 0; j < lineScale.length; j++) {
// if line hasn’t overlapped with an object it will continue
// calculate further points
if (!linesStopped[j]) {
lineScale[j] = (0.013f * i);
linesStopped[j] = adjustLinescales(i, j, actors);
}

}

}
}
}
/**
* Reboots the lines as not stopped.
*/
private void falsifyLineStopped() {
for (int i = 0; i < linesStopped.length; i++) {
linesStopped[i]=false;
}

}

As one can see this loop can be very slow for processor to calculate. So it’s more practical to limit the amount of rays and points along the rays where overlapping is checked. Rays should also have a limited length or the loop will continue infinitely. This however can make paper thin visual obstructions invisible and make farther objects less likely to be seen. I also made an if statement so that game doesn’t go through a new ray casting loop unless the game character turns more then 5 degrees from the previous angel of ray casting.

Changes

So I had little problems walls and doors. Well I had wall textures drawn but there is no use for wall that lets characters walk through them.  I spent three days just  to make collision detection between walls and game characters (or maybe more like collision prevention). Basically my collision prevention had to know where the walls were according to the game character. It was a walk in the park to figure that out but I’d probably would like scale my levels into a big mazes so it could slower my game if the game should check distance to every single wall. So I gave each room, also the space outside the rooms, an ID. Now my game goes through only the walls in the same room as a potential walls which may collide with game characters.

In earlier blog post I presented my circle for turn-based moving and the blue path that pointed the direction and use of action points by the moving action. The game doesn’t prevent game character overlapping with wall but it doesn’t give enough action points to characters to go through walls.

I also decided to make some major changes in my game. As I have told my framework was based on source codes from here: http://code.google.com/p/beginning-android-games/ . My current framework was great for teaching myself how to program for Android  and I really thought my game was so simple I could make just doing everything else by myself. But now after few months I’ve noticed my time goes more on trivial programming tasks, like colliding with walls, than adding new features.

My choice for new development framework was libGDX (http://libgdx.badlogicgames.com/). Main reason for my choice was that I could set up a project rather quickly, but it also makes cross-platform game development pretty easy and the author of Beginning Android Games is behind it. Also there are many Android games made with libGDX (for example Apparatus: https://play.google.com/store/apps/details?id=com.bithack.apparatus) and the Apache 2.0 licence makes even the commercial use possible. So probably my future posts are going to be updates about moving my code on different framework. Either how successful or what  a horrible disaster it was.

 

 

 

Greatest Failures So Far…

So I made a small list of failures during my game development journey. I probably couldn’t solve any of these problems on my own, I’ve found solution to almost every problem by reading android developer website, stackoverflow, wikipedia or blogs written by android developers. Part of this reason this blog is a bit like collection of great links that have helped me to fix my failures. Right now I have fever so I apologize if my post gets too delirious.

1. Not Planning Enough

Okay I didn’t went just to write code, and noticed that I had written useless dead end code,  when I started my project. I took pen and paper which is probably the best way to start planning any programming project. I drew umlish mind map which described how the turn-based engine worked, but I left Android activities out from it. I didn’t revise my plans when making radical change either. So after I while I was wasting time pondering what to do next and do I have to change something from current code if I do it.

Since software architecture planning is quite vast subject (and since I am such a lazy person) I think just explain my point with links. Here is somewhat simple introduction to UML: http://www.ibm.com/developerworks/rational/library/769.html. UML is a great way to visualize classes and their methods just as longs one doesn’t overdo it.

Here is a Android app concept design that I found great example for android app with lots of activities: http://faucgutier8.wordpress.com/2012/08/13/animator-creator-app-design/ . It looks a bit complicated first but it’s so comprehensive it’s way easier to start writing code.  Plans are perfect if the time after planning is spent in programming and other practical stuff like making graphics, not wondering what to do next. Of course perfect plans are really rare in software architecture so better be prepared for errors in planning, but the errors are not reason leave proper planning out (okay I admit that was a bit vague way to put it).

2. Using Android emulator

After my Android phone broke, I thought my only option was Android emulator that came with the SDK. And boy do I hate that emulator. I mean I really really hate it! In Finland we have this idiom that fits here perfectly, “Android emulaattorin käyttö on yhtä tervan juontia”, wich means, “Using Android Emulator is like drinking tar”. I was actually interested in android development before I had my Android cellphone but the emulator in Eclipse scared me away.

In Android development blog there was a post how the emulator is now faster (http://android-developers.blogspot.fi/2012/04/faster-emulator-with-better-hardware.html). Well I don’t see any difference, it’s still like a pint of tar. Okay part of it might be because I have a really old computer and I’m not emulating Android 4.0. But there is another faster way to test Android programs without Android phone. Android-x86 is an Android OS made for personal computers and VirtualBox is software for virtualizing operating systems. Virtualization with these is way faster than emulator.  But there is no reason for me to explain how to set them up since there is well detailed blog on how to set up VirtualBox and Android-x86 for testing Android apps on Eclipse (http://blog.gokifu.com/2011/05/android-x86-faster-emulator/).

3. Not Using Revision Control

Well I didn’t have any catastrophic, “I replaced big part of the working code with useless code”-moment, but I had many, “It would be so much easier to go back”-moments when the Ctrl+Z just isn’t enough. I did very brief research on revision control softwares and solutions. I chose Git on emotional grounds (if manual says it’s, “the stupid content tracker”, it’s have to be good). So I’m using it in eclipse with EGit (http://wiki.eclipse.org/EGit/User_Guide) which I’m still learning. There is also entire online book about Git for free (http://git-scm.com/book). Here article about revision control that I found through Wikipedia: http://betterexplained.com/articles/a-visual-guide-to-version-control/.

XML & JSON

I think I broke my laptop (no sound, mouse doesn’t work and keyboard has difficulties understanding finnish) but it isn’t slowing my game development yet. Anyway I had to do some research a while ago about serialization and deserialization (i.e. how to save my game information and how to load for example character or item objects from files). In small casual games there probably isn’t need for larger serialization but in strategy games I don’t think it wouldn’t be smart to pass a huge Java object array or list around between activities.

XML

First option that came into my mind was XML. I’m not much of an XML expert but do know it is a markup language and I had heard that it isn’t exactly a winner in the database or serialization circles. I had some programming experience of it though. Of course through the Android layouts but I had also made parser that made OpenGL vertices from SVG paths. I also knew that Android has also XML parsers in the Android API (http://developer.android.com/training/basics/network-ops/xml.html).

So for example short array for characters in my game would look something like this:

<?xml version="1.0" encoding="UTF-8"?>
<GameCharacterArray>
<GameCharacter>
	<name>Markku Markkanen</name>
	<characterId>1</characterId>
	<accuaracy>4</accuaracy>
	<speed>5</speed>
	<strength>9</strength>
	<perception>5</perception>
	<intelligence>2</intelligence>
	<firearmSkill>33<firearmSkill>
	<characterType>POLICE</characterType>
</GameCharacter>
<GameCharacter>
<name>Sam Diego</name>
<characterId>2</characterId>
	<accuaracy>7</accuaracy>
	<speed>4</speed>
	<strength>6</strength>
	<perception>7</perception>
	<intelligence>8</intelligence>
	<firearmSkill>47<firearmSkill>
	<characterType>POLICE</characterType>
</GameCharacter>
</GameCharacterArray>

Size of this file would be about 600 bytes (indentations affect on the size of the file a little bit). XML is easy for human to read but start tags and end tags makes this file difficult to edit by hand in text editor without any autocomplete tricks. It probably would be easier to make GameCharacter into an empty element and current elements inside GameCharacter into attributes. Which would look something like this:

<GameCharacter
	name = "Markku Markkanen"
	characterId= "1"
	accuaracy="4"
	speed="5"
	strength="9"
	perception="5"
	intelligence="2"
	firearmSkill="33"
	characterType="POLICE"
/>

So this is a little bit more easier to read and it takes less space: about 400 bytes.

JSON

JSON (JavaScript Object Notation) is an alternative for XML in serialization. First I just passed JSON because I haven’t used much JavaScript and I thought JSON is something made specially for JavaScript and if I use it in Android with Java  my laptop will explode and I get laptop shrapnels in my hands and it will hurt my hands. I got over my JSON fobia after I looked closer to the syntax of JSON and found out that JSONObject and JSONArray is included in Android API (http://developer.android.com/reference/org/json/package-summary.html).

My stumpy GameCharacterArray would look like this in JSON:

[
{
"characterId":1,
"name":"Markku Markkanen",
"accuaracy":4,
"speed":5,
"strength":9,
"perception":5,
"intelligence":2,
"firearmSkill":33,
"characterType":"POLICE"
},
{
"characterId":2,
"name":"Sam Diego",
"accuaracy":7,
"speed":4,
"strength":6,
"perception":7,
"intelligence":8,
"firearmSkill":47,
"characterType":"POLICE"
}
]

JSON is pretty easy to read. The square brackets define a JSON object array and curly brackets define JSON object. Handling JSON files is pretty easy with the help of JSONTokenizer, JSONObjects and JSONArray. Size of this file would be 331 bytes.

Comparison

Both XML and JSON are easy to read for humans. XML is ubiquitous but JSON is more specialized. I found conference article by Audie Sumaray and S. Kama Makki where XML and JSON are compared in data serialization with binary serialization formats: Apache Thrift and Google’s Protocol Buffer (Such a boring name). Well the conclusion in Sumaray’s and Makki’s article was that JSON is exceptionally better in data serialization than XML, both in speed and size. Protocol Buffer and Apache Thrift were faster and more compact but they are not human readable so they do not work for me. So my choice in the end was JSON and I haven’t regretted it yet. Of course there would have YAML which is also pretty popular data serialization format but I was too lazy to look into it.

References

Audie Sumaray and S. Kami Makki. 2012. A comparison of data serialization formats for optimal efficiency on a mobile platform. In Proceedings of the 6th International Conference on Ubiquitous Information Management and Communication (ICUIMC ’12). ACM, New York, NY, USA, , Article 48 , 6 pages. DOI=10.1145/2184751.2184810 http://doi.acm.org/10.1145/2184751.2184810

.

Link

Usually turn-based tactics and strategy game’s game objects are inside squares or hexes. I’ve decided that in my game it would be fun to make turn-based game without those board game like cells. Biggest differences compared to hex and square thingies, I could think of when I planned this, were: objects positions are not hex No. X but x and y float coordinates in game space, distances are not X amount of hexes but  float numbers and the area where game characters can move are now circles. So I’ve came up with MoveCircle which shows where player character can move, how many action points moving will take and path which character will use. I can’t remember, have I seen this kind of way to control character in any other game but it’s so simple I think I am just reinventing the CIRCLE here (but that joke was really original).

Moving path (the blue line in the picture) now shows how far within the green circle the character will go but I’m also going to make it show a path around objects which are blocking the way.

Since OpenGL doesn’t have circle shapes by default  I had to make my circles by myself from triangles. Easiest way for this is to make for-loop which counts vertices from distance from the center of the circle and angle with the help of my arch-nemeses from senior high school: sine and cosine.

//Green circle's vertices
circleArray[0] = 0;
circleArray[1] = 0;
// Angle
float theta = 0;

for (int i = 2; i &lt; circleArray.length; i+=2) {
    // x-coordinate
    circleArray[i] = FloatMath.cos(theta);
    // y-coordinate
    circleArray[i+1] = FloatMath.sin(theta);
    //Black line circle's vertices
    lineCircleArray[i-2] = circleArray[i];
    lineCircleArray[i-1] = circleArray[i+1];
    // The angle is in radians
    theta += 2*(Math.PI) /((circleArray.length/2)-1) ;
}

The circleArray is an array which consists the green transparent circle’s vertices. It also has the center vertices because it will be drawn from triangles. This loop also includes the black hollow circle’s vertices. It doesn’t have center vertex  because it’s made from lines. When for-loop fills the arrays the line circles and green circle are same size but when OpenGL draws them I just scale them smaller.

The more circle has vertices  the more smoother it is. This also means bigger arrays for vertices and possibly less frames per second. My circleArray’s length is 38 so it has 19 vertices (18 on the edges and 1 in the center). Of course one can distinguish the edge lines in my circles but it’s perfectly adequate for testing.

More about OpenGL ES circles:

http://stackoverflow.com/questions/4811981/drawing-a-circle-in-android-with-opengl-es-results-in-a-square

http://gamedev.stackexchange.com/questions/26232/drawing-a-circle-in-opengl-es-android-squiggly-boundaries

My progress so far

It’s  been bit too long time after my last post but I have been programming my game more or less almost every day. Right now I have basic turn-based moving and attacking but I also have basic AI for the opponent game characters (…well very very basic, but hey moving in the opposite direction from the player character is fleeing).

As one can see from the picture it is messy and unfinished, but it is adequate for the testing purposes. The screen is consisted of android text view and OpenGL ES. On the top of the screen there is a space for in game messages e.g. “Suspect has been injured” but now I’m using it also for monitoring game character coordinates and user interface events. This I made by adding android text view with transparent background on top of the OpenGL surfaceview.

According to the all-knowing Internet (http://stackoverflow.com/questions/1339136/draw-text-in-opengl-es-android) this is slower way to view text in OpenGL game but I found this simplifying things way more than the other solutions. Other way would have been changing alphabets into a texture atlas and using them as sprites but for lazy person like me its sounded like way too much work. For my game the slower option is not that bad because frame rate isn’t that important in turn-based games. Numbers I had to make into sprites and I probably have to make some short words and phrases into sprites but with more complicated text I’m going to stick with my TextView.

I have been using framework based on tutorials in “Beginning Android Games” book (https://code.google.com/p/beginning-android-games/). They are licensed with the new BSD licence so the code isn’t copyleft licensed.

On the next post I’m going to explain about moving the player characters (this has something to do with the green circle or ellipse and the blue line in the picture) and little bit about virtual android OS which I am using after my Android dropped on the floor of my bathroom.