Current Phaser Version : 3.55.2
My issue is that when I am calling the addNewPlayer
function from another file client.js
the context of this
is not what I want. I want the same this
as if the function was called from scene-one.js
When I call the addNewPlayer
function from the client.js
file I am receiving this error. (I have also logged this
for each addNewPlayer
call)
I have read online that I can use the call()
function to specify what the value of this
is. However , in scene-one.js
if I use Client.askNewPlayer.call(this)
there doesn’t seem to be any difference.
is there any easy way to change the context of this
, should I even be trying to do that?
Is there a better way that I should be going about this task?
thanks,
Mschilli
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="/socket.io/socket.io.js"></script>
<script src="//cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>
<script src="js/scene-one.js" type="text/javascript"></script>
<script src="js/client.js" type="text/javascript"></script>
<title>Basic multiplayer online game</title>
</head>
<body>
<div id='game'></div>
<script>
const phaserConfig = {
type: Phaser.AUTO,
parent: "game",
width: 1280,
height: 720,
backgroundColor: "#5DACD8",
scene: [SceneOne]
};
const game = new Phaser.Game(phaserConfig);
</script>
</body>
</html>
scene-one.js
class SceneOne extends Phaser.Scene {
constructor () {
super('SceneOne');
}
init() {
}
preload() {
this.load.tilemapTiledJSON('map', 'assets/map/example_map.json');
this.load.image('tileset' , 'assets/map/tilesheet.png')
this.load.image('sprite','assets/sprites/sprite.png');
}
create(data) {
this.playerMap = {};
let map = this.add.tilemap('map');
map.addTilesetImage('tilesheet', 'tileset'); // tilesheet is the key of the tileset in map's JSON file
var layer;
for(var i = 0; i < map.layers.length; i++) {
layer = map.createLayer(i , map.tilesets[0]);
}
layer.setInteractive()
layer.addListener('pointerup' , this.getCoordinates , this)
this.addNewPlayer(0 , 10 , 30);
this.addNewPlayer(1 , 10 , 60);
//Client.askNewPlayer(/*{callbackScope: this}*/).call()
Client.askNewPlayer()
}
update(time, delta) {
}
getCoordinates(pointer){
console.log(`worldX = ${pointer.worldX} , worldY = ${pointer.worldY}`)
}
addNewPlayer = function(id,x,y){
console.log(this)
this.playerMap[id] = this.add.sprite(x,y,'sprite');
console.log('addNewPlayer was called')
};
}
var sceneOne = new SceneOne
client.js
var Client = {};
Client.socket = io.connect();
Client.askNewPlayer = function(){
Client.socket.emit('newplayer');
};
Client.socket.on('allplayers',function(data){
for(var i = 0; i < data.length; i++){
sceneOne.addNewPlayer(data[i].id,data[i].x,data[i].y);
}
});