Phaser scenes don't load - javascript

in browser i see only black canvas and i define 2 scenes but I dunno why i see no text someone help pls
game.js
window.onload=function(){
var game = new Phaser.Game();
var config = {
width: 800,
height: 500,
backgroundcColor: 0xffffff,
scene: [Scene1, Scene2]
}
var game = new Phaser.Game(config);
}
Scene1.js
class Scene1 extends Phaser.Scene {
constructor(){
super("Scene1");
}
create(){
this.add.text(20,20,"Loading game", {font:"25px Arial", fill:"yellow"});
}
}

There are some possible issues:
remove the first line var game = new Phaser.Game(); from the onload function. Since at the end you are creating it again, this time with the config object (and each call create a new canvas / phaser app).
Are you loading Scene1 and Scene2, you have to load both if you reference the in the config if not it will cause an error an the execution stops (Even if you are only using one).
If all this does solve the problem, check the browser console for errors, since any error in the code will/can stop the correct application flow.
Here you can see, that your code works basiclly:
document.body.style = 'margin:0;';
class Scene1 extends Phaser.Scene {
constructor(){
super("Scene1");
}
create(){
this.add.text(20,20,"Loading game", {font:"25px Arial", fill:"yellow"});
}
}
window.onload = function(){
// remove this line it is not needed
//var game = new Phaser.Game();
var config = {
width: 800,
height: 500,
backgroundcColor: 0xffffff,
// Remove Scene2 if it is not loaded
//scene: [Scene1, Scene2]
scene: [Scene1]
}
var game = new Phaser.Game(config);
}
<script src="//cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>

Related

Problems with phaser framework, running a server on xampp, getting errors, javascript/html

So I have this code that will run a game being this the base of that game. it uses phaser.
I was trying to run it on xampp on htdocs/itw/test.html
with the 2 pngs and json file being located on htdocs/itw/assets/
the pngs are tilesets and the json tilemap
but I get this errors on console executing the indext.html
Any Help would be awsome
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/phaser#3.15.1/dist/phaser-arcade-physics.min.js"></script>
</head>
<body>
<script>
const config = {
type: Phaser.AUTO, // Which renderer to use
width: 800, // Canvas width in pixels
height: 600, // Canvas height in pixels
parent: "game-container", // ID of the DOM element to add the canvas to
scene: {
preload: preload,
create: create,
update: update
}
};
const game = new Phaser.Game(config);
function preload() {
// Runs once, loads up assets like images and audio
this.load.image("quadrados1", "../assets/outside.png");
this.load.image("quadrados2", "../assets/outside2.png");
this.load.tilemapTiledJSON("mapa", "../assets/fcul_map.json");
}
function create() {
// Runs once, after all assets in preload are loaded
const map = this.make.tilemap({ key: "mapa" });
const tileset = map.addTilesetImage("outside", "quadrados1");
const belowLayer = map.createStaticLayer("Below Player", tileset, 0, 0);
const worldLayer = map.createStaticLayer("World", tileset, 0, 0);
const aboveLayer = map.createStaticLayer("Above Player", tileset, 0, 0);
}
function update(time, delta) {
// Runs once per frame for the duration of the scene
}
</script>
</body>
</html>
.. represents parent directory. Try removing them in your load statements
Ex.
../assets/outside.png to assets/outside.png

How to detect click on the images in phaser3

I am new to phaser and I am trying to detect a click on several images in phaser3 .This has somehow become a two part problem for me.
First is to detect click on the objects, but even if I click anywhere else on the screen also the click handler fires.
Second part is that I have identical and multiple images on the scene, and I want to detect clicks on each of them inside a single function only and detect which image was clicked .
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/phaser#3.24.1/dist/phaser-arcade-physics.min.js"></script>
<style media="screen">
canvas { display : block; margin : auto;}
</style>
</head>
<body>
<script>
var config = {
type: Phaser.CANVAS,
scale: {
mode: Phaser.Scale.ScaleModes.FIT,
parent: 'phaser-example',
autoCenter: Phaser.Scale.CENTER_BOTH,
width: 400,
height: 640
},
// width: 400,
// height: 640,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 10 }
}
},
scene: {
preload: preload,
create: create,
update: update
}
};
var game = new Phaser.Game(config);
var Bimages;
function preload ()
{
this.load.setBaseURL('http://localhost:3000');
this.load.image('sky', 'assets/skies/deepblue.png');
this.load.image('tube1', 'assets/myassets/ballSort/tube.png');
this.load.image('tube2', 'assets/myassets/ballSort/tube.png');
}
var numOfTestTubes = 5;
var storeTubes = [];
function create ()
{
ctx = this;
this.add.image(400, 300, 'sky').scaleY = 1.2;
var t1 = ctx.add.image(150, 300, 'tube1');
t1.scaleY = 0.5;
t1.scaleX = 0.5;
var t2 = ctx.add.image(220, 300, 'tube2');
t2.scaleY = 0.5;
t2.scaleX = 0.5;
t1.setInteractive();
t2.setInteractive();
t1.on('pointerdown', handleclick);
}
function update(){
}
function handleclick(pointer, targets){
console.log("clicked0",pointer);
}
</script>
</body>
</html>
Can anyone help me out here please?
The pointerdown event listener on game objects is different than the pointerdown event listener on the global input manager. If you instead do this.input.on('pointerdown', ...) you'll get a callback with the pointer, but also an array of game objects that were clicked, with an empty array if no game objects were clicked. If you need to register clicks on input objects that overlap each other, you can change this behavior with #setTopOnly. You can check object equality or against some property expected such as the object's name or texture key. I linked a stackblitz with rectangles, but understand they are behaving the same as an image's hitbox would.
https://stackblitz.com/edit/phaser-so-global-input-manager?file=index.ts

Container doesn't render children when declared by 'new' keyword (Phaser 3)

I am trying to declare Container with new keyword for code modularization (referencing this article). However, when I declare one with new Container(), it doesn't render its child image/sprite. What am I doing wrong here? Please see my code below:
var config = {
type: Phaser.AUTO,
width: 800,
height: 600,
backgroundColor: '#010101',
parent: 'phaser-example',
physics: {
default: 'arcade',
arcade: {
gravity: { y: 200 },
debug: true
}
},
scene: {
preload: preload,
create: create
}
};
var container1, container2;
var game = new Phaser.Game(config);
function preload () {
this.load.image('mushroom', 'assets/sprites/mushroom2.png');
this.load.image('lemming', 'assets/sprites/lemming.png');
}
function create () {
var image1 = this.add.image(-40, 0, 'mushroom');
var image2 = this.add.image(40, 0, 'lemming');
container1 = this.add.container(100, 200);
container1.add(image1);
container1.setSize(128, 64);
this.physics.world.enable(container1);
container1.body.setVelocity(0, 200).setBounce(1, 1).setCollideWorldBounds(true);
container2 = new Phaser.GameObjects.Container(this, 300, 200)
container2.add(image2);
container2.setSize(128, 64);
this.physics.world.enable(container2);
container2.body.setVelocity(0, 200).setBounce(1, 1).setCollideWorldBounds(true);
// container1 renders image1, but container2 doesn't render image2.
console.log(this.add.image, Phaser.GameObjects.Container);
console.log(container1, container2);
console.log(container1.list[0], container2.list[0]);
}
If you want to run this code, please go to Phaser3 SandBox, and copy & paste above code and click Run Code (sorry, I don't know how to save my code there). Any help would be highly appreciated!
Copying #rexrainbow's answer at Phaser forum:
A new game object won’t be added to display list, or updating list,
call this method to add this container to display list.
this.add.existing(container2);

Aframe Dynamic Canvas as Texture

I was trying to use a canvas as texture in my aframe project. I found some instructions here. It mentioned:
The texture will automatically refresh itself as the canvas changes.
However, I gave it a try today and the canvas could only be changed / updated in init function. Afterwards the update to canvas cannot be reflected. Here is my implementation:
module.exports = {
'canvas_component': {
schema: {
canvasId: { type: 'string' }
},
init: function () {
this.canvas = document.getElementById(this.data.canvasId);
this.ctx = this.canvas.getContext('2d');
this.ctx.fillStyle = "#FF0000";
this.ctx.fillRect(20, 20, 150, 100);
setTimeout(() => {
this.ctx.fillStyle = "#FFFF00";
this.ctx.fillRect(20, 20, 150, 100);
}, 2000);
}
}
The color change of of the texture was never changed. Is there anything I missed? Thank you so much for any advice.
I could never get it to work with those instructions (never checked out if bug or improper use though), but you can achieve the same with Three.js:
// assuming this is inside an aframe component
init: function() {
// we'll update this manually
this.texture = null
let canvas = document.getElementById("source-canvas");
// wait until the element is ready
this.el.addEventListener('loaded', e => {
// create the texture
this.texture = new THREE.CanvasTexture(canvas);
// get the references neccesary to swap the texture
let mesh = this.el.getObject3D('mesh')
mesh.material.map = this.texture
// if there was a map before, you should dispose it
})
},
tick: function() {
// if the texture is created - update it
if (this.texture) this.texture.needsUpdate = true
}
Check it out in this glitch.
Instead using the tick function, you could update the texture whenever you get any callback from changing the canvas (mouse events, source change).
The docs are out of date, I've made a pull request to update them. Here is the code that shows how to do it now:
src: https://github.com/aframevr/aframe/issues/4878
which points to: https://github.com/aframevr/aframe/blob/b164623dfa0d2548158f4b7da06157497cd4ea29/examples/test/canvas-texture/components/canvas-updater.js
We can quickly turn that into a component like this, for example:
/* global AFRAME */
AFRAME.registerComponent('live-canvas', {
dependencies: ['geometry', 'material'],
schema: {
src: { type: "string", default: "#id"}
},
init() {
if (!document.querySelector(this.data.src)) {
console.error("no such canvas")
return
}
this.el.setAttribute('material',{src:this.data.src})
},
tick() {
var el = this.el;
var material;
material = el.getObject3D('mesh').material;
if (!material.map) {
console.error("no material map")
this.el.removeAttribute('live-canvas')
return;
}
material.map.needsUpdate = true;
}
});
(remember to declate your components before your scene...)
usage:
<body>
<canvas id="example-canvas"></canvas>
<a-scene>
<a-box live-canvas="src:#example-canvas;"></a-box>
</a-scene>
</body>
live glitch code demo here:
https://glitch.com/edit/#!/live-canvas-demo?path=index.html%3A58%3A43
You can of course be more efficient than a tick handler if you just intentionally run the equivalent code manually whenever you update the canvas yourself, if that makes more sense / isn't happening frame-by-frame.

How to take screenshot of game div in phaser

I am using this code now, but it returns a blank transparent image:
$(document).ready(function(){
$("#t").click(function() {
html2canvas(document.querySelector("#bracelet_maker"),
{ onrendered: function(canvas){
src = canvas.toDataURL();
window.open(src); } });
});
});
If I use game.canvas.toDataUrl(); it returns a black image.
This is how the game is started in #bracelet_maker div
var game = new Phaser.Game(width,height,Phaser.AUTO,"bracelte_canvas",{
preload:preload,
create:create,
update:update });
Using Phaser.AUTO will allow either Phaser.WEBGL or Phaser.CANVAS be used, depending upon what your browser supports.
If you switch over to Phaser.CANVAS when creating your new Phaser.Game you should be able to use access the canvas.
For example, within Phaser by binding off the S key:
function create() {
// ...
var screenshotKey = game.input.keyboard.addKey(Phaser.Keyboard.S);
screenshotKey.onDown.add(function () { window.open(game.canvas.toDataURL());
}
There's also preserveDrawingBuffer which should allow you capture from WebGL as well, but it needs to be set early on in the process.
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', {
preload: preload, create: create, update: update
});
game.preserveDrawingBuffer = true;

Categories

Resources