});
this.load.image('mapIMG2', FrameMap);
this.load.tilemapTiledJSON('mapJSON2',gameplay_menu);
}
exitApp() {
if (this.canExit && this.canExit == true) {
this.SwitchWithAnims('WelcomeMenu-Great_job', {
effects: 'burst',
sound: 'welcome_speech'
});
}
}
destroy() {
this.sound.stopAll();
socket.disconnect();
}
shutdown() {
socket.disconnect();
}
create() {
this.velocityCurrentLeft = 0;
this.velocityCurrentRight = 0;
this.events.on('shutdown', this.shutdown, this);
this.events.on('predestroy', this.destroy, this);
if (this.map && this.mapJSON) {
this.all_movers = [];
const menu = this.make.tilemap({ key: 'mapJSON2' });
const tileset2 = menu.addTilesetImage('FrameMap', 'mapIMG2');
//gameplay menu
const menuBG = menu.createLayer('bg_layer', tileset2);
const menuFront = menu.createLayer('front_layer', tileset2);
const bullets = menu.getObjectLayer('bullets');
this.winnerList = menu.getObjectLayer('WinnerList');
menuBG.setDepth(999);
menuFront.setDepth(1000);
menuBG.setScrollFactor(0);
menuFront.setScrollFactor(0);
this.rateForFullWidth = (menuFront.width / this.sys.game.config.width);
menuFront.setScale(1 / this.rateForFullWidth);
menuBG.setScale(1 / this.rateForFullWidth);
this.ammoCountText = this.add.text(bullets.objects[0].x * (1 / this.rateForFullWidth) + 8, bullets.objects[0].y * (1 / this.rateForFullWidth), 0, {
color: 'white',
fontWeight: 700,
fontFamily: 'press_start',
fontSize: this.sys.game.config.height / 40
});
this.ammoCountText.setOrigin(0.5, (0.5 + 0.25) / 2);
this.ammoCountText.setDepth(1000);
this.ammoCountText.setScrollFactor(0);
if (socket) {
socket.on("take_list_info", (data) => {
// Mevcut kişileri güncellemek için kullanılan bir geçici dizi oluşturun
let updatedListDetails = [...this.tableListDetails];
// Gelen verileri işleme
data.forEach(person => {
// Mevcut kişiyi bulmak için diziyi kontrol et
const existingIndex = updatedListDetails.findIndex(item => item.myName === person.who);
if (existingIndex === -1) {
// Kişi mevcut değilse, dizinin sonuna ekleyin
updatedListDetails.push({
distance: Math.FloorTo(person.data),
finisPercent: Math.FloorTo(person.xp),
myName: person.who
});
} else {
// Kişi mevcutsa, verileri güncelleyin
updatedListDetails[existingIndex] = {
distance: Math.FloorTo(person.data),
finisPercent: Math.FloorTo(person.xp),
myName: person.who
};
}
});
// Güncellenmiş listeyi `this.tableListDetails` ile güncelle
this.tableListDetails = updatedListDetails;
// `datas` dizisini oluştur
let datas = this.tableListDetails.map((perData, i) => ({
que: i,
text: perData.myName
}));
// Paneli güncelle
if(this.Panel1){
this.Panel1.delete();
this.Panel1.update(datas);
}
});
}
/* const modal = new InputElem(this, this.sys.game.config.width / 2, this.sys.game.config.height / 2, {
color1: Display.Color.GetColor(1 * 255, 1 * 255, 0.5 * 255),
color2: 'black',
textColor: 'white',
alpha: 0.5,
}, 1, 100, 100)
*/
const html = `
<div style="display: block; background-color: #212529; padding: 0; position: absolute; width: 25%; right: 0; overflow: auto; height: 100%;" class="nes-field is-inline">
<div style="position: sticky; top: 0; left: 0;">
<input type="text" id="message_input" class="nes-input is-dark is-small" placeholder="type...">
<button id="msg_sender" class="nes-btn is-error is-small">send</button>
</div>
<div class="nes-container with-title is-centered is-small" style="position: relative; left: 0; bottom: 0; width: 100%;" id="allMessages"></div>
</div>
`;
// DOM elementini ekleme
const element = this.add.dom(600, 300).createFromHTML(html).setScrollFactor(0);
element.setOrigin(0.5, 0.5); // Merkezde hizalama
// Z-indeksini ayarlama
element.node.style.zIndex = 10;
// Olay dinleyicileri eklemek
const msg_sender = document.getElementById('msg_sender');
const message_input = document.getElementById('message_input');
msg_sender.addEventListener('click', () => {
const new_msg = message_input.value;
if (socket) {
socket.emit('receive_form_frontend', {
person: localStorage.getItem('my_name'),
message: new_msg
});
}
message_input.value = '';
});
const messageBox = document.getElementById("allMessages");
if (socket) {
socket.on("takeAllMessage", (datas) => {
let perMessage = document.createElement("div");
let name = document.createElement("div");
let message = document.createElement("div");
let messageText = document.createElement('p');
name.className = "title";
message.className = "nes-container with-title is-centered";
perMessage.id = "perMessage";
name.innerHTML = datas.person;
messageText.innerHTML = datas.message;
messageText.className = 'nes-text is-disabled';
messageText.style.fontSize = window.innerHeight / 30;
message.appendChild(messageText);
perMessage.appendChild(name);
perMessage.appendChild(message);
messageBox.appendChild(perMessage);
document.querySelector("#perMessage:last-child").scrollIntoView({ behavior: "smooth" });
});
}
this.input.setDefaultCursor('none');
this.customCursor = this.add.image(0, 0, 'pointer').setOrigin(0.5, 0.5).setDepth(200).setScrollFactor(0);
this.input.on('pointermove', (pointer) => {
this.customCursor.setPosition(pointer.x, pointer.y);
});
window.addEventListener('dblclick', () => {
if (document.getElementById('infos_table').style.display !== 'none') {
document.getElementById('infos_table').style.display = 'none';
} else {
document.getElementById('infos_table').style.display = 'inherit';
}
});
this.cameras.main.on('camerapanstart', () => {
this.canExit = false;
})
this.cameras.main.on('camerapancomplete', () => {
this.canExit = true;
})
//const book = new StoryBook(this,"Bu bir başlık", "asdsadsadasdsdsadasdsadsadsadsadsadsadsadasdasadsa");
this.maskGraphics = this.make.graphics();
this.hurtSoundsForPlay = [];
const hurtSounds = [
'hurt2',
'hurt3',
'hurt4',
];
hurtSounds.forEach(hurterSound => {
this.hurtSoundsForPlay.push(this.sound.add(hurterSound));
})
this.tableListDetails = [];
/*
if (isSocketWorks && isSocketWorks == true && socket) {
socket.on("take_list_info", (data) => {
datas = "";
data.forEach(person => {
const existingIndex = this.tableListDetails.findIndex(item => item.myName === person.who);
if (existingIndex === -1) {
this.tableListDetails.push({ distance: person.data, finisPercent: person.xp, myName: person.who });
} else {
// Eğer kişi zaten varsa, mevcut kaydın verilerini güncelle
this.tableListDetails[existingIndex] = { distance: Math.FloorTo(person.data), finisPercent: Math.FloorTo(person.xp), myName: person.who };
}
});
const table_list = document.getElementById("winnerListerTable");
this.tableListDetails.forEach((perData, i) => {
const tr = `<tr id="person${i + 1}">
<td scope="row" id="person_name${i + 1}">${perData.myName}</td>
<td id="person_percentage${i + 1}">${perData.finisPercent}</td>
<td id="person_distance${i + 1}">${perData.distance}</td>
</tr>`;
datas += tr;
});
table_list.innerHTML = datas;
});
if (socket) {
socket.emit("getAllWithoutMe", { Id: myId });
}
}
*/
this.matter.set30Hz();
this.polices = [];
this.isWin = false;
keyList.clear();
this.policeSpeech = this.sound.add('police_speech');
this.IsGunWith = false;
if (localStorage.getItem("weapon_number")) {
this.defaultGunNumber = Number(localStorage.getItem("weapon_number")) ?? 1;
} else {
this.defaultGunNumber = 1;
}
OtherCharacterDetails.forEach(enemy => {
if (enemy && enemy.key && enemy.start !== undefined && enemy.end !== undefined && enemy.onCompleteDestroy !== undefined) {
this.anims.create({
key: enemy.key + '_anims',
frames: this.anims.generateFrameNumbers(enemy.key + '_anims', {
start: enemy.start,
end: enemy.end
}),
frameRate: 10,
repeat: (enemy.onCompleteDestroy == true) ? 0 : -1,
hideOnComplete: enemy.onCompleteDestroy,
})
}
})
AzurWithGun.forEach(GunType => {
GunType.forEach(manWithGun => {
this.anims.create({
key: manWithGun.key,
frames: this.anims.generateFrameNumbers(manWithGun.key),
frameRate: 8,
repeat: -1
});
});
});
this.FirstRobots.forEach(robot => {
this.anims.create({
key: robot.key + "_anim",
frames: this.anims.generateFrameNumbers(robot.key),
frameRate: 3,
repeat: 0,
hideOnComplete: false,
});
});
this.ThirdRobots.forEach(robot => {
this.anims.create({
key: robot.key + "_anim",
frames: this.anims.generateFrameNumbers(robot.key),
frameRate: 3,
repeat: -1,
});
});
this.SecondRobots.forEach(robot => {
this.anims.create({
key: robot.key + "_anim",
frames: this.anims.generateFrameNumbers(robot.key),
frameRate: 3,
repeat: -1,
});
});
this.anims.create({
key: 'mover',
frames: this.anims.generateFrameNumbers('mover'),
frameRate: 3,
repeat: -1
})
this.robots = [];
this.bombs = [];
this.escaped = false;
const bgZoom = 3.5;
this.isDesktop = this.sys.game.device.os.desktop;
this.bg1 = this.add.tileSprite(0, 0, this.sys.game.config.width, this.sys.game.config.height, "bg1");
this.bg1.setOrigin(0.5, 0.5);
this.bg1.height = this.sys.game.config.height * 3;
this.bg1.setScale(bgZoom, bgZoom).setScrollFactor(0);
this.bg2 = this.add.tileSprite(0, 0, this.sys.game.config.width, this.sys.game.config.height, "bg2");
this.bg2.setOrigin(0.5, 0.5);
this.bg2.height = this.sys.game.config.height * 3;
this.bg2.setScale(bgZoom, bgZoom).setScrollFactor(0.0385);
this.bg3 = this.add.tileSprite(0, 0, this.sys.game.config.width, this.sys.game.config.height, "bg3");
this.bg3.setOrigin(0.5, 0.5);
this.bg3.height = this.sys.game.config.height * 3;
this.bg3.setScale(bgZoom, bgZoom).setScrollFactor(0.0675);
this.bg4 = this.add.tileSprite(0, 0, this.sys.game.config.width, this.sys.game.config.height, "bg4");
this.bg4.setOrigin(0.5, 0.5);
this.bg4.height = this.sys.game.config.height * 3;
this.bg4.setScale(bgZoom, bgZoom).setScrollFactor(0.125);
this.bg5 = this.add.tileSprite(0, 0, this.sys.game.config.width, this.sys.game.config.height, "bg5");
this.bg5.setOrigin(0.5, 0.5);
this.bg5.height = this.sys.game.config.height * 3;
this.bg5.setScale(bgZoom + 0.5, bgZoom + 0.5).setScrollFactor(0.25);
/*
const controllerUI = this.make.tilemap({key: 'ControllerJSON'});
const controllerTiles = controllerUI.addTilesetImage("FrameMap","ControllerIMG");
const controllerFG = controllerUI.createLayer("foreground",controllerTiles);
const controllerBG = controllerUI.createLayer("background",controllerTiles);
const heightScale = this.sys.game.config.height / controllerFG.displayHeight;
const widthScale = this.sys.game.config.width / controllerFG.displayWidth;
const rateFGK = heightScale < widthScale ? heightScale : widthScale;
controllerFG.setScale(1 / rateFGK);
controllerFG.setScrollFactor(0);
controllerBG.setScale(1 / rateFGK);
controllerBG.setScrollFactor(0);
// Katmanı hesaplanan oranla ölçekle
*/
// Tilemap oluşturma
this.my_map = this.make.tilemap({ key: 'map' });
this.tiles = this.my_map.addTilesetImage('map', 'map');
// Katmanları oluşturma
this.layerBG = this.my_map.createLayer('bg_layer', this.tiles);
this.layer = this.my_map.createLayer('Tile Layer 1', this.tiles);
this.ladders = this.my_map.createLayer('ladders', this.tiles);
this.deathLine = this.my_map.findObject("important_coords", obj => obj.name === "death_line");
this.startCoord = this.my_map.findObject("important_coords", obj => obj.name === "start");
this.FinishCoord = this.my_map.findObject("important_coords", obj => obj.name === "end");
this.keysCoord = this.my_map.findObject("mission", obj => obj.name == "keys");
this.timerLimit = this.my_map.findObject("mission", obj => obj.name == "timer");
this.robotCoords = this.my_map.getObjectLayer("enemies");
this.workers = [];
this.workerCoords = this.my_map.getObjectLayer('workers')
this.policeCoords = this.my_map.getObjectLayer('polices');
this.battleRobotCoords = this.my_map.getObjectLayer('Battle_Mecha_Robots');
this.textList = [];
this.textsLayers = this.my_map.getObjectLayer('texts');
if (this.textsLayers) {
this.textsLayers.objects.forEach(textElem => {
let glowing = false;
let type = 1;
let icon = null;
const properties = textElem.properties;
properties.forEach((property, key) => {
if (property.name === 'glowing') {
glowing = property.value;
} else if (property.name === 'type') {
type = property.value;
} else if (property.name === 'icon') {
icon = property.value;
}
})
this.textList.push(new SpecialText(this, textElem.text.text, type, {
x: textElem.x,
y: textElem.y
},
{
x: textElem.text.pixelSize,
y: textElem.text.pixelSize
},
10, glowing,
Display.Color.HexStringToColor(textElem.text.color).color
));
if (icon) {
this.add.sprite(textElem.x, textElem.y, icon).setDepth(100).setOrigin(-0.5, 1.5);
}
})
}
this.movers = this.my_map.getObjectLayer('movers');
if (this.movers) {
if (this.movers.length > 0) {
this.movers.forEach(mover => {
const my_mover = this.matter.add.sprite(mover.x, mover.y, 'mover');
my_mover.isStatic = true;
my_mover.setDisplaySize(1, 1);
my_mover.anims.play('mover');
my_mover.setVisible(false);
});
} else {
const my_mover = this.matter.add.sprite(this.movers.x, this.movers.y, 'mover');
my_mover.isStatic = true;
my_mover.anims.play('mover', true);
my_mover.setDisplaySize(1, 1);
my_mover.setVisible(false);
}
}
this.low_fps_timer = 0;
this.time.addEvent({
callback: () => {
if (this.sys.game.loop.delta < 20) {
localStorage.setItem('Features', 'low');
this.low_fps_timer -= 1;
} else {
this.low_fps_timer += 1;
localStorage.setItem('Features', 'high');
}
},
loop: true,
delay: 250,
args: []
})
this.time.addEvent({
callback: () => {
if (this.low_fps_timer > 2 && localStorage.getItem('Features') !== 'low') {
this.scene.restart();
}
},
loop: true,
args: [],
delay: 750,
})
this.real_mover = [];
if (this.movers && this.movers.objects) {
this.movers.objects.forEach(mover1 => {
// mover1.polyline'i bir Phaser.Curves.Path nesnesine dönüştür
const points = mover1.polyline.map((coord) => new Math.Vector2(coord.x, coord.y));
const path = new Curves.Path(points[0].x + mover1.x, points[0].y + mover1.y);
points.forEach(point => path.lineTo(point.x + mover1.x, point.y + mover1.y));
// my_mover sprite'ını oluştur ve animasyonunu oynat
const my_mover = this.matter.add.sprite(mover1.x, mover1.y, 'mover');
my_mover.setData('currentCoordIndex', 0);
my_mover.setData('points', { points: mover1.polyline });
// my_mover.anims.play('mover');
// follower'ı oluştur ve yolu takip etmeye başla
const follower = this.add.follower(path, mover1.x, mover1.y, 'mover').setVisible(false);
// Follower nesnesini oluştur
// Follower nesnesine sprite'ı ekleyerek dikdörtgen fizik bedenini atayın
// Follower nesnesine sprite'ı ekleyin
const followerSprite = this.matter.add.sprite(mover1.x, mover1.y, 'mover');
my_mover.setFixedRotation();
follower.lifespan = -1;
my_mover.setVisible(false);
my_mover.setDisplaySize(0.5, 0.5);
follower.startFollow({
targets: my_mover,
duration: mover1.properties[0].value,
rotateToPath: true,
repeat: -1,
delay: 1000,
yoyo: true,
ease: 'Linear',
onUpdate: () => {
follower.setData('position_data', {
before: {
x: followerSprite.x,
y: followerSprite.y
},
now: {
x: follower.x,
y: follower.y
},
})
}
});
this.real_mover.push(followerSprite)
this.all_movers.push(follower);
});
}
const dynamite = this.my_map.getObjectLayer("dangerous");
if (this.keysCoord && this.FinishCoord) {
if (isSocketWorks && isSocketWorks == true && socket) {
socket.emit("mapSet", { maxDistance: Math.Distance.Between(this.keysCoord.x, this.keysCoord.y, this.FinishCoord.x, this.FinishCoord.y) });
}
this.cameras.main.pan(this.FinishCoord.x, this.FinishCoord.y, 2500, 'Power2');
}
if (dynamite) {
dynamite.objects.forEach(obj => {
let x = obj.x;
let y = obj.y;
let durance = 0;
let perDamage = 0;
let key = "";
Object.values(obj.properties).forEach(property => {
if (property.name == "perDamage") {
perDamage = property.value;
}
if (property.name == "key") {
key = property.value;
}
if (property.name == "durance") {
durance = property.value;
}
});
let bombOne = this.matter.add.sprite(x, y, key);
bombOne.setData("durance", durance);
bombOne.setData("perDamage", perDamage);
this.bombs.push(bombOne);
});
}
this.bullets = [];
this.battle_mechas = [];
if (this.battleRobotCoords) {
this.battleRobotCoords.objects.forEach(obj => {
this.battle_mechas.push(new BattleMechaRobots(
this,
Number(obj.properties[6].value),
obj.x,
obj.y,
obj.width,
obj.height,
obj.properties.map(props => {
if (props.name === "health") {
return {
health: props.value
};
} else if (props.name === "name") {
return {
name: props.value
};
} else if (props.name === "type") {
return {
type: props.value
};
} else if (props.name.includes("Attack")) {
const frames = {};
frames[props.name] = props.value;
return {
[props.name]: frames[props.name],
};
}
})
));
});
}
if (this.policeCoords) {
this.policeCoords.objects.forEach(obj => {
this.polices.push(new PoliceCharacter(
this,
Number(obj.properties[6].value),
obj.x,
obj.y,
obj.width,
obj.height,
obj.properties.map(props => {
if (props.name === "health") {
return {
health: props.value
};
} else if (props.name === "name") {
return {
name: props.value
};
} else if (props.name === "type") {
return {
type: props.value
};
} else if (props.name.includes("Attack")) {
const frames = {};
frames[props.name] = props.value;
return {
[props.name]: frames[props.name],
};
}
})
));
});
}
if (this.robotCoords) {
this.robotCoords.objects.forEach(obj => {
this.robots.push(new Robot(
this,
obj.type,
obj.x,
obj.y,
obj.width,
obj.height,
obj.properties.map(props => {
if (props.name === "health") {
return {
health: props.value
};
} else if (props.name === "name") {
return {
name: props.value
};
} else if (props.name === "type") {
return {
type: props.value
};
} else if (props.name.includes("Attack")) {
const frames = {};
frames[props.name] = props.value;
return {
[props.name]: frames[props.name],
};
}
})
));
});
if (this.workerCoords) {
this.workerCoords.objects.forEach(obj => {
this.workers.push(new WorkerEnemies(
this,
Number(obj.properties[6].value),
obj.x,
obj.y,
obj.width,
obj.height,
obj.properties.map(props => {
if (props.name === "health") {
return {
health: props.value
};
} else if (props.name === "name") {
return {
name: props.value
};
} else if (props.name === "type") {
return {
type: props.value
};
} else if (props.name.includes("Attack")) {
const frames = {};
frames[props.name] = props.value;
return {
[props.name]: frames[props.name],
};
}
})
));
});
}
/*
this.robotCoords.forEach(robot=>{
this.robots.push(new Robot(this,robot.type,robot.x,robot.y,robot.width,robot.height));
});
*/
}
// this.timerText = this.add.text(this.sys.game.config.width / 2,0,this.timerLimit.text.text);
// this.timerText.setOrigin(0.5,0).setDepth(105);
this.timer = this.add.text(this.sys.game.config.width / 2, 20, '___', {
color: 'white',
fontWeight: 700,
fontFamily: 'press_start',
fontSize: this.sys.game.config.height / 50
});
let ctx = this.add.graphics();
ctx.fillStyle({
color: 0x000000,
alpha: 1
});
ctx.setAlpha(0.4);
const padding = 0;
let roundRect = ctx.fillRoundedRect(this.timer.x - this.timer.displayWidth + padding, this.timer.y - this.timer.displayHeight / 2 + padding, this.timer.displayWidth * 2 - padding, this.timer.displayHeight * 2 - padding * 2, 15);
roundRect.setDepth(198);
roundRect.setScrollFactor(0);
this.timer.setOrigin(0.5, 0);
this.timer.setDepth(200);
this.timer.setScrollFactor(0);
if (isSocketWorks && isSocketWorks == true && socket) {
socket.on("timeChange", (data) => {
if (data.timer <= 1) {
if (this.isWin && this.isWin == true) {
this.SwitchWithAnims('WelcomeMenu-Great_job', {
sound: 'time_is_up'
});
} else {
this.SwitchWithAnims('WelcomeMenu-Great_job',
{
sound: 'time_is_up'
});
}
}
let currentTime = data.timer;
let minute = Math.FloorTo(currentTime / 60);
let second = currentTime % 60;
this.timer.setText(((minute < 0) ? "0" : minute) + ":" + ((second < 10) ? "0" + second : second));
// document.getElementById('game_timer').innerText = ((minute < 0) ? "0" : minute) + ":" + ((second < 10) ? "0" + second : second);
// this.timerText.text = "Yarış başladı! =>" + ((minute < 0) ? "0" : minute) + ":" + ((second < 10) ? "0" + second : second);
});
}
//this.timerText.setScrollFactor(0);
this.anims.create({
key: "keys",
frames: this.anims.generateFrameNumbers("entry_cards"),
frameRate: 3,
repeat: -1,
});
this.anims.create({
key: "entry",
frames: this.anims.generateFrameNumbers("entry"),
frameRate: 3,
repeat: -1,
});
this.jumpSound1 = this.sound.add("jump1");
this.jumpSound2 = this.sound.add("jump2");
this.deathSound1 = this.sound.add("death1");
this.attackbig0 = this.sound.add("attackbig0");
this.attackbig1 = this.sound.add("attackbig1");
this.attackbig2 = this.sound.add("attackbig2");
this.attackbig3 = this.sound.add("attackbig3");
this.attackbig4 = this.sound.add("attackbig4");
this.soundtrack2 = this.sound.add("soundtrack1", {
volume: 0.5
});
this.soundtrack2.play();
this.soundtrack2.setMute(!isSounded());
this.attackSounds = [this.attackbig0, this.attackbig1, this.attackbig2, this.attackbig3, this.attackbig4];
this.gunSound = this.sound.add("gun" + this.defaultGunNumber, {
start: 0.25,
volume: 2,
});
this.keySound = this.sound.add("keysound");
// Matter.js fizik nesnelerini oluşturma
if (this.layer) {
this.layer.setCollisionByProperty({ collides: true });
this.addTilemapPolygonsToMatter(this.layer);
}
// Collider'ları tanımlama
if (this.layer) {
this.matter.world.convertTilemapLayer(this.layer);
}
if (this.ladders) {
this.matter.world.convertTilemapLayer(this.ladders);
}
this.keys = this.add.sprite(0, 0, "keys");
this.keys.anims.play("keys");
this.keys.x = this.keysCoord.x;
this.keys.y = this.keysCoord.y;
this.player = this.matter.add.sprite(100, 100, "player_Azur_Idle");
this.player.setBody({
type: 'rectangle',
width: this.player.displayWidth * (3/4),
height: this.player.displayHeight,
})
this.player.setOrigin(0.5 - 1/9, 0.5);
this.player.setData("canJump", false);
this.player.setData("JumpTimes", 0);
this.player.setData('isGuilty', false)
this.player.setFixedRotation();
this.player.setFriction(0.05);
this.player.setFrictionAir(0.02);
this.player.setData("health", 200);
this.player.setData("first_health", 200);
/* if(this.healthBar){
this.healthBar.clear();
}
this.healthBar = this.ctx.fillRect(0,-this.player.height / 5,(this.player.getData("health") / this.player.getData("first_health")) * this.player.width,this.player.height / 10);
this.healthBar.x = this.player.x;
this.healthBar.y = this.player.y;
*/
this.ctx = this.add.graphics()
this.ctx.setDefaultStyles({
fillStyle: {
color: 0x00ffff,
alpha: 1
},
lineStyle: {
width: 1,
color: 0x0000ff,
alpha: 0.75
}
});
this.healthBar = this.ctx.fillRect(0, -this.player.height / 5, (this.player.getData("health") / this.player.getData("first_health")) * this.player.width, this.player.height / 10);
this.healthBar.x = this.player.x;
this.healthBar.y = this.player.y;
this.zoomEffect = 1;
this.player.x = this.startCoord.x;
this.player.y = this.startCoord.y;
this.cameras.main.setBounds(-2000, -2000, 10 ** 4, 10 ** 4)
this.cameras.main.startFollow(this.player, true, 0.05, 0.05);
this.cameras.main.setZoom(this.zoomEffect);
this.bulletIcons = [];
this.player.setData("bullet_limit", weaponDatas[this.defaultGunNumber - 1].effects.ammoCount);
this.ammoCountText.setText(this.player.getData('bullet_limit'));
this.player.setData("canClimb", false);
this.fillAmmo();
this.playerAll = [];
this.allkeys = [];
this.allOfThem = [];
let newPlayerAll = []; // Yeni oyuncu dizisi
if (isSocketWorks && isSocketWorks == true && socket) {
socket.on("otherPlayersData", (data) => {
this.allkeys.forEach(key => {
if (!Object.keys(data).includes(key)) {
this.playerAll[key].destroy();
}
});
Object.keys(data).forEach(key => {
// Kendi oyuncunuzu filtreleyin
if (key !== this.player) {
let player = new CharacterAsSprite(
this,
data[key].x ?? this.startCoord.x,
data[key].y ?? this.startCoord.y,
"Biker_Idle",
data[key].anim
);
player.frameType = data[key].anim;
player.velocity = data[key].velocity;
if (!this.allkeys.includes(key)) {
this.allkeys.push(key);
player.add();
this.playerAll[key] = player;
} else {
if (data[key].flipped) {
this.playerAll[key].character.setFlipX(true);
} else {
this.playerAll[key].character.setFlipX(false);
}
this.playerAll[key].x = data[key].x;
this.playerAll[key].y = data[key].y;
this.playerAll[key].character.x = data[key].x;
this.playerAll[key].character.y = data[key].y;
this.playerAll[key].anim = data[key].anim;
this.playerAll[key].text.x = data[key].x;
this.playerAll[key].text.y = data[key].y;
this.playerAll[key].name = data[key].name;
this.playerAll[key].text.text = this.playerAll[key].name;
if (this.playerAll[key].character.anims.currentAnim.key !== data[key].anim) {
this.playerAll[key].character.anims.play(data[key].anim);
}
}
// player.setAnimation(data[key].anim);
if (this.playerAll.x !== player.x) {
}
}
});
});
}
if (isSounded() === 'null') {
this.soundtrack2.setMute(true);
this.gunSound.setMute(true);
this.hurtSoundsForPlay.forEach(sound => {
sound.setMute(true);
});
this.policeSpeech.setMute(true);
this.jumpSound1.setMute(true)
this.jumpSound2.setMute(true);
}
this.keyTaken = false;
this.entry = this.matter.add.sprite(this.FinishCoord.x, this.FinishCoord.y, "entry");
this.entry.body.isStatic = true;
this.entry.setOrigin(0.5, 0.5);
characterDetails.forEach(character => {
// Animasyonu oluştur
this.anims.create({
key: character.key,
frames: this.anims.generateFrameNumbers(character.key, {
start: character.start,
end: character.end,
}),
frameRate: 8,
repeat: -1,
});
});
if (this.IsGunWith) {
this.player.anims.play("gun" + this.defaultGunNumber + "_Idle");
} else {
this.player.anims.play("player_Azur_Idle");
}
//ismim
this.Itsname = localStorage.getItem("my_name") ?? "thats_me";
this.text = this.add.text(this.player.x, this.player.y, this.Itsname, {
color: "blue",
fontWeight: 100,
backgroundColor: "rgba(255,255,255,0.1)",
align: "center"
}).setOrigin(0.5, 1.5);
this.Panel1 = new InputElem(this, this.winnerList.objects[0].x * (1 / this.rateForFullWidth), this.winnerList.objects[0].y * (1 / this.rateForFullWidth), {
color1: Display.Color.GetColor(0.1 * 255, 0.1 * 255, 0.1 * 255),
color2: Display.Color.GetColor(1 * 255, 1 * 255, 0),
textColor: 'yellow',
alpha: 0.5,
padding: 10,
}, 1, this.winnerList.objects[0].width * (1 / this.rateForFullWidth), this.winnerList.objects[0].height * (1 / this.rateForFullWidth), []);
const my_datas = [];
/*
for (let key = 0; key < 10; key++) {
my_datas.push({
text: key + '- iste bu',
que: key
})
}
Phaser's asset loading system expects resource URLs as strings, not as Promises. In your preload method, you're using dynamic import statements that return Promises. This causes Phaser to receive a Promise instead of the expected string URL, leading to the TypeError: t.url.match is not a function error.
To resolve this issue, you should use static imports for your assets and ensure that the URLs are available synchronously when calling Phaser's load methods. Here's how you can adjust your code:
Step 1: Static Import of Assets
Instead of dynamically importing assets within the preload method, import them statically at the top of your file. For example:
// Importing images
import dynamiteImg from '../assets/areas/objects/dynamite.png';
import bulletImg1 from '../assets/bullets/bullet1.png';
// ... import other images similarly
// Importing JSON files
import mapJSON0 from '../maps/online_maps/online0.json';
import mapJSON1 from '../maps/online_maps/online1.json';
// ... import other JSON files similarly
// Importing spritesheets
import transporterSprite from '../assets/areas/objects/4 Animated objects/Transporter.png';
// ... import other spritesheets similarly
Step 2: Update the preload Method
With static imports, you can directly reference the imported URLs in the preload method:
preload() {
// Load images
this.load.image("map", mapIMG);
this.load.image('sunEffect', sunEffect);
this.load.image('pointer', pointer);
this.load.image('gun', gun);
this.load.image('health_bar_empty', health_bar_empty);
this.load.image('health_bar_filled', health_bar_filled);
// Load audio
this.load.audio('soundtrack1', soundtrack1);
this.load.audio('hurt2', hurt2);
this.load.audio('hurt3', hurt3);
this.load.audio('hurt4', hurt4);
// ... load other audio similarly
// Load dynamic assets that are now imported statically
this.load.spritesheet('mover', transporterSprite, {
frameWidth: 96,
frameHeight: 17
});
// Load tilemaps
this.load.tilemapTiledJSON('map', mapJSON0); // Example for map0
// Repeat for other maps as necessary
// Load other assets as needed
// ...
}
Step 3: Handle Multiple Maps
If you have multiple maps or assets that depend on dynamic data (like the data.level), make sure all possible assets are imported statically, and then select the appropriate one based on the level:
// At the top, import all map JSONs
import mapJSON0 from '../maps/online_maps/online0.json';
import mapJSON1 from '../maps/online_maps/online1.json';
// ... import other map JSONs similarly
// Create a mapping
const mapJSONs = [
mapJSON0,
mapJSON1,
// ... add other map JSONs here
];
// In your Scene class
init(data) {
// ...
if (data.level >= 0 && data.level < mapJSONs.length) {
this.mapJSON = mapJSONs[data.level];
} else {
console.error('Geçersiz seviye:', data.level);
}
// ...
}
preload() {
// ...
this.load.tilemapTiledJSON('map', this.mapJSON);
// ...
}
Step 4: Update Spritesheets and Other Assets
For spritesheets and other dynamically loaded assets, follow the same pattern:
// Import all necessary spritesheets statically
import robot1Sprite from '../assets/robots/robot1.png';
import robot2Sprite from '../assets/robots/robot2.png';
// ... import other spritesheets similarly
// Create a mapping if needed
const robotSprites = {
robot1: robot1Sprite,
robot2: robot2Sprite,
// ... map other robots
};
// In preload
this.load.spritesheet('robot1', robotSprites.robot1, {
frameWidth: 96,
frameHeight: 96
});
this.load.spritesheet('robot2', robotSprites.robot2, {
frameWidth: 96,
frameHeight: 96
});
// ... load other spritesheets similarly
Summary
The core issue is that Phaser expects URLs as strings in its load methods, but using dynamic import returns Promises. By switching to static imports, you ensure that Phaser receives the correct URLs synchronously, preventing the TypeError.
If you need dynamic loading based on certain conditions (like levels), plan to import all potential assets upfront and select the appropriate ones during the scene initialization.
Additional Tips
-
Asset Management: Consider organizing your assets in a way that makes static imports easier to manage, especially if you have many assets.
-
Error Handling: Always include error handling when dealing with asset loading to catch and debug issues more efficiently.
-
Performance: Static imports can sometimes increase the initial bundle size. If this becomes an issue, explore code-splitting or other optimization techniques compatible with Phaser and React.
Example Updated Code Snippet
Here's a simplified version of how your preload method might look after these changes:
import Phaser from 'phaser';
import dynamiteImg from '../assets/areas/objects/dynamite.png';
import mapJSON0 from '../maps/online_maps/online0.json';
// ... other static imports
class SceneForStory extends Phaser.Scene {
constructor() {
super({ key: 'gameplay', autoStart: false });
// ... other initializations
}
preload() {
// Load images
this.load.image('map', mapIMG);
this.load.image('dynamite', dynamiteImg);
// ... load other images
// Load tilemaps
this.load.tilemapTiledJSON('map', mapJSON0);
// ... load other tilemaps
// Load audio
this.load.audio('soundtrack1', soundtrack1);
// ... load other audio
// Load spritesheets
this.load.spritesheet('mover', transporterSprite, {
frameWidth: 96,
frameHeight: 17
});
// ... load other spritesheets
}
// ... rest of your Scene class
}
export default SceneForStory;
By implementing these changes, Phaser should correctly load all assets without encountering the TypeError.