Question

In a small crafty.js project, I used a sprite as the background image but it renders over other sprites. How do I fix this? The code for the main scene is given below:

    Crafty.scene('game', function () {
    Crafty.background('bg');
    Crafty.e("Background, DOM, 2D, bg")
          .attr({ x: 0, y: 0});
      drawStage();
    points = 0;
    updatePoints();

    var speed = 1; // Number of frames per second

    // Game objects

    var appleEvent = Crafty.bind('EnterFrame', function () {
      if (randomInt(0, 60) === 0) {
        Crafty.e('Apple')
              .attr({
                x: randomInt(1, 19) * cell,
                y: randomInt(1, 16) * cell
              });
      }
    });
  }, function () {
    Crafty.unbind('EnterFrame', appleEvent);
  });
Was it helpful?

Solution

How about specifically setting the z-index of entities?

var img_w = 1024;
var img_h = 768;
var bg = Crafty.e("2D, DOM, Image").attr({ w: img_w, h: img_h });
bg.z = 0;

Later in the code:

var player = Crafty.e();
player.z = 1;

OTHER TIPS

It's not clear where 'bg' is coming from, but I had a similar problem with a background image overwriting the foreground content. This forum post had the answer: https://groups.google.com/forum/?fromgroups=#!topic/craftyjs/pdxcYi8T_j8

Basically, instead of assigning an entity to the background, I assigned an image URL path to a local file:

Crafty.background("url('path/to/image.png')");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top