Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created March 6, 2014 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmcw/9389683 to your computer and use it in GitHub Desktop.
Save tmcw/9389683 to your computer and use it in GitHub Desktop.

Next Challenge: Making things look awesome

Let's draw some sprites: these are the images that show when you see characters and other stuff in levels. They'll give this more personality than rectangles.

First: sprites are images. Let's draw our first sprite: open up http://pixelartor.com/ and create a new 64x64 image. Draw what you want, like a person or an obstacle or something else.

Save your image to the same directory as your game, and name it something you'll remember, like player.png

Next:

First we need a JavaScript function that will load an image. This will do the same thing as an <img> tag in HTML, except it'll make the image available for us to use in JS:

function makeImage(url) {
    var img = new Image();
    img.src = url;
    return img;
}

(copy and paste that at the very end of your game.js file)

Next, your Person needs to know how to draw an image. Right now it'll have a part like

  this.draw = function(ctx) {
        ctx.fillStyle = settings.color;
        ctx.fillRect(this.center.x, this.center.y, this.size.x, this.size.y);
  };

Let's expand this:

  this.draw = function(ctx) {
    if (this.image && this.image.complete) {
        ctx.drawImage(this.image, this.center.x, this.center.y, this.size.x, this.size.y);
    } else {
        ctx.fillStyle = settings.color;
        ctx.fillRect(this.center.x, this.center.y, this.size.x, this.size.y);
    }
  };

Read through this: if the person has an image and that image has loaded, draw it! Otherwise draw a rectangle (a Rect) of a certain color.

Okay, now let's define something with an image. A player might be like:

this.c.entities.create(Person, { center: { x:0, y:332 }, size: { x: 500, y: 2 }, color: '#000' });

At the end, we're saying that the player should have color: '#000'. Let's say it has an image instead:

this.c.entities.create(Person, { center: { x:0, y:332 }, size: { x: 500, y: 2 }, image: makeImage('player.png') });

Now this player will have an image!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment