how to make html5 game run on mobile device browser with phaser? - javascript

I have just found a html5 game framework named phaser and it says that this framework support both PC browser and mobile device browser only if they support Html5. So I wrote a sample as the tutorial and It worked fine in my PC with Chrome, But When I launch it with chrome browser on my iphone. It just give a blank page with nothing.
Here is the code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Phaser - Making your first game, part 1</title>
<script type="text/javascript" src="js/phaser.min.js"></script>
<style type="text/css">
body {
margin: 0;
}
</style>
</head>
<body>
<script type="text/javascript">
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });
var score = 0;
var scoreText;
function preload() {
game.load.image('sky', 'assets/sky.png');
game.load.image('ground', 'assets/platform.png');
game.load.image('star', 'assets/star.png');
game.load.spritesheet('dude','assets/dude.png', 32,48);
game.add.sprite(0,0,'star');
}
var platforms;
function create() {
game.physics.startSystem(Phaser.Physics.ARCADE);
game.add.sprite(0,0,'sky');
platforms = game.add.group();
platforms.enableBody = true;
var ground= platforms.create(0,game.world.height-64,'ground');
ground.scale.setTo(2,2);
ground.body.immovable=true;
var ledge = platforms.create(400,400,'ground');
ledge.body.immovable=true;
ledge = platforms.create(-150,250,'ground');
ledge.body.immovable = true;
player = game.add.sprite(32,game.world.height-150,'dude');
game.physics.arcade.enable(player);
player.body.bounce.y = 0.2;
player.body.gravity.y = 300;
player.body.collideWorldBounds = true;
player.animations.add('left',[0,1,2,3],10,true);
player.animations.add('right',[5,6,7,8],10,true);
cursors = game.input.keyboard.createCursorKeys();
stars = game.add.group();
stars.enableBody = true;
for(var i=0;i<12;i++){
var star = stars.create(i*70,0,'star');
star.body.gravity.y = 100;
star.body.bounce.y=0.7 + Math.random()*0.2;
}
scoreText = game.add.text(16,16, 'score:0',{fontSize:'32px',fill:'#000'});
}
function collectStar(player, star){
star.kill();
score = score + 10;
scoreText.text = 'Score: ' + score;
}
function update() {
game.physics.arcade.collide(player, platforms);
game.physics.arcade.collide(stars,platforms);
game.physics.arcade.overlap(player,stars,collectStar, null,this);
player.body.velocity.x=0;
if(cursors.left.isDown){
player.body.velocity.x=-150;
player.animations.play('left');
}
else if(cursors.right.isDown){
player.body.velocity.x=150;
player.animations.play('right');
}else {
player.animations.stop();
player.frame=4;
}
if(cursors.up.isDown && player.body.touching.down){
player.body.velocity.y = -350;
}
}
</script>
</body>
</html>
And you can try the code here: http://game.ximing.org/

In my experience, the supported renderers are for some reason not always properly recognized when using auto detection. Try using
Phaser.CANVAS
in the game constructor.

I use the CocoonJS launcher app on my iPhone to test out my games. I'm not familiar with Android, but for iOS users, just connect your iPhone to your computer, open up the applications folder, and then drag and drop a copy of your game into the CocoonJS app, then sync your phone. You can then test your game on you phone as if it were in a wrapper (no URL, or any signs of it being a web application).

Related

Unity trying to make downloaded webGL game go fullscreen automatically [duplicate]

This question already has answers here:
Javascript request fullscreen is unreliable
(5 answers)
Closed 21 days ago.
I have a Unity webGL game I downloaded from the web. I don't know what version of unity it was made in.
It starts playing in a small canvas with other stuff on the page like Unity logo, there is a button on the page that makes it fullscreen. I would like it to be fullscreen as soon as you load the page..
I tried adding this line to the script in index.html, to click the fullscreen button..
fullscreenButton.click();
But I get a load of errors..
here is the full index.html with the javascript in it. You can see the line I added near the bottom. I just tried clicking the button after unityInstance.SetFullscreen(1) is assigned to its onclick event (or whatever it is (I dunno anything about web).
I also tried just calling unityInstance.SetFullscreen(1) but I get the same error.
So how can I make it go fullscreen?
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Unity WebGL Player | QTE</title>
<link rel="shortcut icon" href="TemplateData/favicon.ico">
<link rel="stylesheet" href="TemplateData/style.css">
</head>
<body>
<div id="unity-container" class="unity-desktop">
<canvas id="unity-canvas" width="100%" height="100%"></canvas>
<div id="unity-loading-bar">
<div id="unity-logo"></div>
<div id="unity-progress-bar-empty">
<div id="unity-progress-bar-full"></div>
</div>
</div>
<div id="unity-warning"> </div>
<div id="unity-footer">
<div id="unity-webgl-logo"></div>
<div id="unity-fullscreen-button"></div>
<div id="unity-build-title">QTE</div>
</div>
</div>
<script>
var container = document.querySelector("#unity-container");
var canvas = document.querySelector("#unity-canvas");
var loadingBar = document.querySelector("#unity-loading-bar");
var progressBarFull = document.querySelector("#unity-progress-bar-full");
var fullscreenButton = document.querySelector("#unity-fullscreen-button");
var warningBanner = document.querySelector("#unity-warning");
// Shows a temporary message banner/ribbon for a few seconds, or
// a permanent error message on top of the canvas if type=='error'.
// If type=='warning', a yellow highlight color is used.
// Modify or remove this function to customize the visually presented
// way that non-critical warnings and error messages are presented to the
// user.
function unityShowBanner(msg, type) {
function updateBannerVisibility() {
warningBanner.style.display = warningBanner.children.length ? 'block' : 'none';
}
var div = document.createElement('div');
div.innerHTML = msg;
warningBanner.appendChild(div);
if (type == 'error') div.style = 'background: red; padding: 10px;';
else {
if (type == 'warning') div.style = 'background: yellow; padding: 10px;';
setTimeout(function() {
warningBanner.removeChild(div);
updateBannerVisibility();
}, 5000);
}
updateBannerVisibility();
}
var buildUrl = "Build";
var loaderUrl = buildUrl + "/WebBuild.loader.js";
var config = {
dataUrl: buildUrl + "/WebBuild.data",
frameworkUrl: buildUrl + "/WebBuild.framework.js",
codeUrl: buildUrl + "/WebBuild.wasm",
streamingAssetsUrl: "StreamingAssets",
companyName: "Rat Bashers",
productName: "QTE",
productVersion: "0.1",
showBanner: unityShowBanner,
};
// By default Unity keeps WebGL canvas render target size matched with
// the DOM size of the canvas element (scaled by window.devicePixelRatio)
// Set this to false if you want to decouple this synchronization from
// happening inside the engine, and you would instead like to size up
// the canvas DOM size and WebGL render target sizes yourself.
// config.matchWebGLToCanvasSize = false;
if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
// Mobile device style: fill the whole browser client area with the game canvas:
var meta = document.createElement('meta');
meta.name = 'viewport';
meta.content = 'width=device-width, height=device-height, initial-scale=1.0, user-scalable=no, shrink-to-fit=yes';
document.getElementsByTagName('head')[0].appendChild(meta);
container.className = "unity-mobile";
// To lower canvas resolution on mobile devices to gain some
// performance, uncomment the following line:
// config.devicePixelRatio = 1;
canvas.style.width = window.innerWidth + 'px';
canvas.style.height = window.innerHeight + 'px';
unityShowBanner('WebGL builds are not supported on mobile devices.');
} else {
// Desktop style: Render the game canvas in a window that can be maximized to fullscreen:
canvas.style.width = "1280px";
canvas.style.height = "720px";
}
loadingBar.style.display = "block";
var script = document.createElement("script");
script.src = loaderUrl;
script.onload = () => {
createUnityInstance(canvas, config, (progress) => {
progressBarFull.style.width = 100 * progress + "%";
}).then((unityInstance) => {
loadingBar.style.display = "none";
unityInstance.SetFullscreen(1);
fullscreenButton.onclick = () => {
unityInstance.SetFullscreen(1);
};
fullscreenButton.click();
}).catch((message) => {
alert(message);
});
};
document.body.appendChild(script);
</script>
</body>
</html>
For security reasons requestFullscreen can only be called in an event handler of a keyboard or click event.
More details: Javascript request fullscreen is unreliable

How to fix 'HTML 5 Audio pool exhausted, returning potentially locked audio object' in JavaScript?

I am trying to clone this particular website called patatap.com as I am learning JavaScript. But i keep getting this error that I don't know how to solve it. It directs me to a google website where it says that there was a policy change for 'Auto play Policy Changes'. But I can't quite figure out how to apply the given example in my code as I am using objects and howler.js.
error:
https://i.imgur.com/oybV1Vw.png
I have tried not using objects and directly defining all key press events inside keyDown function using if..else and it works but it gets confusing and messy.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Circles</title>
<link rel="stylesheet" href="assets/css/circles.css">
<script type="text/javascript" src="assets/lib/paper-full.js"></script>
<script type="text/javascript" src="assets/lib/howler.js"></script>
<script type="text/paperscript" canvas="canvas">
var circles = [];
var keyData = {
a:{
color: "purple",
sound: new Howl({
src: ['assets/sounds/bubbles.mp3'],
html5:true
})
},
s:{
color: "green",
sound:new Howl({
src:['assets/sounds/clay.mp3'],
html5:true
})
},
d:{
color:"yellow",
sound:new Howl({
src:['assets/sounds/confetti.mp3'],
html5:true
})
}
}
function onKeyDown(event){
if(keyData[event.key]){
var maxPoint = new Point(view.size.width, view.size.height);
var randomPoint = Point.random();
var point = maxPoint * randomPoint;
var newCircle = new Path.Circle(point, 500);
newCircle.fillColor=keyData[event.key].color;
circles.push(newCircle);
}
}
function onFrame(event){
for(var i = 0; i < circles.length; i++) {
circles[i].fillColor.hue+=2;
circles[i].scale(.9);
}
}
</script>
</head>
<body>
<canvas id="canvas" resize></canvas>
</body>
</html>
I expect that the sounds start playing while I can still make use of objects and howler.js
In function onkeyDown add this line:
keyData[event.key].sound.play();
Hope this will work.

web audio api convolver doens't seem to output zeros

I have used web audio api to connect a microphone to a convolver to an analyser to a flot gui to plot the spectrum. For testing I set the buffer of the convolver to be unity but I don't get any output. If I bypass the convolver and connect the mic directly to the analyser it works. Can you please help?
In the code below use_convolver determines if to bypass convolver or not.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://www.flotcharts.org/flot/jquery.flot.js" type="text/javascript"></script>
</head>
<body>
<h1>Audio Spectrum</h1>
<div id="placeholder" style="width:400px; height:200px; display: inline-block;">
</div>
<script>
var microphone;
var analyser;
var convolver;
//user media
navigator.getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
if (navigator.getUserMedia) {
console.log('getUserMedia supported.');
navigator.getUserMedia(
// constraints - only audio needed for this app
{
audio : true,
echoCancellation : true
},
// Success callback
user_media_setup,
// Error callback
function(err) {
console.log('The following gUM error occured: ' + err);
});
} else {
console.log('getUserMedia not supported on your browser!');
};
function user_media_setup(stream) {
console.log('user media setup');
// set up forked web audio context, for multiple browsers
// window. is needed otherwise Safari explodes
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
//microphone
microphone = audioCtx.createMediaStreamSource(stream);
//analyser
analyser = audioCtx.createAnalyser();
analyser.fftSize = 1024;
analyser.smoothingTimeConstant = 0.85;
//convolver
convolver = audioCtx.createConvolver();
convolver.normalize = true;
convolverBuffer = audioCtx.createBuffer(1, 1, audioCtx.sampleRate);
// convolverBuffer[0] = 1; //wrong
convolverChannel = convolverBuffer.getChannelData(0);
convolverChannel[0] = 1;
convolver.buffer = convolverBuffer;
//connectivity
var use_convolver = false;
if (use_convolver) {
//through convolver:
microphone.connect(convolver);
convolver.connect(analyser);
} else {
//direct:
microphone.connect(analyser);
}
visualize();
}
function visualize() {
console.log('visualize');
dataArray = new Float32Array(analyser.frequencyBinCount);
draw = function() {
analyser.getFloatFrequencyData(dataArray);
var data = [];
for (var i = 0; i < dataArray.length; i++) {
freq = audioCtx.sampleRate * i / dataArray.length / 2;
data.push([freq, dataArray[i]]);
}
var options = {
yaxis : {
min : -200,
max : 0
}
};
$.plot("#placeholder", [data], options);
window.requestAnimationFrame(draw);
};
window.requestAnimationFrame(draw);
}
</script>
</body>
</html>
convolverBuffer[0] is the wrong way to get at the sample data in the buffer. You need to call convolverBuffer.getChannelData(0) to get the sample array to modify.
#aldel This problem was bugging me for a few frustrating days .. much thanks for this tip. I can confirm that this is an issue in firefox as well. It seems if you use a mono WAV file as the buffer for the convolver, you will not get any output from the convolver.
After I switched to a stereo WAV impulse response as the buffer, the convolver worked.
Also a tip I learned today is that firefox's web audio tools (enabled by clicking the gear in the top right section of the firefox dev tools, and checking 'web audio' over on the left) are really useful for visualizing the order of your nodes. And you can easily switch a node on/off (bypass it) to see if that's causing problems in your audio context.

Creating a FallBack for Flash for IE8

I created an simple animation with Flash and used the CREATEJS PLuggin to convert my SWF to a HTML5 + JS solution. THis works fine in all browsers EXCEPT IE* and older of course.
My solution is to create a Flash FallBack to play the SWF file if the Browser is IE.
Unfortunately I am able to write this and was hopig someone can help me to achieve this.
Please see the HTML file below:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CreateJS export from cwtXmasCard2013</title>
<script src="http://code.createjs.com/easeljs-0.6.0.min.js"></script>
<script src="http://code.createjs.com/tweenjs-0.4.0.min.js"></script>
<script src="http://code.createjs.com/movieclip-0.6.0.min.js"></script>
<script src="http://code.createjs.com/preloadjs-0.3.0.min.js"></script>
<script src="cwtXmasCard2013.js"></script>
<script>
var canvas, stage, exportRoot;
function init() {
canvas = document.getElementById("canvas");
images = images||{};
var manifest = [
{src:"images/Image.png", id:"Image"},
{src:"images/Image_1.png", id:"Image_1"},
{src:"images/Image_0.png", id:"Image_0"},
{src:"images/CWT_HolidayCard.jpg", id:"CWT_HolidayCard"}
];
var loader = new createjs.LoadQueue(false);
loader.addEventListener("fileload", handleFileLoad);
loader.addEventListener("complete", handleComplete);
loader.loadManifest(manifest);
}
function handleFileLoad(evt) {
if (evt.item.type == "image") { images[evt.item.id] = evt.result; }
}
function handleComplete() {
exportRoot = new lib.cwtXmasCard2013();
stage = new createjs.Stage(canvas);
stage.addChild(exportRoot);
stage.update();
createjs.Ticker.setFPS(24);
createjs.Ticker.addEventListener("tick", stage);
}
</script>
</head>
<body onload="init();" style="background-color:#D4D4D4">
<canvas id="canvas" width="711" height="661" style="background- color:#ffffff"></canvas>
</body>
</html>

PreloadJS is undefined(Windows 8 game programming)

I am new to metro style programming so I am following a tutorial here http://www.sitepoint.com/creating-a-simple-windows-8-game-with-javascript-game-basics-createjseaseljs/ for games using createJS. Here the code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>game</title>
<!-- WinJS references -->
<link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>
<!-- game references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
<script src="/js/CreateJS/easeljs-0.5.0.min.js"></script>
<script src="/js/CreateJS/preloadjs-0.2.0.min.js"></script>
</head>
<body>
<canvas id="gameCanvas"></canvas>
</body>
</html>
and here's javascript code
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
"use strict";
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
WinJS.strictProcessing();
function initialize() {
canvas = document.getElementById("gameCanvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
context = canvas.getContext("2d");
preload = new PreloadJS();
preload.onComplete = prepareGame;
var manifest = [
{ id: "screenImage", src: "images/Backgrounds/gameplay_screen.png" },
{ id: "redImage", src: "images/Catapults/Red/redIdle/redIdle.png" },
{ id: "blueImage", src: "images/Catapults/Blue/blueIdle/blueIdle.png" },
{ id: "ammoImage", src: "images/Ammo/rock_ammo.png" },
{ id: "winImage", src: "images/Backgrounds/victory.png" },
{ id: "loseImage", src: "images/Backgrounds/defeat.png" },
{ id: "blueFire", src: "images/Catapults/Blue/blueFire/blueCatapult_fire.png" },
{ id: "redFire", src: "images/Catapults/Red/redFire/redCatapult_fire.png" },
];
preload.loadManifest(manifest);
stage = new Stage(canvas);
}
function prepareGame() {
bgImage = preload.getResult("screenImage").result;
bgBitmap = new Bitmap(bgImage);
bgBitmap.scaleX = SCALE_X;
bgBitmap.scaleY = SCALE_Y;
stage.addChild(bgBitmap);
stage.update();
}
function gameLoop() {
}
function update() {
}
function draw() {
}
var canvas, context, stage;
var bgImage, p1Image, p2Image, ammoImage, p1lives, p2lives, title, endGameImage;
var bgBitmap, p1Bitmap, p2Bitmap, ammoBitmap;
var preload;
// Current Display Factor. Because the orignal assumed a 800x480 screen
var SCALE_X = window.innerWidth / 800;
var SCALE_Y = window.innerHeight / 480;
var MARGIN = 25;
var GROUND_Y = 390 * SCALE_Y;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
// TODO: This application has been newly launched. Initialize
// your application here.
} else {
// TODO: This application has been reactivated from suspension.
// Restore application state here.
}
args.setPromise(WinJS.UI.processAll());
}
};
app.oncheckpoint = function (args) {
// TODO: This application is about to be suspended. Save any state
// that needs to persist across suspensions here. You might use the
// WinJS.Application.sessionState object, which is automatically
// saved and restored across suspension. If you need to complete an
// asynchronous operation before your application is suspended, call
// args.setPromise().
};
document.addEventListener("DOMContentLoaded", initialize, false);
app.start();
})();
Now the problem is that whenever I try to compile the code it gives me the Preload is undefined error. I do not understand the reason I have included the script in HTML and file in my project. Would somebody please help this problem has been killing me for the last hour and I just want to make a simple game.
The reason for this is that the libraries have been placed under the "createjs" namespace. In order to instantiate the PreloadJS object, please do the following:
var preload = new createjs.PreloadJS();
That should get you back to happy path.
(Tried on Feb 2013, after PreloadJS 0.3.0 released)
I just tried the tutorial from sitepoint.com (http://www.sitepoint.com/creating-a-simple-windows-8-game-with-javascript-game-basics-createjseaseljs/), using the latest versions of EaselJS and PreloadJS, but I couldn't get the code to run without errors at first.
The new version of PreloadJS (v0.3.0) has renamed the old PreloadJS class to LoadQueue.
See the documentation at the links below:
http://www.createjs.com/Docs/PreloadJS/classes/PreloadJS.html
http://www.createjs.com/Docs/PreloadJS/classes/LoadQueue.html
But simply using the new class while using v0.3.0 doesn't fix the project. The newer version has additional incompatibilities (e.g. image.width is not valid) which can probably be fixed by trial and error.
I had to download the older PreloadJS v0.2.0:
https://github.com/CreateJS/PreloadJS/tags
IN A NUTSHELL: If I use the SitePoint tutorial, I have to stick with PreloadJS v0.2.0 and also use the createjs namespace.
NOTE: The sample project mentioned in a previous response doesn't work either, because its WinJS references are invalid. Adding the reference manually doesn't seem to work either.
https://github.com/dave-pointbypoint/CatapultGame
Move your default.js in the HTML to be after the preloadjs & easel code.
This is because the order of inclusion is important to JavaScript

Categories