can anyone explain how the code below works ? this is a timed animation that uses the Phaser Javascript framework.
I can't work out how this works in sequence, e.g. how each function is triggered, doIntro0() followed by doIntro1()
For brevity , I have ommited the majorty of doIntro functions.
showIntro(); // initial call
var introFlags = new Object();
function showIntro(){
if (!introFlags.step0){
if (!introFlags.doingStep0){
introFlags.doingStep0 = true;
doIntro0();
}
return
}
if (!introFlags.step1){
if (!introFlags.doingStep1){
introFlags.doingStep1 = true;
doIntro1();
}
return
}
}
function doIntro0(){
player.animations.play("rest");
player.x = 160+32;
princess.animations.play("rest0");
princess.x = 240;
graves.alpha = 0;
devil.alpha = 0;
armour = game.add.sprite(140,354,"armour");
setTimeout(endIntro0,500);
}
function endIntro0(){
introFlags.step0 = true;
}
function doIntro1(){
blackBg.alpha = 0.2;
setTimeout(endIntro1,2000);
}
function endIntro1(){
introFlags.step1 = true;
}
Related
let play_button = document.querySelector('#play_button');
let reverb_button = document.querySelector('#reverb_button');
let save_button = document.querySelector("#save_button");
let song, reverb, speed_slider, recorder;
let reverb_on = false;
function preload() {
song = loadSound('music/Mood.mp3');
}
function setup() {
speed_slider = createSlider(0.6, 1.5, 1, 0.1); // min, max, start, step
reverb = new p5.Reverb();
reverb.process(song, 10, 10); // 10 seconds duration, 10% decay
}
function draw() {
let val = 0;
if (reverb_on) val = 1;
reverb.drywet(val); // 1 is all reverb
song.rate(speed_slider.value());
}
function togglePlay() {
if (!song.isPlaying()) {
song.play();
play_button.innerText = "Stop"
} else {
song.pause();
play_button.innerText = "Play"
}
}
function toggleReverb() {
if (!reverb_on) {
reverb_button.innerText = 'off';
reverb_on = true;
} else {
reverb_button.innerText = 'on';
reverb_on = false
}
}
function saveSong() {
saveSound(song, 'mood')
}
Above is my code, trying to give the user an option to save the soundfile after they added different effects to it, such as reverb and speed control.
No matter what method I tried that was on the p5 documentation, including:
saveSound() -> https://p5js.org/reference/#/p5/saveSound
save() -> https://p5js.org/reference/#/p5.SoundFile/save
p5.SoundRecorder passing in the sound file itself.
None of them work and only save the original sound; doesn't save any of the 'changes' you make.
I'm trying to change this code that I made from actionscript 3 to html5 canvas. I’m with doubt about calling functions that I created, for example:
function cleanSelection(){
this.a1.visible = true;
this.sa1.visible = false;
this.a2.visible = true;
this.sa2.visible = false;
}
function maxSelection(count){
cleanSelection();
count = 0;
return count;
}
I want to make this function below be able to call maxSelection() which calls cleanSelection()
this.a1.addEventListener("click", fl_Click.bind(this));
function fl_Click()
{
this.sa1.visible = true;
this.a1.visible = false;
count++;
if(count >= 2){
count = maxSelection(count);
}
}
How can I call these functions?
You Should put "bind(this)" in all methods:
function cleanSelection(){
this.a1.visible = true;
this.sa1.visible = false;
this.a2.visible = true;
this.sa2.visible = false;
}
function maxSelection(c){
cleanSelection.bind(this)();
c= 0;
return c;
}
var count = 0;
this.a1.addEventListener("click", fl_Click.bind(this));
function fl_Click() {
this.sa1.visible = true;
this.a1.visible = false;
count++;
if(count >= 2){
count = maxSelection.bind(this)(count);
}
}
I'm having trouble with designing a class which exposes its actions through callbacks. Yes my approach works for me but also seems too complex.
To illustrate the problem I've drawn the following picture. I hope it is useful for you to understand the class/model.
In my approach, I use some arrays holding user defined callback functions.
....
rocket.prototype.on = function(eventName, userFunction) {
this.callbacks[eventName].push(userFunction);
}
rocket.prototype.beforeLunch = function(){
userFunctions = this.callbacks['beforeLunch']
for(var i in userFunctions)
userFunctions[i](); // calling the user function
}
rocket.prototype.lunch = function() {
this.beforeLunch();
...
}
....
var myRocket = new Rocket();
myRocket.on('beforeLunch', function() {
// do some work
console.log('the newspaper guys are taking pictures of the rocket');
});
myRocket.on('beforeLunch', function() {
// do some work
console.log('some engineers are making last checks ');
});
I'm wondering what the most used approach is. I guess I could use promises or other libraries to make this implementation more understandable. In this slide using callbacks is considered evil. http://www.slideshare.net/TrevorBurnham/sane-async-patterns
So, should I use a library such as promise or continue and enhance my approach?
var Rocket = function () {
this.timer = null;
this.velocity = 200;
this.heightMoon = 5000;
this.goingToMoon = true;
this.rocketStatus = {
velocity: null,
height: 0,
status: null
};
this.listener = {
};
}
Rocket.prototype.report = function () {
for (var i in this.rocketStatus) {
console.log(this.rocketStatus[i]);
};
};
Rocket.prototype.on = function (name,cb) {
if (this.listener[name]){
this.listener[name].push(cb);
}else{
this.listener[name] = new Array(cb);
}
};
Rocket.prototype.initListener = function (name) {
if (this.listener[name]) {
for (var i = 0; i < this.listener[name].length; i++) {
this.listener[name][i]();
}
return true;
}else{
return false;
};
}
Rocket.prototype.launch = function () {
this.initListener("beforeLaunch");
this.rocketStatus.status = "Launching";
this.move();
this.initListener("afterLaunch");
}
Rocket.prototype.move = function () {
var that = this;
that.initListener("beforeMove");
if (that.goingToMoon) {
that.rocketStatus.height += that.velocity;
}else{
that.rocketStatus.height -= that.velocity;
};
that.rocketStatus.velocity = that.velocity;
if (that.velocity != 0) {
that.rocketStatus.status = "moving";
}else{
that.rocketStatus.status = "not moving";
};
if (that.velocity >= 600){
that.crash();
return;
}
if (that.rocketStatus.height == 2000 && that.goingToMoon)
that.leaveModules();
if (that.rocketStatus.height == that.heightMoon)
that.landToMoon();
if (that.rocketStatus.height == 0 && !that.goingToMoon){
that.landToEarth();
return;
}
that.report();
that.initListener("afterMove");
that.timer = setTimeout(function () {
that.move();
},1000)
}
Rocket.prototype.stop = function () {
clearTimeout(this.timer);
this.initListener("beforeStop");
this.velocity = 0;
this.rocketStatus.status = "Stopped";
console.log(this.rocketStatus.status)
this.initListener("afterStop");
return true;
}
Rocket.prototype.crash = function () {
this.initListener("beforeCrash");
this.rocketStatus.status = "Crashed!";
this.report();
this.stop();
this.initListener("afterCrash");
}
Rocket.prototype.leaveModules = function () {
this.initListener("beforeModules");
this.rocketStatus.status = "Leaving Modules";
this.initListener("afterModules");
}
Rocket.prototype.landToMoon = function () {
this.initListener("beforeLandToMoon");
this.rocketStatus.status = "Landing to Moon";
this.goingToMoon = false;
this.initListener("afterLandToMoon");
}
Rocket.prototype.landToEarth = function () {
this.initListener("beforeLandToEarth");
this.stop();
this.rocketStatus.status = "Landing to Earth";
this.initListener("afterLandToEarth");
}
Rocket.prototype.relaunch = function () {
this.initListener("beforeRelaunch");
this.timer = null;
this.velocity = 200;
this.heightMoon = 5000;
this.goingToMoon = true;
this.rocketStatus = {
velocity: 200,
height: 0,
status: "relaunch"
};
this.launch();
this.initListener("afterRelaunch");
}
init;
var rocket = new Rocket();
rocket.on("afterLaunch", function () {console.log("launch1")})
rocket.on("afterLandToMoon", function () {console.log("land1")})
rocket.on("beforeLandToEarth", function () {console.log("land2")})
rocket.on("afterMove", function () {console.log("move1")})
rocket.on("beforeLaunch", function () {console.log("launch2")})
rocket.launch();
You can add any function before or after any event.
This is my solution for this kinda problem. I am not using any special methods anything. I was just wonder is there any good practise for this like problems. I dig some promise,deferred but i just can't able to to this. Any ideas ?
Click this link, after around 2 seconds you will see some ships coming at you. Now go to a different window for like 15-20 seconds. then come back, you will see a huge wall of enimes coming at you. Now obviously this is because canvas keeps the loops going but is just not letting the came continue on?
So any help would be great, I know this is not an issue during gameplay but if anyone goes off the window then it kind of messes things up...
I tried to solve this by adding these listeners:
window.onblur = function() {
// Add logic to pause the game here...
stopLoop();
};
window.onfocus = function() {
// Add logic to pause the game here...
startLoop();
};
But it does not solve the issue...
The actual loops:
function init()
{
isPlaying = true;
drawBackground();
drawBars();
setUpListeners();
startLoop();
}
and then...
function Loop()
{
if (isPlaying == true)
{
Player1.draw();
requestAnimFrame(Loop);
drawAllEnemies();
}
}
function startLoop()
{
isPlaying = true;
Loop();
startSpawningEnemies();
}
function stopLoop()
{
isPlaying = false;
stopSpawningEnemies();
}
function spawnEnemy(n) //total enemies starts at 0 and every-time you add to array
{
for (var x = 0; x < n; x++)
{
enemies[totalEnemies] = new Enemy();
totalEnemies++;
}
}
function drawAllEnemies()
{
ClearEnemyCanvas();
for(var i = 0; i < enemies.length; i++)
{
enemies[i].draw();
}
}
function startSpawningEnemies()
{
stopSpawningEnemies();
spawnInterval = setInterval(function() {spawnEnemy(spawnAmount);}, spawnRate); //this calls spawnEnemy every spawnRate
/////////spawn 'spawnAmount' enemies every 2 seconds
}
function stopSpawningEnemies()
{
clearInterval(spawnInterval);
}
Actual methods for the enemy:
function Enemy() //Object
{
//////Your ships values
this.EnemyHullMax = 1000;
this.EnemyHull = 1000;
this.EnemyShieldMax = 1000;
this.EnemyShield = 347;
this.SpaceCrystalReward = 2684;
this.EnemySpeed = 2; //should be around 6 pixels every-time draw is called by interval, directly linked to the fps global variable
////////////
////Pick Ship
this.type = "Hover";
this.srcX = EnemySrcXPicker(this.type);
this.srcY = EnemySrcYPicker(this.type);
this.enemyWidth = EnemyWidthPicker(this.type);
this.enemyHeight = EnemyHeightPicker(this.type);
this.drawX = EnemydrawXPicker(this.type);
this.drawY = EnemydrawYPicker(this.type);
////
}
Enemy.prototype.draw = function()
{
this.drawX -= this.EnemySpeed;
ctxEnemy.globalAlpha=1;
ctxEnemy.drawImage(spriteImage,this.srcX,this.srcY,this.enemyWidth,this.enemyHeight,this.drawX,this.drawY,this.enemyWidth,this.enemyHeight);
}
function EnemySrcXPicker(type)
{
if (type == "Hover")
{
return 906;
}
}
function EnemySrcYPicker(type)
{
if (type == "Hover")
{
return 616;
}
}
function EnemydrawXPicker(type)
{
if (type == "Hover")
{
return Math.floor(Math.random() * 1000) + canvasWidthEnemy;
}
}
function EnemydrawYPicker(type)
{
if (type== "Hover")
{
return Math.floor(Math.random() * (canvasHeightEnemy - 72));
}
}
function EnemyWidthPicker(type)
{
if (type == "Hover")
{
return 90;
}
}
function EnemyHeightPicker(type)
{
if (type == "Hover")
{
return 72;
}
}
Depends on the loop.
If you use setTimeOut or setInterval, then yes. The loop will continue even when the window loses focus.
If you use requestFrameAnimation, then no, the loop will stop when the window loses focus.
requestFrameAnimation was created to solve issues like this. Having you PC burn CPU cycles for something not active is just silly.
I'm trying to build a simple Tween class in javascript. The code reads something like:
function Tween(object, parameters) { // constructor-class def.
this.object = object;
this.parameters = parameters;
this.isRunning = true;
this.frameRate = some value;
this.timeElapsed = some value;
this.duration = some value;
}
Tween.prototype.drawFrame = function () {
var self = this;
this.nextFrame();
if (this.isRunning)
setTimeout( function () { self.drawFrame() } , 1000 / frameRate);
}
Tween.prototype.nextFrame = function () {
if (this.timeElapsed < this.duration) {
// calculate and update the parameters of the object
} else
this.isRunning = false;
}
Tween.prototype.start = function () {
this.isRunning = true;
this.drawFrame();
}
This is then called by another script, say main.js :
window.onload = init;
init = function() {
var tweenDiv = document.createElement('div');
tweenDiv.id = 'someDiv';
document.body.appendChild(tweenDiv);
var myTween = new Tween(document.getElementById('someDiv').style, 'left', parameters);
myTween.start();
}
Unfortunately, this doesnt work. If I examine my site with Google Chrome developer tools, someDiv has its left-style-attribute set to the number of pixels set in the parameters. But it doesn't move on the screen.
Anybody know what I'm doing wrong? Why isn't someDiv being redrawn?
Much Obliged
You have to set the position style to absolute, fixed or relative for the left style to have any effect.