Can you group polygons in layers using Phaser?

My goal is to animate two polygons: one that remains stationary and another that changes shape while moving. The challenge is to ensure that the stationary polygon always stays on top when overlapping.

This is my proposed solution:

(function() {
  "use strict";

  var SIZE_X = 400;
  var SIZE_Y = 300;
  var CENTER_COLOR = 0xFF33FF;
  var ALT_COLOR = 0xFFFF33;

  var moving_graphics;
  var tick = 0;

  var LayerTest = {
    preload: function() {},
    create: function() {
      game.world.setBounds(-SIZE_X / 2, -SIZE_Y / 2, SIZE_X / 2, SIZE_Y / 2);

      var center_group = game.add.group();
      center_group.z = 1;
      var center_graphics = new Phaser.Graphics(game, 0, 0);
      center_graphics.beginFill(CENTER_COLOR);
      center_graphics.drawPolygon(new Phaser.Polygon([
        new Phaser.Point(-30, -30),
        new Phaser.Point(-30, 30),
        new Phaser.Point(30, 30),
        new Phaser.Point(30, -30)
      ]));
      center_graphics.endFill();
      center_group.add(center_graphics);

      var moving_group = game.add.group();
      moving_group.z = 0;
      moving_graphics = new Phaser.Graphics(game, 0, 0);
      moving_group.add(moving_graphics);
    },
    update: function() {
      moving_graphics.clear();
      moving_graphics.beginFill(ALT_COLOR);
      moving_graphics.drawPolygon(new Phaser.Polygon([
        new Phaser.Point(-SIZE_X / 2 + tick - tick % 40, -10),
        new Phaser.Point(-SIZE_X / 2 + tick - tick % 40, 10),
        new Phaser.Point(20 - SIZE_X / 2 + tick, 10),
        new Phaser.Point(20 - SIZE_X / 2 + tick, -10)
      ]));
      moving_graphics.endFill();
      tick++;
    }
  };

  var game = new Phaser.Game(SIZE_X, SIZE_Y, Phaser.AUTO, '', LayerTest);
})();
<!doctype html>
<html lang="en">

<head>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.4.4/phaser.js"></script>
</head>

<body>
</body>

</html>

I have created a pink square at the center and a yellow rectangle that moves from the left side of the screen towards the center. Despite organizing them into groups with different z-index values, the moving group consistently appears on top. Adjusting z-index directly for each graphics object also does not yield the desired outcome.

The objective is to keep the moving group (yellow rectangle) behind the stationary one.

Answer №1

Always remember to include the moving group first, followed by the center group.

(function() {
  "use strict";

  var SIZE_X = 400;
  var SIZE_Y = 300;
  var CENTER_COLOR = 0xFF33FF;
  var ALT_COLOR = 0xFFFF33;

  var moving_graphics;
  var tick = 0;

  var LayerTest = {
    preload: function() {},
    create: function() {
      game.world.setBounds(-SIZE_X / 2, -SIZE_Y / 2, SIZE_X / 2, SIZE_Y / 2);

      var moving_group = game.add.group();
      moving_graphics = new Phaser.Graphics(game, 0, 0);
      moving_group.add(moving_graphics);
      
      var center_group = game.add.group();
      var center_graphics = new Phaser.Graphics(game, 0, 0);
      center_graphics.beginFill(CENTER_COLOR);
      center_graphics.drawPolygon(new Phaser.Polygon([
        new Phaser.Point(-30, -30),
        new Phaser.Point(-30, 30),
        new Phaser.Point(30, 30),
        new Phaser.Point(30, -30)
      ]));
      center_graphics.endFill();
      center_group.add(center_graphics);

    },
    update: function() {
      moving_graphics.clear();
      moving_graphics.beginFill(ALT_COLOR);
      moving_graphics.drawPolygon(new Phaser.Polygon([
        new Phaser.Point(-SIZE_X / 2 + tick - tick % 40, -10),
        new Phaser.Point(-SIZE_X / 2 + tick - tick % 40, 10),
        new Phaser.Point(20 - SIZE_X / 2 + tick, 10),
        new Phaser.Point(20 - SIZE_X / 2 + tick, -10)
      ]));
      moving_graphics.endFill();
      tick++;
    }
  };

  var game = new Phaser.Game(SIZE_X, SIZE_Y, Phaser.AUTO, '', LayerTest);
})();
<!doctype html>
<html lang="en">

<head>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.4.4/phaser.js"></script>
</head>

<body>
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is Eslint functioning in just one Sublime Text project?

I have encountered an issue where I duplicated the .eslintrc and package.json files for two projects, but only the first project is able to run linting properly. The second project does not show any errors. I am using sublime-linter with the eslint modul ...

Tips for sending an email without using MAILTO in JavaScript or jQuery

Today is a great day for many, but unfortunately not for me. I've been struggling with this issue for over two weeks now and can't seem to find a solution anywhere on the internet. Stack Overflow always comes to my rescue when things get really t ...

Next.js React Hydration Issue - "Anticipated a corresponding <a> within the server HTML <a>"

Currently, I am encountering a hydration error while working on my Next.js project. The specific error message that keeps popping up is: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected serv ...

connecting elements in an object's array to another array within a nested object

Is there a way to iterate through each string value in the imageKeys array and use it to create a URL for each object in the images array within the nested ImageList object, all without changing the original object? const myInitialStateFromParent = { ...

Unable to Pause Video with Javascript

I have a project with a video that plays in a continuous loop. Below is the HTML code for the video tag: <video playsinline autoplay muted loop id="myVid"> <source src="River.mp4" type="video/mp4"> </video> My goal is to make the vi ...

Is there a way for me to retrieve the text response of a fetch request from client-side JavaScript to fastify server?

In my fastify node.js application, I am encountering an issue where I can see the text results of a promise right before it is returned to the browser's JavaScript code. However, once the promise is returned to the browser JS, all I get is an empty st ...

directive does not execute when the <Enter> key is pressed

I recently came across a helpful post on Stack Overflow about creating an Enter keypress directive. After following the instructions, here is my JavaScript code that replicates the functionality: JavaScript var app = angular.module('myApp', [] ...

Encountered an npm installation error: The rollbackFailedOptional issue arose during the npm session with the verb npm-session a0d68 while attempting the command npm install --save

Every time I attempt to install babel, I encounter the following error message: rollbackFailedOptional: verb npm-session a0d68 The version of Node currently installed is 12.16.1 The version of npm being used is 6.13.4 All I want is to get babel up and ...

After receiving the go-ahead from JavaScript, I am planning on integrating PHP into my project. I have come across some recommendations

Looking for assistance with AJAX functionality on a website. Specifically, users should be prompted to confirm a purchase before completing it. If they confirm, the purchase goes through; if they decline, it does not. Originally considered using PHP within ...

Strategies for creating a dynamic progress bar using jQuery and JavaScript

I'm currently working on a project that involves increasing a percentage number while filling up the background color inside it based on the percentage value. The current setup is functional in terms of animating the background, but I need it to dynam ...

Ways to retrieve the value of a concealed element without any activation signal

In my project, I've created a slider that dynamically shows different forms one by one. Each form contains a hidden element with a specific value that I need to retrieve (using its class) every time a new form is displayed. This way, I can use that el ...

Updating a Nested Form to Modify an Object

There is an API that fetches an object with the following structure: { "objectAttributes": [ { "id": "1", "Name": "First", "Comment": "First" }, { "id": "2", "Name": "Second", "Comment": "Second" } ] ...

What is the process for displaying the current bitcoin price on an HTML page using API integration?

I'm looking to develop an application that can display the current Bitcoin price by fetching data from the API at . I want to showcase this information within an h2 element. Any suggestions on how I could achieve this? Thank you in advance. const e ...

Extracting over 100 tweets from the Twitter API with the help of Node.js

I am facing a challenge while trying to fetch over 100 tweets from Twitter in nodejs as I continuously receive an empty array. Here is the approach I have attempted: const MAX_TWEETS = 200; const TWEETS_PER_REQUEST = 100; async function retrieveTweets(T, ...

Challenges with compiling Next.js with Tailwindcss and Sass

I recently created a simple template using Tailwind for my Next.js project. Normally, I rely on Tailwind's @layer components to incorporate custom CSS styles. However, this time I wanted to experiment with Sass, so I converted my globals.css file to ...

Searching for a JavaScript tool that offers syntax highlighting capabilities

I have come across some excellent RTE HTML text editors such as jsredaktor, TinyMCE, and FCK Editor, but I am in search of an HTML/JavaScript component that functions similarly to a TEXTAREA with built-in code syntax highlighting. ...

What is the process for obtaining authorization to access user information?

I am facing a perplexing issue with my app settings. Despite setting everything up correctly, I am unable to authenticate my account on my website using the Javascript SDK. Whenever I try to console.log(me), I only receive public information. Upon furthe ...

Creating unique sizes for each quad in Three.js using InstancedBufferGeometry and ShaderMaterial

I'm working on creating a visually dynamic scene filled with points of varying widths and heights. The challenge I'm facing is figuring out how to manipulate the vertices in the vertex shader to achieve customized sizes for each point. Here' ...

Ways to establish a default search outcome in a search box

Looking to create a search bar with JavaScript and JSON to display default search results for visitors. Currently, the search bar only shows results after text is removed. How can I show predefined search results when the page is loaded? const search = ...

Updating Sailsjs Localization Settings

After working with Sails.js for a while, I am interested in finding out if it is possible to manually adjust the localization from the controllers based on the URL. For example, accessing http://example.com/en would display the English version, while http ...