Search code examples
javascriptcraftyjs

Background displayed over sprites in crafty.js


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);
  });

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;