Posts Tagged ‘code’

[SPOILERS] Fun with shaders for LD37, part 3!

Posted by (twitter: @avaskoog)
Sunday, December 18th, 2016 5:03 pm

Hey! Posted part 1 and part 2 earlier about some of the custom shaders that were written for our LD37 entry, LOCK AND RELOAD. c:

Since the posts easily get a bit lengthy, I decided to divide this into a series of more bite-sized posts so that I don’t have to sacrifice all too much clarity for the sake of space. This is part three, about two shaders that make use of UV scrolling (sort of) and number two is a spoiler, so do play the game first! c;


Some of the effects are connected to slightly fundamental parts of the story, and since the game ended up being really short due to time constraints, I recommend you play the game first to avoid the spoilers and get the most out of the game with it’s little twists! So I’ll be adding a “read more” tag at to some parts to hide some of the stuff from the front page of the blog.

Note: the game was made in Unity and the shaders were written accordingly and so any code will be given as boiled down versions of the shader code written for that, but obviously everything is readily convertible to something like GLSL with minor to no changes.


Animated TV noise

In the small room that the game takes place there is a television set, and at the start of the game you’ll find that the screen is turned on, but showing nothing but static. Moving static, of course, and not just a frozen image!

View post on

So how does this work? We could of course have gone super fancy and generate noise programmatically right there in the shader, but since we were not looking to do anything procedural here, that was completely unnecessary, and we’re only using a static texture with the noise already in it. The movement comes from randomly jumping around (rather than scrolling) the UV coördinates! ᕕ( ᐛ )ᕗ

UV scrolling

What does it mean to “scroll UV’s”, or “move UV coördinates around”? Well, the UV’s are what determine where and how textures will map onto a mesh/model. By moving the x and y positions of the UV’s along the surface onto which a texture is being rendered, the position of the texture will move. There are many neat uses for this, so let’s look at a few before we move on, just to make sure you understand! (◕‿◕✿)

View post on

A waterfall is easy to achieve by scrolling a repeating texture vertically along a simple rectangular plane. In this particular case, there are multiple layers of textures moving at different speeds on top of each other, as well as some particle systems to help sell the effect further.

This next GIF was recorded from this YT video from the channel ClassicGameJunkie and their show How did they do that?, so go check that cool channel out! Its creator is also working on the 3D platformer Clive ‘N’ Wrench!

View post on

The flat, cartoony eyes in The Legend of Zelda: Twilight Princess are best animated by scrolling the UV’s of the texture around the flat geometry rather than trying to actually move any vertices.

The noise texture

I admit! The briefing on UV scrolling was a filler, to some extent, because there isn’t very much to say about it. It’s very easy, at least now that you know how the concept works! c:

When UV’s scroll enough that we’re able to see one repetition of the texture meet another, there are two ways to go about rendering it. It can either be repeated/tiled, or it can be clamped. You may have seen these option before when looking at a texture in Unity’s inspector. To make it clearer what’s going on, let’s look at the noise texture in both modes:


As you can see, clamping means that the last pixel of each side of the texture will be repeated indefinitely in the corresponding direction, while repeating means, well, repeating. This is what we want, since we want to be able to move to random locations on the texture and still get the TV screen filled up nicely with static.

The noise shader

Finally! As you would know, perhaps from the previous part, the basic way of going about shaders is to run the program on each pixel, or fragment, of something to be rendered, and process the final colour and alpha to output for each. To get the colour from the currently processed pixel, we just use the UV coördinate in the texture that we got from the previous part of the shader, the vertex part. Like so:

fixed4 col = tex2D(_MainTex, i.uv);

What we can do now is to add some numbers to the UV’s—an offset—that will move to a different part in the texture. We want this to happen in a way that looks random, and we want erratic jumping, not smoothly sliding over to the next part in the texture.

The thing to do when one does want to move smoothly around a texture would be to move by a constantly increasing value, like the game’s time. This might alternatively be plugged into some function, like cosine or sine, to move around in wavy or circular fashions.

We won’t do exactly that, of course, but we still need the time variable to have the conditions keep changing. What we can do to get the jagged movements we want is to make use of the modulo operator to see if the current time is divisible by some number, and use that as the basis of our stuff. We’ll even use some wave functions!

Since the rounded number will remain divisible by something until it has changed into something else that no longer is divisible by that number, we’ll be seeing each position where the UV’s end up for at least a few frames, which is of course what we want. We want this to change over time, so we’ll modulo the time by the time itself, but multiply each operand by a different number.

float factor = (time * 10) % (time * 22);

Something like that! That determines how much we move. Now to determine how far and where to move! We’ll use cosine and sine for this, again plugging in the time, multiplied perhaps by something else (or even nothing at all—i.e. 1.0—this time). This will make it move around in circles, but of course we won’t be able to see that as we only skip around on those circles.

float2 movement = float2(cos(time), sin(time) * distance;

The distance variable ensures that we move about a fair distance on the texture, so that the difference between each position is clear. And honestly, we might as well plug in something like time % 100 in there as well to make the noise as varied as possible!

And so we modify our initial line of code:

fixed4 col = tex2D(_MainTex, i.uv + movement * factor);

That’s it! Incredibly cheap cheating for some fake randomness that looks good enough for something like this, where the texture is already very random to begin with. I only used a texture that’s big enough to precisely cover the screen, but in retrospect I’d say this works even better with a texture that’s much bigger than the TV screen, to make any repetitions less obvious!




Thus you may want to play the game before you move on! c;




[NO SPOILERS] Fun with shaders for LD37, part 1!

Posted by (twitter: @avaskoog)
Friday, December 16th, 2016 2:34 pm

Hey! They’re not all too advanced, but I still thought I’d share a little something on the custom shaders that were written for our LD37 entry, LOCK AND RELOAD. c:

Since the posts easily get a bit lengthy, I’ll divide this into a series of more bite-sized posts so that I don’t have to sacrifice all too much clarity for the sake of space. We’ll start with the main shader that gives the game its look and feel!


Some of the effects are connected to slightly fundamental parts of the story, and since the game ended up being really short due to time constraints, I recommend you play the game first to avoid the spoilers and get the most out of the game with it’s little twists! So I’ll be adding a “read more” tag at to some parts to hide some of the stuff from the front page of the blog.

Note: the game was made in Unity and the shaders were written accordingly and so any code will be given as boiled down versions of the shader code written for that, but obviously everything is readily convertible to something like GLSL with minor to no changes.


Post effect filter

This one won’t spoil a thing as it is the very first thing to see upon starting the game: the wonky colour effects and checkerboard overlay. There’s also a dark vignette as well as some increased contrast.

View post on

This effect applies to the whole final rendered image rather than individual objects and is therefore done in one step at the end of each frame, simply applying the shader to each pixel, or fragment.

Let’s go! ᕕ( ᐛ )ᕗ

The low-fi colour effect

This is achieved by first multiplying the colour values (which are all normalised between 0.0 and 1.0) by some factor, then rounding the numbers so that any resulting decimals disappear, and then dividing the values back down again by the original factor. This effectively decreases the colour variation. The smaller the factor, the greater the effect.

col.rgb *= factor;
col.rgb = round(col.rgb);
col.rgb /= factor;



The contrast effect is fundamentally not so complicated. It can be done in different ways, but for this particular game what I found worked best was to subtract some of the intensity of the colour if the original colour was below some tolerance value, but multiply it by some factor if it were above it.

col.rgb += (col.rgb < tolerance) ? 0.5 : 1.5;



Alternating dark and bright squares are all over the screen. This isn’t some texture; just a little bit of maths. By checking the position of each pixel on the screen and figuring out whether it’s even using the modulo operator (which gives the remainder of a division), we can figure out whether the number is evenly divisible by two and thereby whether it’s odd or even.

If we multiply the coördinates by some factor to pretend that the screen is smaller or bigger than it really is, we can control how big the squares get. We apply the effect by darkening odd squares and leaving even ones untouched or vice versa.

col.rgb -= ((floor(x * s) % 2.0) - (floor(y * s) % 2.0)) * darkness;



In this case, a vignette is a darkening of the corners of the screen. We’re basically applying darkness to the whole screen except an oval in the middle, leaving the corners dark but the middle unaffected. Circles are easy. We can achieve an oval by pretending that our rectangular canvas is in fact square.

fixed ratio = height / width;
fixed2 middle = fixed2(0.5 * ratio, 0.5);

We can then check the distance from the center to the current fragment, adjusted for the rectangle’s ratio, to get its position inside a circle, which will appear as an oval thanks to the ratio.

fixed2 pos = fixed2(x * ratio, y);
fixed factor = length(pos - middle);
col.rgb -= factor * darkness;


You will probably want to adjust some values by multiplying them by various factors to make your vignette look the way you want.

That’s it for this part! In the next one (and I won’t be posting it right away as I don’t want to be spammy), we’ll be talking about the first of the two effects in the game that required extra cameras and render textures!

Stay tooned! ☆

p5.js experimentation/prep = code for all

Posted by (twitter: @avaskoog)
Friday, December 9th, 2016 4:49 pm

After using Unity for most of our more recent entries, I’m considering trying something simpler out this time, and just a few days ago I found out about a JavaScript framework called p5.js, which is basically a JS port of the Java framework Processing, in case anybody’s familiar with that. It makes it simple enough to draw things and play sounds in the browser in no time.

In order to learn how to use it and to get some fundamental stuff going (animated sprites, for example), I wrote up a few JS “classes” today. I’m still not sure whether I’ll be using p5.js at all, but in case somebody else wants to use my boilerplate stuff, feel free! c:

A glorious demo (live [warning: thunder audio at the beginning]:

View post on

Fundamental files:

Less interesting but perhaps handy…

You’ll need to tie it up yourself, but I’m sure you can figure it out. The sprite and animation classes want an object from loadImage() and the animation requires a delta time, which you can calculate easily by using millis(). Animation class in particular is a bit tricky perhaps, with a bunch of settings, so read the comments in the file.


Desert Strife Post-Jam AI (with more code examples!)

Posted by
Wednesday, October 5th, 2016 2:31 am



Took a while (too many projects at the moment; loving it!), but here it is: Part 2. The basis of the system is still a reactive AI using heuristics. It doesn’t plan ahead at all, which is good enough even if it does show every once in a while.

The full AI code can be found here, if you care for that sort of thing!


Heatmap, the main technique utilized, simply stores values in an extra tilemap (int array!) for spatial information evaluation. In this case the heatmap stores threat and support values used in choosing the AI attack target and movement path.


Heatmap visualization

The recursive heatmap function is called for each enemy and ally on the map

Threat evaluation

Calculating the threat (and support) values is a cinch: Add up the probable averages of all usable weapon types of your allies and enemies. There is a bit of quess work involved if the enemy ammo counts are not known already.


 Nothing out of ordinary here I’d hope


New feature alert! Taken that we already have threat values for each group and location data about safe areas, we might as well have a bit of fun with them! Every time a group gets into a fight its support value is compared to the threat level around it. A high enough difference will send the group in panic, running away from enemies and finally fleeing if reaching the level border. Now you can bully your enemies to submission!


Panic also ensues if the total enemy force is overwhelming, but that is checked elsewhere


Simple and seems to work alright. In the next project I’ll be using Monte Carlo Tree Search, no doubt about that. It is much less work with potentially more intelligent results. Working on a generic version at the moment.

Play it here!


seththefirst suggested taking a look into AI utility functions in part 1 . The threat level comparison turned out to be sufficient so I didn’t implement anything like it, but maybe you (yes, you!) will find it useful.

Desert Strife Jam AI (with code examples!)

Posted by
Tuesday, September 6th, 2016 3:14 am


The Post-Jam version is still far away (I’ve hardly had any time to work on it yet) so I might as well talk about the AI of the Jam version and the plan for the Post-Jam AI.

Version one

The first version of the AI was finished in the morning of the second day. It had one goal and one goal only, EXTERMINATE! In simple terms each unit finds the closest enemy and moves towards it. They also check that the path to the enemy is not blocked, by simply finding a path to it. This could cause slowdown with bigger maps and larger unit counts, but here it is just fine and dandy.

VIEW CODE (embedding doesn’t work unfortunately…)

Version two

So far the AI doesn’t take into consideration the main mechanic: scavenging technology. Implementing such behaviour, the quick and easy way, requires nothing more than adding technology distance checking into the previous code. If there’s technology closer to the unit than enemies, then that is what the unit will go for. On top of this the unit won’t move until it has completely excavated the technology.


Version three

I could have stopped here, but there was an annoying deficiency in the artificial thought process. The units don’t prioritize actions; In other words, an attacking unit is sometimes blocked by a scavenging unit.

The fix is slightly more elaborate than the previous step, but by no means complicated: tally up the best actions from all units and choose the most important one based on the target type and distance. Here’s the final AI in action.



The future?

There are still a few things I’d like to implement in the AI, namely threat assessment and intelligent positioning. As luck would have it, there’s a single technique which can be used to achieve both of these goals: heatmaps! A heatmap is simply an extra tilemap which contains values based on unit proximity and threat level (if you are lazy you can even reuse the world tilemap objects for this purpose). Heatmaps can be used in selecting the target (lower threat value is preferred) and in pathfinding to choose the safest route to the target.


Keep it simple and you’ll go surprisingly far.

Play Desert Strife here

It’s a clusterfuck!

Posted by (twitter: @Guard13007)
Sunday, December 13th, 2015 4:18 pm

So I haven’t posted anything until now because I’ve been focused on trying to build something cool.

Many many hours of work later, and we have this:

it's a clusterfuck

So the concept for this game is that your two buttons are 1 and 0 because the control systems on this shuttle are fried. You have to execute opcodes in order to fly around, scan, communicate, fire weapons, warp, do whatever. You start out with just those notes on the sides telling you how to control the shuttle. “Growth” has not come into play yet, but the idea is either to build your ship up, or in the future, to build an empire. I won’t get the empire building done within the next few hours, but hopefully I can get some basic scenarios and sector-generation going, and upgrades.

Right now you can travel between sectors which all generate .. pretty much what you started in. I’m working on that! Not much else is done either, but it’s a lot more than I’ve ever put in a game before, so I’m pretty excited!

Code is on GitHub btw.

Oh, and here’s a video (no I’m not live streaming right now cause crunch time) that shows off some of it at an earlier state:

Going in once more!

Posted by (twitter: @Zazanxors)
Thursday, December 10th, 2015 1:33 am

This will be my sixth time and I’m looking forwards to it! Planning to make a smaller game this time around, as I feel my ideas have been too large for me to accomplish in the time frame. As for my tools, I’ll be using Unity (Game Engine), Visual Studio (IDE), Beepbox (Music, some SFX), Chiptone (Other SFX), Paint.NET (Art) and Gimp (Art extras)

As always, I may end up using (and fixing up) some old Unity platformer code I wrote a while back – feel free to use it for your stuff if you want.

Good luck!

Code snippets for everyone to use

Posted by (twitter: @@moongateuk)
Tuesday, December 8th, 2015 6:13 am

Hey everyone,

For my own use I’d been coding up some base code for items and levels. So as of yesterday I’ve put them up over at and it’s called Basecode Bits.

It’s free to use for anything and will be updated with different little snippets predominantly for game dev and game jams.

This is what’s currently included in the small pack:

  • Level Object.
  • Item Object.
  • Basic Level Generation Code.

If you have any ideas or suggestions then post a comment over on the page.

For those having trouble with collision detection in Java:

Posted by
Saturday, August 22nd, 2015 6:08 pm

Try putting this in your player class:

public boolean intersects(Tile tile) {
tile = this.tile;
Rectangle r1 = new Rectangle(x, y, width, height);
Rectangle r2 = tile.getRectangle();
if(r1.intersects(r2) || r2.intersects(r1)) {
return true;
} else {
return false;

And in your main class, put:

if(player.intersects(tile) {

To get a visual interpretation of the rectangles, put this code in your method where you render:
// This is at the top of the class
public boolean meshMode;
// Rendering:
public void render(Graphics2D g) {
if(meshMode) {
// You can of course use any color
// If your ints/doubles aren't public, then make some getters.
g.drawRect(player.x, player.y, player.width, player.height);
g.drawRect(tile.x, tile.y, tile.width, tile.height);
// In Key Listeners:
public void keyPressed(KeyEvent e) {
int k = e.getKeyCode();
if(k == KeyEvent.VK_M) {
meshMode = true;
if(k == KeyEvent.VK_N) {
meshMode = false;

This is a very simple way to calculate collision detection in a 2D Java Game.
Hope this helps a lot :)

I haven’t been here in a long time. So I thought I would share this code I made with you and explain how it works (so people who don’t use Gamemaker can reverse-engineer it). Unfortunately I’m not taking part this time round, but I felt like helping those who are!

Gamemaker Script Code

Simply copy and paste these into two seperate scripts:

Ring Health Bars

Circle Health Bars

To execute the scripts simply use:




Meet The Variables:

Ring Health bars

x,y = the coordinates of the center of the ring

radius = the distance from the center to the start of the ring

thickness = the thickness of the ring

rotation = at what angle is the zero mark of the ring?

angle = over how many degrees does the ring span?

max segments = how many segments the ring is split in to

segments = how many of those segments are visible

direction = which way is the ring drawn? 1 for anti-clockwise and -1 for clockwise

For the circle health bar the variables are the same except that thickness is not included.

Demo download

A demo (gif):

Circular Health Bars Demo


The demo is using two rings; one red and one green to simulate health.

What is this sorcery?

When a computer draws a circle, it is actually just a bunch of triangles arranged in the same way as slices of pie.

To find the coordinates of each triangle to be able to draw them we need a big steaming pile of math.


Specifically we need some trigonometry. Let’s start with which way is up:

Ring Health bars angles

Or in this case, which way is right: zero degrees.

A new temporary variable, i, will count our current angle as we sweep around the circle.

After each cycle in the loop it will change by the angle variable divided by the maxsegments.

Ring Health bars sections


Add to the mix our variables for radius and thickness and we can draw a triangle to work out our x and y coordinates for our triangles to draw!

Ring Health bars triangle

From this we can get the coordinates for the two points a and b. To get point b we simply add the thickness to the radius:

Ring Health bars triangle ab


Then we add the angle change to i, and get the variables c and d. Then we can connect the dots and draw one section!

Ring Health bars triangle cd

Ring Health bars section

Repeating this process for how many sections we want to draw will result in a ring!

This process is the same for the circle, except we only need points a, c, and the center for each triangle.


Good luck for LD 32! Hopefully this tutorial will come in handy.

I kinda rushed this. Hopefully you can understand it if you have a basic grip on maths.

Hexagonal Grids!

Posted by (twitter: @theupgradezone)
Wednesday, November 12th, 2014 5:10 am

So, I did the maths on how to draw a perfect hexagon. Now, using the same logic from that
tutorial, in this tutorial I will show you how to make a hexagonal grid!

Let’s say we have a hexagon with width a and height b.
(If you used the last tutorial, then the value of a from the last tutorial becomes twice that
value in this tutorial)


Now we generate a bunch of hexagons to fill up the screen area.
For this example the point of reference is in the center of the hexagon.

Each hexagon will be 3/4*a to the side of the last one, and b above or below:


Remember to keep a and b as whole numbers!

So the screen should look like this: (grey = hexagon, dark grey = overlap)


But we need every 2nd column to go up a bit, so that the hexagons interconnect properly.
So we use this equation, where x and y are the coordinates of the center of each hexagon:


Now your screen will look like this:



Now we can code it!

Pseudo Code:

width = (width of hexagon)
height = (height of hexagon)

Creation Loop:
create hexagon
x = x + (3*width)/4
if edge of screen is reached {
go back to starting edge of screen
y = y + height

Creation code for each hexagon:
y = y + mod(sin((90*(x/width))*height/2)



And there you have a hexagonal grid!

And this is the last of my little group of tutorials :3
Thanks for the comments on how to refine the logic and code of previous tutorials :)

How to draw a perfect Hexagon!

Posted by (twitter: @theupgradezone)
Tuesday, November 11th, 2014 9:55 am

So I did that maths of drawing a perfect octagon. Now, for a perfect hexagon!


First, we must imagine a rectangle with width a and height b.
You must now choose which side, a or b, you want to specify.


If you specified a, to find b you must use this equation:




If you specified b, to find a you must use this equation:


Which can also be written as:


Remember to round to the nearest number!



Once you have a and b, we need to specify the 6 coordinates.
For this example, the frame of reference is the center of the rectangle.

The top and bottom two are b/2 up or down and a/2 to each side.


The two sides are a to the side.


Then you draw lines between the coordinates.


And there you have a perfect hexagon!


Pseudo Code:

// Let’s say we specified the width, a
width = (width of imaginary square)
height = 2 * width * sin(60)


coord_1x = x – width/2
coord_1y = y + height/2
coord_2x = x + width/2
coord_2y = y + height/2
coord_3x = x + width
coord_3y = y
coord_4x = x + width/2
coord_4y = y – height/2
coord_5x = x – width/2
coord_5y = y – height/2
coord_6x = x – width
coord_6y = y




And that’s how to draw a perfect hexagon!

Coming soon: Hexagonal grids!

How to draw a Perfect Octagon!

Posted by (twitter: @theupgradezone)
Tuesday, November 11th, 2014 4:45 am

I did some maths while I was bored, and I calculated a way to draw a perfect octagon.
I thought this might come in useful for some of you :3

Warning! Maths ahead!



Imagine a square, with side length a.


Our octagon will fit in this square.

We will call the length of a side of the octagon b.



Now you put a into this equation:


Which can also be written as:


And you get b.

Now, round b to the nearest number. We can’t be dealing with fractions of pixels now, can we?

Now you have b, we can draw the octagon.



For this example, our reference point will be in the center of the octagon, which is also the center of our imaginary square.


Our first 2 co-ordinates will be a/2 up and b/2 to either side.



For the sides, it will be a/2 to the side and b/2 up or down.


Then, draw lines between the co-ordinates to finish the octagon.


And there you have a regular octagon!


Pseudo code:


size = (length of side of square)
oct_side = round((size*sqrt(2))/(2+sqrt(2)))


coord_1x = x – oct_side/2
coord_1y = y + size/2
coord_2x = x + oct_side/2
coord_2y = y + size/2
coord_3x = x + size/2
coord_3y = y + oct_side/2
coord_4x = x + size/2
coord_4y = y – oct_side/2
coord_5x = x + oct_side/2
coord_5y = y – size/2
coord_6x = x – oct_side/2
coord_6y = y – size/2
coord_7x = x – size/2
coord_7y = y – oct_side/2
coord_8x = x – size/2
coord_8y = y + oct_side/2





And that’s how to draw a perfect octagon!

Coming soon: How to draw a perfect hexagon!


To those interested in the maths involved to get the equation:



I originally calculated this to be able to draw the Aperture Science logo by hand, but I also saw the use of it on the computer!

Base code update

Friday, December 13th, 2013 4:04 pm

I’ve written a little base code project I’m going to start with.

It’s fairly simple and is available here.

To recap, it uses libgdx. If I fancy some postprocessing shader stuff, I’ll use the PostProcessor class from here, and if I need to do some pathfinding, I have my own simple A* implementation I wrote which is available right here.


Hi everyone

****I posted new questions about compilers and editors in the comments please read them :) ****

I am an experienced programmer and know a few languages.

I want to start making games with a windows 7 computer for any operating system (linux, Mac and Windows).

I do not know which is the best coding language to use for that that is free But has a good compiler and runs well. I also do not want to use software like gamemaker or construct. Something like c++ or java or love2D so please take that into consideration!

Also what libraries would I need for 2D games for now to make it with.

Thanks so much for your help in advance! I really want to become some kind of game devloper so this is key.

Hope you all are having fun in the ludum dare! Expect me to be ready for the next one!

Hope my questions make sense!

Please comment!



Yesterday my stream peaked at 126 people watching me program! In order to make it a true 53 hour marathon, I just left the stream going overnight and pointed the camera at my bed. When I woke up, there were still 44 people in the stream who greeted me as I got back on! Aha, ha ah!

More coding action today at! I’m making a massively multiplayer online capture the flag turn based real time game using Django and Coffeescript.  I’m hoping to have a playable game today.  Stay tuned! #ld48


[cache: storing page]