Phaser IO: Altering text dynamically with callback functions

I am currently in the process of developing a game using Phaser IO and SignalR along with jQuery. The server provides me with a list of players, each containing an ID and Name. I then create a text field for each player which I plan to later manipulate based on the number of votes that specific player has received. However, I am unsure how to reference the dynamically created text objects.

I am open to any new ideas or suggestions.

var game = new Phaser.Game($window.innerWidth, $window.innerHeight, Phaser.Auto, 'gameCanvas');

        var dayState = {
            preload: function () {
                // Preloaded stuff
            },
            create: function () {
                var world = game.world;

                // Get list of players alive in the game from server
                var players = // Server call to retrieve list of players

                // Add player 
                for (var i = 0; i < players.length; i++) {
                    var currentPlayer = players[i];

                // Display player name
                    game.add.text(world.width - 225, y, currentPlayer.Name);

              // I WANT TO UPDATE THIS UPON CALLBACK
                game.add.text(world.width - 175, y, 0)

                    // Vote button
                        game.add.button(world.width - 50, y + 2, //preloaded texture for button, voteFunction, currentPlayer.Id , 2, 1, 0);                    
                }
            }
        };
        game.state.add('DayState', dayState);
        game.state.start('DayState');

        function voteFunction() {
            // Posts vote to server
        };

function voteReturnedFromServer(amount){
// Server calls this function (SignalR)
// This is where I want to update text element created above with data from SignalR
// Update text with callback data "amount"
};

Answer №1

To simplify the process, consider creating a variable at the same level as game and assign it to the text you want to incorporate into the game.

var customText;
// ...


customText = game.add.text('world.width - 175, y, 0);

Next, update the text if customText is defined.

customText.text = 'data received from the server'

Answer №2

Issue I encountered involved locating the text once it was created. To solve this problem, I decided to create an array outside of the game states and store the texts in that array. Then, whenever I needed to make changes to the text, I would search for it within the array using grep (as I was already utilizing jQuery).

var game = new Phaser.Game($window.innerWidth, $window.innerHeight, Phaser.Auto, 'gameCanvas');

// Array where texts will be stored
var voteTexts = [];

        var dayState = {
            preload: function () {
                // Preloaded content
            },
            create: function () {
                var world = game.world;

                // Retrieving list of players currently alive in the game
                var players = // Call to Server, retrieves list of players

                // Adding player information 
                for (var i = 0; i < players.length; i++) {
                    var currentPlayer = players[i];

                    // Display player name
                    game.add.text(world.width - 225, y, currentPlayer.Name);

                    // Will update this upon callback
                    var vote = game.add.text(world.width - 175, y, 0);
                    vote.id = currentPlayer.Id;
                    voteTexts.push(vote);

                    // Vote button
                        game.add.button(world.width - 50, y + 2, //preloaded texture for button, voteFunction, currentPlayer.Id , 2, 1, 0);                    
                }
            }
        };
        game.state.add('DayState', dayState);
        game.state.start('DayState');

        function voteFunction() {
            // Sending vote data to server
        };

function voteReturnedFromServer(amount){
                var textToUpdate = $.grep(voteTexts, function (e) {
                    return e.id === votes.TargetId;
                });
                // As there's only one result expected, selecting [0]
                textToUpdate[0].text = votes.Count;
};

Answer №3

To update text content, utilize the built-in method setText()

text.setText(amount);

Visit this link for more information

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

Increase the date by one day in the minimum date field using the date picker

I've been struggling with adding one day to the minDate in my code. Despite trying multiple solutions from Stackoverflow, none of them have worked successfully. Here is the code I currently have: $('#cal_mulamhn').datepicker({ minDate ...

Are there any advantages to using Promises and Async/Await together?

Currently, I am in the process of working through my express server controllers and transitioning from using promises to async/await. However, I find myself questioning whether this change is truly beneficial or just done for the sake of it. If the code is ...

`Problem encountered in establishing a database table through jQuery ajax`

I am completely new to utilizing jQuery and ajax. Currently, I am experimenting with creating a table on my local MySQL server using a JavaScript file that sends SQL statements to a .php file for execution. Here is the code in the .js file: function exec ...

Transform an array into JSON format in Javascript using the same key

Within my PHP file, I have a list of file names from a specific folder that I need to convert into JSON format. The array containing the file names looks like this: Array ( [0] => teste3.pdf [1] => teste2.pdf [2] => teste.pdf ...

Transferring and bringing in components in React without ES6

I'm currently working on a react project and I want to export my ShoppingList class. However, I prefer not to use ES6 as I find it confusing. Here is the code for the ShoppingList class: class ShoppingList extends React.Component { render() { ...

React and Express are incompatible due to the error message "TypeError: undefined is not a function

I am attempting to display the data from this array on my website using react and express: [{"LocationName":"LIBERTY DOGS","Address":"105 Greenwood Ave N, Seattle WA","Available":"Y"},{"LocationName":"FREEDOM DOGS","Address":"105 Greenwood Ave N, Seattle ...

Using jQuery Validator Plug In to manually trigger validation from a custom function

I'm encountering an issue with validating a lengthy form that is loaded via AJAX after the document has finished loading. When using the standard validation syntax, the validator searches for my form in the document before it actually exists, resultin ...

Tips for modifying an axios instance during response interception

Is there a way to automatically update an axios instance with the latest token received in a response, without making a second request? The new token can be included in any response after any request, and I want to make sure that the last received token ...

What is the best method for retrieving keys from a key/value JSON object?

I have a JSON object that I need to process in order to extract certain elements. The issue is that the data structure of this particular section is different from what I'm used to working with. Typically, I would iterate through the elements like so: ...

A difference in the way content is displayed on Firefox compared to Chrome, Edge, and Safari

Recently, I encountered an issue with a tool I had developed for generating printable images for Cross-Stitch work. The tool was originally designed to work on Firefox but is now only functioning properly on that browser. The problem at hand is whether th ...

Mastering EmberJS 2.7: The Definitive Guide to Binding the 'disabled' Attribute for Buttons

Here is an official guide explaining how to bind a boolean property to the disabled attribute of an HTML element. However, it references a controller in the process. I have a button that, when clicked, transitions the route (it must be a button and not a ...

Generating all combinations of multi-dimensional objects within an array with variable length, also known as the Cartesian product

While there are numerous solutions available on StackOverflow and a helpful article on RosettaCode demonstrating how to find the Cartesian product for simple arrays, I have encountered a unique challenge for which I can't find a suitable solution. My ...

Having trouble entering text into a textarea field labeled with "area-label" and receiving an error stating that the element

Apologies for the vague title, can someone suggest a better one? Here are the details of the issue I am encountering: Website: https://www.desmos.com/calculator/lzidy3m70r Steps: Click on the + button on the top left Select images and upload an image U ...

Create a new variable within a function using an Angular factory

I am working with an Angular factory that generates a function including a variable to select an array for a dropdown. While I have successfully set the variable from a user selection in a controller, I am facing difficulties getting this variable into the ...

"Personalized labels for enhancing user insights on Microsoft Clarity

Is there a way to add a custom tag on MS Clarity specifically for tracking a user clicking the cancel button during a particular event? I am working on an Angular project and need guidance on how to achieve this. I attempted using script tags within the H ...

The issue of Rails time lagging by a day persists upon deployment on my server

When a user clicks on a day in my calendar, I pass a JavaScript time variable to my Rails controller using Ajax. Everything works perfectly when I test it locally, but once deployed on the server, the date appears to be one day behind the actual day click ...

Tips on customizing the appearance of React rendering components

<div> <h3>{this.props.product.name}</h3> <h3>{this.props.product.code}</h3> {this.renderColors()} <article> <div da ...

Error: The function is invalid for callback at end (node_modules/middy/src/middy.js:152:16)

I seem to be having some trouble with my test when using middy. Removing middy makes the test pass successfully, but with middy, I encounter the error "TypeError: callback is not a function at terminate (C:\cico\node_modules\middy\src&b ...

Tips on sending template variables to JavaScript

Greetings, I am currently facing an issue with passing a template variable to javascript in order to create a chart. Unfortunately, Django treats all js files as static files which means that dynamic template variables are not accessible within javascript. ...

Issue with Snackbar slide transition not functioning properly in mui 5

Transitioning from material-ui 4 to mui 5 has presented me with a challenge. Whenever I try to display my snackbar, an error pops up in the console. After some investigation, I realized that the issue lies within the Slide component that I'm using as ...