Jump to content

How do I read an image from an atlas?


kray
 Share

Recommended Posts

I need to select an image at random from my atlas. 
I used Texture Packer to make the atlas. But I don't understand how to get an image from the atlas.

This is my code:

 

preload: function() {        this.load.spritesheet('dude', 'asset/dude.png', 32, 48);        this.load.atlas('alphabets','asset/letters.png','asset/letters.json');        this.load.image('ground','asset/platform.png');    },

I found this method to use atlases, using frameName:

 

var x = Math.floor(Math.random()*10)%this.world.width;var letter = this.add.sprite(x, 0, 'alphabets');//letter.frameName = img;letter.frameName = "a.png";//  Let gravity do its thingletter.body.gravity.y = 200;

However, my console says 

 

Cannot read property 'gravity' of null.

Why is letter null? Am i reading it wrong? 

Link to comment
Share on other sites

Property "gravity" is part of the body, not the sprite. So it is actually the body that is null, not the sprite "letter". To add the body to the sprite, use:

 

game.physics.arcade.enable(letter);

 

After that you can set the properties of the body.

 

I don't know about arcade physics, as I normally use p2, but you might have to enable the physics system before the above command will work.

 

EDIT: Also, you can use the one-liner "this.add.sprite(x, 0, 'alphabet', a.png);" instead of setting the frameName in the next line, but that's up to you.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...