Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

30. November 2012

 

One of the most difficult concepts that new developers have to deal with is math.  As you may have noticed, i’ve been publishing a series of game math recipes over the past week or so.  I have now officially compiled them together into a single (static) page.  You can reach the table of contents here.

 

Right now there are recipes for:

  • Rotating to face a point
  • Rotating one object around another
  • Velocity and angular velocity
  • Axis aligned bounding box – Intersections
  • Axis aligned bounding box – Rotation

 

 

For each recipe, there is full source code, a running example and a description of what is happening.

 

I have other idea’s for math related recipes to add to this series, but of course I am open to suggestions.  If there is a particular topic you would like to see covered, post a comment in this thread.

 

So, if you are interested, go check it out.

Programming ,

29. November 2012

 

Alright, in the what not to do with DRM category, this one rates right up there with the Sony rootkit fiasco.  The popular game development program GameMaker by Yoyo Games recently released a DRM update, that resulted in this happening to some paying users assets:

 

(Image source reddit user passa91)

 

Oh and for the record, those changes are permanent… it isn’t some overlay they’ve done, GameMaker actually physically altered the source images.  The story was originally broken on ArsTechnica and is currently being discussed on reddit.

 

Also from the comments on reddit ( completely unconfirmed by the way ) is this scary comment:

Also this admission from developer Mike on the forum:

For those who CAN afford it, but find it just as easy to copy it. Well, rest assured, we know the games which get made, and if something does well.... I'm sure we'll be in touch.

In other words, all games compiled with GM Studio report back to YoYo HQ. Not cool, at all.

 

You know what, I’m all for protecting your product, but that combined with this horrible screw up, let’s just say Yoyo really ought to rethink their strategy on DRM!

 

Where you effected?  Does this misstep discourage you from ever using GameMaker in the future?  At the very least has this taught you a lesson in backups and version control?

News , ,

28. November 2012

In a prior recipe, we looked at how to handle collisions using an axis aligned bounding box, but there was one major problem.  If our bounding box is axis aligned, how do we handle rotation?  As you can probably tell by gigantic spoiler of a rotating jet to our right, the answer is we resize the bounding box to match the new extents of the rotated sprite.  Let's look at how:

 

Just the Math

if(createjs.Bitmap.prototype.getBoundingRect == null){

createjs.Bitmap.prototype.getBoundingRect = function(){

var bb =  new createjs.Rectangle(

        this.x - this.image.width/2,

        this.y - this.image.height/2,

        this.image.width,

        this.image.height);

 

var corners = new Array();

corners[0] = new createjs.Point(bb.x,bb.y); //Top left

corners[1] = new createjs.Point(bb.x + bb.width,bb.y); //Top right

corners[2] = new createjs.Point(bb.x,bb.y + bb.height); // Bottom Left

corners[3] = new createjs.Point(bb.x + bb.width,bb.y + bb.height); //Bottom Right

 

var midPoint = new createjs.Point(this.x,this.y);

 

for(var i = 0; i < corners.length; i++){

    corners[i] = rotatePoint(corners[i],midPoint,this.rotation);

}

 

var minX,minY,maxX,maxY;

minX = maxX = corners[0].x;

minY = maxY = corners[0].y;

 

for(var i =1; i < corners.length; i++){

    if(corners[i].x < minX) minX = corners[i].x;

    if(corners[i].x > maxX) maxX = corners[i].x;

    if(corners[i].y < minY) minY = corners[i].y;

    if(corners[i].y > maxY) maxY = corners[i].y;

}

 

bb.width = maxX - minX;

bb.height = maxY - minY;

bb.x = this.x - bb.width/2;

bb.y = this.y - bb.height/2;

 

return bb;

}

}

 

Controls:
Click on the box to focus and press B to toggle the blue box from being displayed.

Description

That code excerpt makes it look more complicated than it actually is, not the version at the bottom of this post in the Complete Code section is more heavily commented.

Essentially as our underlying sprite rotates, the bounding box around it changes in size.  Now when we are creating our bounding box, we have to take the rotation into consideration.  Please note, there are a number of opportunities to optimize this code for performance, I favoured readability over performance, although I did note a few of the opportunities for improvement in the code comments.

First thing we have to do is get the original, untranslated bounding box of the sprite.  This is simply the image dimensions of our source sprite.  Unfortunately EaselJS doesn't provide a mechanism for defining a rectangle about it's mid point, like we have with our sprite, so we need to calculate the x and y values of our bounding box, which is at the top left corner of the rectangle.  This value is calculated by subtracting half the sprites width and height from it's location ( at it's mid point ).  If your library of choice allows you to specify a rectangle using it's mid point, width and height, you can remove some of this ugliness.

Now that we have our untranslated bounding box, we want to apply the sprite's rotation to each corner of the sprite.  We accomplish by applying a rotation around the centre of the sprite to each corner of the bounding box, see the See Also section for more details about rotation.  Note, this is one of those areas you could easily optimize for performance down the road.   

Now that all 4 corners have been rotated, we need to figure out what the smallest rectangle that will encompass our translated points is.  To determine this, we loop through each point in our array, looking for the largest and smallest values in the X and Y axis.  Once we have determined what the new boundaries our, we construct our newly resized bounding box using these values.  Once again, we can't specify a rectangle using it's centre point in EaselJS, so once again we need to calculated the top left corner using the same logic as before.

If you turn off the blue debug lines I've drawn around the translated shape ( click the window and press B to toggle ), you will notice there is a ton of empty space as the sprite rotates, making it easy for collisions to appear to happen even though the space is actually empty.  You are very correct, and this is one of the biggest downsides to using AABBs.  There are however options for dealing with this, some of which we will discuss later on.

When looking at the complete code below, realize that a great deal of it is for rendering debug information on screen and wouldn't normally be required in your collision detection code.

Complete Code

<!DOCTYPE html>

<html>

<head>

    <script src="http://code.createjs.com/easeljs-0.5.0.min.js"></script>

    <script>

        var jetSprite;

        var stage;

 

        // Actual bounds is the Shape used to store the drawn blue bounding lines

        var actualBounds;

        // hideActualBounds is a toggle for making the debug lines visible or not

        var hideActualBounds = false;

 

        document.addEventListener('DOMContentLoaded', demo,false);

        document.onkeydown = function(e){

            switch(e.keyCode)

            {

                case 66: // up arrow

                    hideActualBounds = !hideActualBounds;

                    break;

            }

        }

        function rotatePoint(point, center, angle){

            angle = (angle ) * (Math.PI/180); // Convert to radians

            var rotatedX = Math.cos(angle) * (point.x - center.x) - Math.sin(angle) * (point.y-center.y) + center.x;

            var rotatedY = Math.sin(angle) * (point.x - center.x) + Math.cos(angle) * (point.y - center.y) + center.y;

 

            return new createjs.Point(rotatedX,rotatedY);

        }

 

 

        if(createjs.Rectangle.prototype.intersects == null){

            createjs.Rectangle.prototype.intersects = function(rect){

                return (this.x <= rect.x + rect.width &&

                        rect.x <= this.x + this.width &&

                        this.y <= rect.y + rect.height &&

                        rect.y <= this.y + this.height);

            }

        }

 

        if(createjs.Bitmap.prototype.getBoundingRect == null){

            createjs.Bitmap.prototype.getBoundingRect = function(){

                var bb =  new createjs.Rectangle(

                        this.x - this.image.width/2,

                        this.y - this.image.height/2,

                        this.image.width,

                        this.image.height);

 

                // Get the 4 corners of the bounding box, order doesn't matter since they can potentially change

                // Note, you could optimize this two only require the top left and bottom right corners

                var corners = new Array();

                corners[0] = new createjs.Point(bb.x,bb.y); //Top left

                corners[1] = new createjs.Point(bb.x + bb.width,bb.y); //Top right

                corners[2] = new createjs.Point(bb.x,bb.y + bb.height); // Bottom Left

                corners[3] = new createjs.Point(bb.x + bb.width,bb.y + bb.height); //Bottom Right

 

                var midPoint = new createjs.Point(this.x,this.y);

                // Now apply the rotation of the sprite to the corners of the bounding box

                // This loop could be merged with the min/max loop for optimization purposes

                // But for readability I keep it separate for now.

                for(var i = 0; i < corners.length; i++){

                    corners[i] = rotatePoint(corners[i],midPoint,this.rotation);

                }

 

                // Draw the rotated shape for debug reasons

                // This draws a rectangle as 4 lines around the actual rotated image bounding area

                if(actualBounds){

                    stage.removeChild(actualBounds);

                }

                if(!hideActualBounds){

                    var g = new createjs.Graphics();

                    g.setStrokeStyle(1);

                    g.beginStroke(createjs.Graphics.getRGB(0,0,255));

                    g.moveTo(corners[0].x,corners[0].y);

                    g.lineTo(corners[1].x,corners[1].y);

                    g.lineTo(corners[3].x,corners[3].y);

                    g.lineTo(corners[2].x,corners[2].y);

                    g.lineTo(corners[0].x,corners[0].y);

 

                    actualBounds = new createjs.Shape(g);

                    stage.addChild(actualBounds);

                }

 

                // These variables hold the smallest and largest X and Y values found in the Point array

                var minX,minY,maxX,maxY;

 

                // Small optimization here, start assuming first point is correct to eliminate a loop iteration

                minX = maxX = corners[0].x;

                minY = maxY = corners[0].y;

 

                // Loop through Points determining the boundaries of our newly rotated rectangle

                for(var i =1; i < corners.length; i++){

                    if(corners[i].x < minX) minX = corners[i].x;

                    if(corners[i].x > maxX) maxX = corners[i].x;

                    if(corners[i].y < minY) minY = corners[i].y;

                ��   if(corners[i].y > maxY) maxY = corners[i].y;

                }

 

                // We now have the four extreme points of our new bounding box, update bb with new box dimensions

                bb.width = maxX - minX;

                bb.height = maxY - minY;

                bb.x = this.x - bb.width/2;

                bb.y = this.y - bb.height/2;

 

                return bb;

            }

        }

 

        // This function is responsible for actually drawing the bounding box on screen

        function updateBoundingBox(){

            // Draw the bounding rect and create a new Shape with it

            var g = new createjs.Graphics();

            g.setStrokeStyle(1);

            g.beginStroke(createjs.Graphics.getRGB(255,255,255));

 

            var bb = jetSprite.getBoundingRect();

            g.drawRect(bb.x,bb.y,bb.width,bb.height);

 

            if(jetSprite.boundingBox){

                stage.removeChild(jetSprite.boundingBox);

            }

            jetSprite.boundingBox = new createjs.Shape(g);

            stage.addChild(jetSprite.boundingBox);

        }

 

        function demo(){

            stage = new createjs.Stage("theCanvas");

 

            jetSprite = new createjs.Bitmap("jetsprite.png");

            jetSprite.boundingBox = null;

            actualBounds = null;

 

            stage.addChild(jetSprite);

 

            // Add a Image load handler, as image.width and image.height are meaningless until

            // load is done and DOMContentLoaded doesn't seem to take into account dynamic images

            jetSprite.image.onload = function(e){

            jetSprite.y = 200;

            jetSprite.x = 200;

            jetSprite.regX = jetSprite.image.width/2;

            jetSprite.regY = jetSprite.image.height/2;

            updateBoundingBox();

            }

 

            //And go...

            stage.update();

 

            // onFrame will be called each "tick". Default is 50ms, or 20FPS

            createjs.Ticker.addListener(onFrame);

        }

 

        function onFrame(elapsedTime) {

            // Convert from milliseconds to fraction of a second

            var delta = elapsedTime /1000;

 

            jetSprite.rotation = jetSprite.rotation + 1;

            if(jetSprite.rotation > 360) jetSprite.rotation = 0;

            updateBoundingBox();

            stage.update();

        }

    </script>

 

</head>

<body>

<canvas width=400 height=400 id="theCanvas" style="background-color:black"/>

</body>

</html>

 

 

See Also

See Collision Detection using an axis-aligned bounding box for part one of this recipe.

See Rotating one point around another point for more information on the code used to rotate the bounding box.

 

Programming

26. November 2012

Collisions are one of those things almost every game deal with eventually.  This is going to be a multi-part recipe on collision detection.  This part specifically explains what an axis aligned bounding box actually is, as well as how to detect if two such bounding boxes have collided.

 

Let's start straight away with some code, then we will discuss the details a bit more later on.  This example simply animates one bounded sprite until it collides with another.  Once an intersection is detected, the positions are reset and the whole things starts all over again.

 

Just the Math

Creating the bounding box:

if(createjs.Bitmap.prototype.getBoundingRect == null){

    createjs.Bitmap.prototype.getBoundingRect = function(){

        return new createjs.Rectangle(

                this.x - this.image.width/2,

                this.y - this.image.height/2,

                this.image.width,

                this.image.height);

    }

}

 

Checking if two bounding boxes intersect:

 

if(createjs.Rectangle.prototype.intersects == null){

    createjs.Rectangle.prototype.intersects = function(rect){

        return (this.x <= rect.x + rect.width &&

                rect.x <= this.x + this.width &&

                this.y <= rect.y + rect.height &&

                rect.y <= this.y + this.height);

    }

}

 

 

Description

The creation of a bounding box is pretty simple.  In this case, our sprite's pivot point is at it's centre, so our top left corner is half the height and width away from our position.  If you are unfamiliar with JavaScript, some of this code might look a bit confusing.  Basically what we are doing is adding a method to the "class" Bitmap named getBoundingRect, but first we want to make sure it hasn't already been added.  We perform the same process when we add the intersects method to the Rectangle "class".  Obviously if you aren't using JavaScript or your language/library of choice includes such functionality already, you can skip that part of the process.

The intersects method works using this simple logic.  

Given two rectangles, say R1 and R2, they intersect if:

  • The left side of R1 is NOT to the right of the right side of R2
  • The left side of R2 is NOT to the right of the right side of R1
  • The top of R1 is NOT below the bottom of R2
  • The top of R2 is NOT below the bottom of R1

If all of those conditions are true, the two rectangles intersect.  The concept is extremely simple, but making sense of the words isn't always the case.  So here is an image illustrating how it works:

CollisionsGraphic

 

 

Now earlier on I used the words axis-aligned bounding boxes.  What do I mean by axis-aligned?  Well don't worry, it's a lot less scary than it sounds.  It simply means that the two sides of the bounding box are aligned with both the X and Y axis.  Again, Ill use a graphic to illustrate.

AxisAlignedBoundingBoxes

Both the top and bottom bounding boxes are axis aligned, in that the sides of the bounding box are parallel to the X and Y axis.  Using axis aligned bounding boxes make the collision test a great deal faster, but comes at a price.  As you see from the middle image, you cannot simply rotate the bounding box if you rotate the sprite, instead as you can see from the bottom example, you resize the bounding box to encompass the new dimensions of the rotated ( or scaled ) sprite.

How do you do this?  That we will discuss in the next section!

 

Complete Code

A word of warning, much of the code below is a) extending the EaselJS to have bounding box support b) to actually (hackishly I admit) render the bounding box on screen.  Do not let the size deter you, the process is actually quite simple and obviously you don't need to draw the bounding box most of the time.

 

<!DOCTYPE html>

<html>

<head>

    <script src="http://code.createjs.com/easeljs-0.5.0.min.js"></script>

    <script>

        var jetSprite,jetSprite2;

        var stage;

 

        document.addEventListener('DOMContentLoaded', demo,false);

 

        if(createjs.Rectangle.prototype.intersects == null){

            createjs.Rectangle.prototype.intersects = function(rect){

                return (this.x <= rect.x + rect.width &&

                        rect.x <= this.x + this.width &&

                        this.y <= rect.y + rect.height &&

                        rect.y <= this.y + this.height);

            }

        }

 

        if(createjs.Bitmap.prototype.getBoundingRect == null){

            createjs.Bitmap.prototype.getBoundingRect = function(){

                return new createjs.Rectangle(

                        this.x - this.image.width/2,

                        this.y - this.image.height/2,

                        this.image.width,

                        this.image.height);

            }

        }

 

        function demo(){

            stage = new createjs.Stage("theCanvas");

 

            jetSprite = new createjs.Bitmap("jetsprite.small.png");

            jetSprite.regX = 30; // Half image width

            jetSprite.regY = 40; // Half image height

            jetSprite.y = 200;

            jetSprite.x = 100;

 

            stage.addChild(jetSprite);

 

            // Add a Image load handler, as image.width and image.height are meaningless until

            // load is done and DOMContentLoaded doesn't seem to take into account dynamic images

            jetSprite.image.onload = function(e){

                // Draw the bounding rect and create a new Shape with it

                var g = new createjs.Graphics();

                g.setStrokeStyle(1);

                g.beginStroke(createjs.Graphics.getRGB(255,255,255));

                var bb = jetSprite.getBoundingRect();

                g.drawRect(bb.x,bb.y,bb.width,bb.height);

                jetSprite.boundingBox = new createjs.Shape(g);

 

                stage.addChild(jetSprite.boundingBox);

            }

 

            jetSprite2 = new createjs.Bitmap("jetsprite.small.png");

            jetSprite2.regX = 30; // Half image width

            jetSprite2.regY = 40; // Half image height

            jetSprite2.y = 200;

            jetSprite2.x = 300;

 

            jetSprite2.image.onload = function(e){

                var g = new createjs.Graphics();

                g.setStrokeStyle(1);

                g.beginStroke(createjs.Graphics.getRGB(255,255,255));

                var bb = jetSprite2.getBoundingRect();

                g.drawRect(bb.x,bb.y,bb.width,bb.height);

                jetSprite2.boundingBox = new createjs.Shape(g);

 

                stage.addChild(jetSprite2.boundingBox);

            }

 

            stage.addChild(jetSprite2);

 

            //And go...

            stage.update();

 

            // onFrame will be called each "tick". Default is 50ms, or 20FPS

            createjs.Ticker.addListener(onFrame);

        }

 

        function onFrame(elapsedTime) {

            // Convert from milliseconds to fraction of a second

            var delta = elapsedTime /1000;

 

            // Move sprite and bounding box shape to the right

            jetSprite.boundingBox.x++;

            jetSprite.x++;

            if(jetSprite.getBoundingRect().intersects(jetSprite2.getBoundingRect())){

                // If a collision occurs, reset position and start all over again

                jetSprite.x = 100;

                jetSprite.boundingBox.x = 0;

            }

            stage.update();

        }

    </script>

 

</head>

<body>

<canvaswidth=400 height=400 id="theCanvas" style="background-color:black"/>

</body>

</html>

 

See Also 

Part two looks at how you handle rotating a bounding box.

 

Programming

24. November 2012

 

Looking for the perfect gift for the geek who has everything?  Well, Learn Lua for iOS Game Development is coming out just before Christmas , plus it’s on sale for 25 bucks.  ( What’s with pre-release books already being on sale??? ).

 

 

Alright, hundreds of computer texts are released every year, dozens of them about game programming… so why the interest in this particular book?  You may remember a while back I put together  Battle of the Lua Game Engines: Corona vs. Gideros vs. Love vs. Moai and I actually enjoyed working with all three technologies.  Well this book covers using all three SDKs as well as Codea which I hadn’t heard of until this point.

 

 

Obviously the book isn’t going to cover any of those technologies in detail, each one could probably merit it’s own book.  It should however teach you the required bits of Lua and expose you to a little more detail than my comparison.  Lua is a wonderful little language, one you should certainly look into if you haven’t already.  This book may just be the right introduction, it releases on December 17th.

 

Here is the Table of Contents of Learn Lua for iOS Game Development:

Part 1 – Lua

1. Introduction to Lua
2. System Libraries
3. File IO
4. Math
5. Strings
6. Threading
7. Tips and Tricks   

Part 2 - Frameworks

8. CoronaSDK
9. Gideros Studio
10. MoaiSDK
11. Löve
12. Codea

Part 3 - Libraries
13. Libraries
14. 3rd Party Apps   

 

Most APress books end up on Safari Books Online, so expect a review shortly after this book is released.  It does strike me a bit odd that they would limit the title to iOS games, when Corona, Gideros and Moai all support Android as well ( without change in most cases ) and I don’t believe Love supports iOS at all…?  So if you are interested in Android development, don’t let the title put you off.

General , ,

Month List

Popular Comments