Phaser loading images using object function - javascript

Hi everyone I'm new to Phaser, its really cool but I'm having an issue trying to use add.sprite, I have an array filled with the game information and I'm trying to paste the pictures into the map on the screen the code is as follows. It is the full game code however I'll elaborate further. I have an array called 'paises' which has the name of each country as well as the population and a little bit of more information. I'm trying to add a function for adding the sprites (images) so that later on I can just use a for loop to add all of them to the screen. This function is known as addSprite();
The error message that I get is that the location of the image that the addSprite function will use is considered as undefined since it doesnt know where 'venezuela' inside the following code is located:
addSprite:function(){ this.add.sprite(85,2,'venezuela');}
Its the same issue for the other addSprite functions.
I'm a little new to prototyping so that might be it. Also tried adding the array paises inside the create function to give it time to load the assets but no luck.
BasicGame = {};
BasicGame.Game = function (game) {};
var paises = [
{
name:'venezuela',
population: 30620404,
brandRecognition: 0,
clients:0,
sales:0,
addSprite:function(){
this.add.sprite(85,2,'venezuela');
}},
{
name:'colombia',
population:48264000,
brandRecognition:0,
clients:0,
sales:0,
addSprite:function(){
this.add.sprite(40,2,'colombia');
}},
{
name:'ecuador',
population:16309000,
brandRecognition:0,
clients:0,
sales:0,
addSprite:function(){
this.add.sprite(25,80,'ecuador');}
},
{
name:'guayana',
population:747884,
brandRecognition:0,
clients:0,
sales:0,
addSprite:function(){
this.add.sprite(164,26,'guayana');}
}];
BasicGame.Game.prototype = {
init: function () {
// set up input max pointers
this.input.maxPointers = 1;
// set up stage disable visibility change
this.stage.disableVisibilityChange = true;
// Set up the scaling method used by the ScaleManager
// Valid values for scaleMode are:
// * EXACT_FIT
// * NO_SCALE
// * SHOW_ALL
// * RESIZE
// See http://docs.phaser.io/Phaser.ScaleManager.html for full document
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
// If you wish to align your game in the middle of the page then you can
// set this value to true. It will place a re-calculated margin-left
// pixel value onto the canvas element which is updated on orientation /
// resizing events. It doesn't care about any other DOM element that may
// be on the page, it literally just sets the margin.
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = false;
// Force the orientation in landscape or portrait.
// * Set first to true to force landscape.
// * Set second to true to force portrait.
this.scale.forceOrientation(true, false);
// Sets the callback that will be called when the window resize event
// occurs, or if set the parent container changes dimensions. Use this
// to handle responsive game layout options. Note that the callback will
// only be called if the ScaleManager.scaleMode is set to RESIZE.
this.scale.setResizeCallback(this.gameResized, this);
// Set screen size automatically based on the scaleMode. This is only
// needed if ScaleMode is not set to RESIZE.
this.scale.setScreenSize(true);
// Re-calculate scale mode and update screen size. This only applies if
// ScaleMode is not set to RESIZE.
this.scale.refresh();
},
preload: function () {
// Here we load the assets required for our preloader (in this case a
// background and a loading bar)
this.load.image('logo', 'asset/phaser.png');
this.load.image('brasil','asset/brasil.png');
this.load.image('colombia','asset/colombia.png');
this.load.image('venezuela','asset/venezuela.png');
this.load.image('ecuador','asset/ecuador.png');
this.load.image('peru','asset/peru.png');
this.load.image('guayana','asset/guayana.png');
this.load.image('surinam','asset/surinam.png');
this.load.image('guayanaFrancesa','asset/guayanaFrancesa.png');
this.load.image('brasil','asset/brasil.png');
this.load.image('chile','asset/chile.png');
this.load.image('bolivia','asset/bolivia.png');
this.load.image('argentina','asset/argentina.png');
this.load.image('paraguay','asset/paraguay.png');
this.load.image('uruguay','asset/uruguay.png');
this.load.image('menu','asset/menu.png');
this.load.image('oceano','asset/oceano.jpg');
},
create: function () {
var oceano = this.add.sprite(0,0,'oceano');
var menu = this.add.sprite(450,50,'menu');
for(var i=0;i<3;i++){
paises[i].addSprite();
}
},
gameResized: function (width, height) {
// This could be handy if you need to do any extra processing if the
// game resizes. A resize could happen if for example swapping
// orientation on a device or resizing the browser window. Note that
// this callback is only really useful if you use a ScaleMode of RESIZE
// and place it inside your main game state.
}};

Hi guys just got it to work, the solution involved moving the function outside the object and just saving the parameters inside the object (the x,y and file name). I also made the paises variable a global one. It might not be the most elegant solution but it does what I need it to do. I'll post the code in case someone else can benefit from it.
var paises = [
{
name:'venezuela',
population: 30620404,
brandRecognition: 0,
clients:0,
sales:0,
x:85,
y:2
},
{
name:'colombia',
population:48264000,
brandRecognition:0,
clients:0,
sales:0,
x:40,
y:2
},
{
name:'ecuador',
population:16309000,
brandRecognition:0,
clients:0,
sales:0,
x:25,
y:80
},
{
name:'guayana',
population:747884,
brandRecognition:0,
clients:0,
sales:0,
x: 164,
y:26
}];
BasicGame = {
};
BasicGame.Game = function (game) {
};
BasicGame.Game.prototype = {
init: function () {
// set up input max pointers
this.input.maxPointers = 1;
// set up stage disable visibility change
this.stage.disableVisibilityChange = true;
// Set up the scaling method used by the ScaleManager
// Valid values for scaleMode are:
// * EXACT_FIT
// * NO_SCALE
// * SHOW_ALL
// * RESIZE
// See http://docs.phaser.io/Phaser.ScaleManager.html for full document
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
// If you wish to align your game in the middle of the page then you can
// set this value to true. It will place a re-calculated margin-left
// pixel value onto the canvas element which is updated on orientation /
// resizing events. It doesn't care about any other DOM element that may
// be on the page, it literally just sets the margin.
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = false;
// Force the orientation in landscape or portrait.
// * Set first to true to force landscape.
// * Set second to true to force portrait.
this.scale.forceOrientation(true, false);
// Sets the callback that will be called when the window resize event
// occurs, or if set the parent container changes dimensions. Use this
// to handle responsive game layout options. Note that the callback will
// only be called if the ScaleManager.scaleMode is set to RESIZE.
this.scale.setResizeCallback(this.gameResized, this);
// Set screen size automatically based on the scaleMode. This is only
// needed if ScaleMode is not set to RESIZE.
this.scale.setScreenSize(true);
// Re-calculate scale mode and update screen size. This only applies if
// ScaleMode is not set to RESIZE.
this.scale.refresh();
},
preload: function () {
// Here we load the assets required for our preloader (in this case a
// background and a loading bar)
this.load.image('logo', 'asset/phaser.png');
this.load.image('brasil','asset/brasil.png');
this.load.image('colombia','asset/colombia.png');
this.load.image('venezuela','asset/venezuela.png');
this.load.image('ecuador','asset/ecuador.png');
this.load.image('peru','asset/peru.png');
this.load.image('guayana','asset/guayana.png');
this.load.image('surinam','asset/surinam.png');
this.load.image('guayanaFrancesa','asset/guayanaFrancesa.png');
this.load.image('brasil','asset/brasil.png');
this.load.image('chile','asset/chile.png');
this.load.image('bolivia','asset/bolivia.png');
this.load.image('argentina','asset/argentina.png');
this.load.image('paraguay','asset/paraguay.png');
this.load.image('uruguay','asset/uruguay.png');
this.load.image('menu','asset/menu.png');
this.load.image('oceano','asset/oceano.jpg');
},
create: function () {
var oceano = this.add.sprite(0,0,'oceano');
var menu = this.add.sprite(450,50,'menu');
for(var i=0;i<3;i++){
this.add.sprite(paises[i].x,paises[i].y,paises[i].name);
}
},
gameResized: function (width, height) {
// This could be handy if you need to do any extra processing if the
// game resizes. A resize could happen if for example swapping
// orientation on a device or resizing the browser window. Note that
// this callback is only really useful if you use a ScaleMode of RESIZE
// and place it inside your main game state.
}
};

Related

External Javascript will execute outside div

I have written a function loja() in an external js. In another html file, at the end of the file I have linked it to the external js and then at the body of the html file I have created a div and onclick it will call the function loja(). It all works well but the thing is that the javascript function is not loaded inside the div but at the end of the page.Can you help me out?
This is from html file.
<div class="section-title" onclick="loja()">Luaj
</div>
This one is the javascript file.
// Create our 'main' state that will contain the game
function loja(){
var mainState = {
preload: function() {
game.load.image('bird', 'assets/car.png');
game.load.image('pipe', 'assets/pipe.png');
game.load.audio('jump', 'assets/jump.wav');
game.load.image('background', 'assets/background.png');
},
create: function() {
game.add.tileSprite(0, 0, 1000, 600, 'background');
// Set the physics system
game.physics.startSystem(Phaser.Physics.ARCADE);
// Display the bird at the position x=100 and y=245
this.bird = game.add.sprite(100, 245, 'bird');
// Add physics to the bird
// Needed for: movements, gravity, collisions, etc.
game.physics.arcade.enable(this.bird);
// Add gravity to the bird to make it fall
this.bird.body.gravity.y = 1000;
// Call the 'jump' function when the spacekey is hit
var spaceKey = game.input.keyboard.addKey(
Phaser.Keyboard.SPACEBAR);
spaceKey.onDown.add(this.jump, this);
// Create an empty group
this.pipes = game.add.group();
this.timer = game.time.events.loop(1500, this.addRowOfPipes, this);
this.score = 0;
this.labelScore = game.add.text(20, 20, "0",
{ font: "30px Arial", fill: "#ffffff" });
// Move the anchor to the left and downward
this.bird.anchor.setTo(-0.2, 0.5);
this.jumpSound = game.add.audio('jump');
},
update: function() {
// If the bird is out of the screen (too high or too low)
// Call the 'restartGame' function
if (this.bird.y < 0 || this.bird.y > 490)
this.restartGame();
game.physics.arcade.overlap(
this.bird, this.pipes, this.hitPipe, null, this);
if (this.bird.angle < 20)
this.bird.angle += 1;
},
// Make the bird jump
jump: function() {
// Add a vertical velocity to the bird
this.bird.body.velocity.y = -300;
// Create an animation on the bird
var animation = game.add.tween(this.bird);
// Change the angle of the bird to -20° in 100 milliseconds
animation.to({angle: -20}, 100);
// And start the animation
animation.start();
if (this.bird.alive == false)
return;
this.jumpSound.play();
},
// Restart the game
restartGame: function() {
// Start the 'main' state, which restarts the game
game.state.start('main');
},
addOnePipe: function(x, y) {
// Create a pipe at the position x and y
var pipe = game.add.sprite(x, y, 'pipe');
// Add the pipe to our previously created group
this.pipes.add(pipe);
// Enable physics on the pipe
game.physics.arcade.enable(pipe);
// Add velocity to the pipe to make it move left
pipe.body.velocity.x = -200;
// Automatically kill the pipe when it's no longer visible
pipe.checkWorldBounds = true;
pipe.outOfBoundsKill = true;
},
addRowOfPipes: function() {
// Randomly pick a number between 1 and 5
// This will be the hole position
var hole = Math.floor(Math.random() * 5) + 1;
// Add the 6 pipes
// With one big hole at position 'hole' and 'hole + 1'
for (var i = 0; i < 8; i++)
if (i != hole && i != hole + 1)
this.addOnePipe(400, i * 60 + 10);
this.score += 1;
this.labelScore.text = this.score;
},
hitPipe: function() {
// If the bird has already hit a pipe, do nothing
// It means the bird is already falling off the screen
if (this.bird.alive == false)
return;
// Set the alive property of the bird to false
this.bird.alive = false;
// Prevent new pipes from appearing
game.time.events.remove(this.timer);
// Go through all the pipes, and stop their movement
this.pipes.forEach(function(p){
p.body.velocity.x = 0;
}, this);
},
};
// Initialize Phaser, and create a 400px by 490px game
var game = new Phaser.Game(600, 800);
// Add the 'mainState' and call it 'main'
game.state.add('main', mainState);
// Start the state to actually start the game
game.state.start('main');
}
Where javascript code appears in your page in this case seems out of point.
You linked it at the end of file? Than it will appear at the end of file.
What I understand you want is your code to interact with some part of a html file structure, called DOM, some DIV tag in particular.
You need to use Javascript to interact with that DIV node. Probably to render your game inside of it.
In your JS file I only see definition and some method calls. I cant see part that would render some content into DOM.
Summarizing: place where your javascript methods definitions are it not the same place where effects of execution of those methods will appear.
It looks like you're trying to implement an open-source Phaser game (https://github.com/photonstorm/phaser/blob/v2.4.4/src/core/Game.js)
Since your issue is with functionality regarding that framework, that should be your starting place for information. Also you shouldn't leave out important information like any framework you're using when asking for help (especially since in this case the issue is only that you're not using the it properly).
If you look at the fourth parameter it actually allows you to specify a DOM parent, it accepts either the ID or the element itself. So you could just do something like this after inserting another element in your HTML with the ID pgame:
var game = new Phaser.Game(600, 800, void(0), 'pgame');

How does the requestAnimationFrame method work in the game 2048?

I found this codepen.io for the game 2048: http://codepen.io/anon/pen/dMzmae
The game is written in JavaScript with a GameManager, HTMLActuator to create the HTML elements, a ScoreManager to keep track of the score and a KeyboardInputManager to track what is pressed and what to do.
The application uses window.requestAnimationFrame to redraw the window. I was wondering how it does that. When the code actuates, it uses the window.requestAnimationFrame() and inside for each cell in the grid it uses the addTile() method to add each tile to the DOM.
HTMLActuator.prototype.actuate = function (grid, metadata) {
var self = this;
window.requestAnimationFrame(function () {
self.clearContainer(self.tileContainer);
grid.cells.forEach(function (column) {
column.forEach(function (cell) {
if (cell) {
self.addTile(cell);
}
});
});
self.updateScore(metadata.score);
if (metadata.over) self.message(false); // You lose
if (metadata.won) self.message(true); // You win!
});
};
If you look at the addTime() method, it too has a window.requestAnimationFrame method that updates the class with the currentPosition if the tile it's adding had a previousPosition property:
HTMLActuator.prototype.addTile = function (tile) {
var self = this;
var element = document.createElement("div");
var position = tile.previousPosition || { x: tile.x, y: tile.y };
positionClass = this.positionClass(position);
// We can't use classlist because it somehow glitches when replacing classes
var classes = ["tile", "tile-" + tile.value, positionClass];
this.applyClasses(element, classes);
element.textContent = tile.value;
if (tile.previousPosition) {
// Make sure that the tile gets rendered in the previous position first
window.requestAnimationFrame(function () {
classes[2] = self.positionClass({ x: tile.x, y: tile.y });
self.applyClasses(element, classes); // Update the position
});
} else if (tile.mergedFrom) {
classes.push("tile-merged");
this.applyClasses(element, classes);
// Render the tiles that merged
tile.mergedFrom.forEach(function (merged) {
self.addTile(merged);
});
} else {
classes.push("tile-new");
this.applyClasses(element, classes);
}
// Put the tile on the board
this.tileContainer.appendChild(element);
};
I guess I'm wondering how does this requestAnimationFrame work to correctly display the tiles when moved? It's building up each tile with the tile information in the grid. Then in addTile() it first uses the tile's previousPosition to build a tile that used to be on the board and creates a class for that position but then it checks if the tile has a previous position and updates the class back to the tile's new position on the grid.
But that only happens in a requestAnimationFrame method for tiles with a previous position and before the method finishes and appends the tile to the tile container in the DOM.
I hope the question makes sense. Are those nested window.RequestAnimationFrame's in the addTile method() called right after the original window.RequestAnimationFrame call in the HTMLActuator.prototype.actuate method so it moves to the new position after an instant and the CSS transition shows it moving?

jquery responsive wordpress slider height change

I have a premium wordpress theme which came with a built in full page slider. It integrates nicely into my website but it displays full page and the information underneath is being lost. The slider is responsive to the window size, I'd like it to be only 60%. Please can someone help:
(function ($) {
"use strict";
$.fn.maximage = function (settings, helperSettings) {
var config;
if (typeof settings == 'object' || settings === undefined) config = $.extend( $.fn.maximage.defaults, settings || {} );
if (typeof settings == 'string') config = $.fn.maximage.defaults;
/*jslint browser: true*/
$.Body = $('body');
$.Window = $(window);
$.Scroll = $('html, body');
$.Events = {
RESIZE: 'resize'
};
this.each(function() {
var $self = $(this),
preload_count = 0,
imageCache = [];
/* --------------------- */
// #Modern
/*
MODERN BROWSER NOTES:
Modern browsers have CSS3 background-size option so we setup the DOM to be the following structure for cycle plugin:
div = cycle
div = slide with background-size:cover
div = slide with background-size:cover
etc.
*/
var Modern = {
setup: function(){
if($.Slides.length > 0){
// Setup images
for(var i in $.Slides) {
// Set our image
var $img = $.Slides[i];
// Create a div with a background image so we can use CSS3's position cover (for modern browsers)
$self.append('<div class="mc-image ' + $img.theclass + '" title="' + $img.alt + '" style="background-image:url(\'' + $img.url + '\');' + $img.style + '" data-href="'+ $img.datahref +'">'+ $img.content +'</div>');
}
// Begin our preload process (increments itself after load)
Modern.preload(0);
// If using Cycle, this resets the height and width of each div to always fill the window; otherwise can be done with CSS
Modern.resize();
}
},
preload: function(n){
// Preload all of the images but never show them, just use their completion so we know that they are done
// and so that the browser can cache them / fade them in smoothly
// Create new image object
var $img = $('<img/>');
$img.load(function() {
// Once the first image has completed loading, start the slideshow, etc.
if(preload_count==0) {
// Only start cycle after first image has loaded
Cycle.setup();
// Run user defined onFirstImageLoaded() function
config.onFirstImageLoaded();
}
// preload_count starts with 0, $.Slides.length starts with 1
if(preload_count==($.Slides.length-1)) {
// If we have just loaded the final image, run the user defined function onImagesLoaded()
config.onImagesLoaded( $self );
}else{
// Increment the counter
preload_count++;
// Load the next image
Modern.preload(preload_count);
}
});
// Set the src... this triggers begin of load
$img[0].src = $.Slides[n].url;
// Push to external array to avoid cleanup by aggressive garbage collectors
imageCache.push($img[0]);
},
resize: function(){
// Cycle sets the height of each slide so when we resize our browser window this becomes a problem.
// - the cycle option 'slideResize' has to be set to false otherwise it will trump our resize
$.Window
.bind($.Events.RESIZE,
function(){
// Remove scrollbars so we can take propper measurements
$.Scroll.addClass('mc-hide-scrolls');
// Set vars so we don't have to constantly check it
$.Window
.data('h', Utils.sizes().h)
.data('w', Utils.sizes().w);
// Set container and slides height and width to match the window size
$self
.height($.Window.data('h')).width($.Window.data('w'))
.children()
.height($.Window.data('h')).width($.Window.data('w'));
// This is special noise for cycle (cycle has separate height and width for each slide)
$self.children().each(function(){
this.cycleH = $.Window.data('h');
this.cycleW = $.Window.data('w');
});
// Put the scrollbars back to how they were
$($.Scroll).removeClass('mc-hide-scrolls');
});
}
}
Thanks in advance. James
Generally, the themes are very customizable on the admin panel. So, you should check it out before you changing it by hand.
If you dont find for customization on the admin panel (and on the theme developer page), as you may be know, when the themes are responsive they are using some framework like bootstrap, foundation, whatever. And then, the slider have to have a css class like "large-12", it should be modified to change its size, for example "large-8", then the slider size will be 8/12.
I hope it help you!

How to send a click event to a div or button with PhantomJS (1.9.8)?

I don't understand how to close a modal or an element with PhanthomJS using sendEvent().
For example I tried to do it using the code below or using CaperJS click and clickLabel and many others things but it's not working.
var webpage = require('webpage').create();
var url = 'http://sourceforge.net/';
webpage.viewportSize = { width: 1280, height: 800 };
webpage.render("test1.png");
webpage.onLoadFinished = function(status) {
var coords = webpage.evaluate(function() {
var firstLink = document.querySelector('a.btn');
return {
x: firstLink.offsetLeft,
y: firstLink.offsetTop
};
});
console.log(coords.x);
console.log(coords.y);
webpage.sendEvent('mousedown', coords.x, coords.y ,'left');
};
webpage.open(url,function(){
webpage.render("test2.png");
phantom.exit()
});
Here is the element I would like to skip.
The offsetLeft and offsetTop only give the offset based on a parent element. You would have to sum all the element offsets up to the root node. That's at least what CasperJS does.
If this notice is static, you can determine the coordinates once and use them every time. Based on the screenshot (444,330) seems good as a replacement for coords.x, coords.y.
You can also simply use a synthentic mouse click as described here which is what CasperJS does, but in combination with a specific position. This is a plain synthetic click:
function click(el){
var ev = document.createEvent("MouseEvent");
ev.initMouseEvent(
"click",
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
false, false, false, false, /* modifier keys */
0 /*left*/, null
);
el.dispatchEvent(ev);
}
Also, you have two callbacks (onLoadFinished and function in webpage.open) for when the page is loaded. You should have only one, so you don't run into problems when when one of them is called. After you click, it's best to wait a little with setTimeout and let the page change before taking the screenshot.

How to load a Google Earth map zoomed in rather than starting from space?

I have a set view to start on when loading the Google Earth API from my website, but it starts from space and then zooms in rather than starting on this zoomed-in view. This is wonky for the viewer particularly because my view is from the north looking south, so the Earth does a whirl on the way in:
http://www.colorado.edu/geography/cartpro/cartography2/fall2011/bartel/projects/project3_tungurahua/tungurahua_hazards.html
The map loads into an iframe. I'd like to toggle between various kmls without changing the zoomed view, as well, but I'll post that question separately. I've looked around for answers but haven't found anything specific to this--if I missed a post about this, I'm happy to check it out if someone can point me in the right direction.
Here's the code:
var ge;
google.load("earth", "1");
function init() {
google.earth.createInstance('map3d', initCB, failureCB);
}
function initCB(instance) {
ge = instance;
ge.getWindow().setVisibility(true);
// set navigation controls
ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
// to fetch a KML file and show it
function finished(object) {
if (!object) {
// wrap alerts in API callbacks and event handlers
// in a setTimeout to prevent deadlock in some browsers
setTimeout(function() {
alert('Bad or null KML.');
}, 0);
return;
}
ge.getFeatures().appendChild(object);
var la = ge.createLookAt('');
la.set(-1.251336, -78.443817, 7000, ge.ALTITUDE_RELATIVE_TO_GROUND,
177, 65, 500);
ge.getView().setAbstractView(la);
}
//var marker = new GMarker(new GLatLng(-1.402002,-78.409471)); // latitude, longitude
// map.addOverlay(marker);
function failureCB(errorCode) {
}
google.setOnLoadCallback(init);
Thanks!!
You can set the fly to speed to SPEED_TELEPORT before loading the abstract view.
This setting will make globe instantaneously fly-to the desired location rather than 'swooping in'. If regular movement should be restored then after you have your initial view you can set the speed back to the default setting.
For example the following function can be used to instantaneously fly-to the desired location.
The method accepts any KmlAbstractView, i.e. a KmlCamera or KmlLookAt as its single parameter.
// fly-to a view using SPEED_TELEPORT
function teleport(abstractView) {
var oldSpeed = ge.getOptions().getFlyToSpeed(); .
ge.getOptions().setFlyToSpeed(ge.SPEED_TELEPORT);
ge.getView().setAbstractView(abstractView); // Wooosh!
ge.getOptions().setFlyToSpeed(oldSpeed);
}
Further to this to make sure that the transition is not shown at all for an initial position you can make the teleport move before setting the GEWindow visibility to True. For example.
function initCB(instance) {
ge = instance;
var la = ge.createLookAt('');
la.set(-1.251336, -78.443817, 7000, ge.ALTITUDE_RELATIVE_TO_GROUND, 177, 65, 500);
teleport(la); // set the position
ge.getWindow().setVisibility(true); // now display the window
//etc..

Categories