Phaser Wont Detect Collision - javascript

I am writing a game in phaser.js where you have to avoid moving spaceships. The mouse is replaced with a UFO. I need help trying to figure out why phaser wont detect the collision between the UFO and the spaceship group. Please excuse the messyness as I have tried a lot of potential solutions.
Code:
var spaceShip;
var score = 0;
var text;
var gameOver = false;
var veggies;
var cursor;
var gameplayState = {
create: function () {
game.add.sprite(0,0,'Stars');
veggies = game.add.group();
veggies.enableBody = true;
veggies.physicsBodyType = Phaser.Physics.ARCADE;
function doSpaceship() {
if (ships == true){
if (ships == false){
kill();
}
if (Math.random() > 0.5){
spaceShip = veggies.create(0, 300, 'Ship');
spaceShip.angle = 90;
game.physics.arcade.collide(veggies, cursor, collisionHandler);
spaceShip.body.velocity.x=1000;
fx.play();
var times = game.time.events.add(Phaser.Timer.SECOND * Math.random() * 3, doSpaceship, this);
var timess = game.time.events.add(Phaser.Timer.SECOND * 1, kill, this);
} else {
spaceShip = veggies.create(Math.random() * 640, 480, 'Ship');
game.physics.arcade.collide(veggies, cursor, collisionHandler);
spaceShip.body.velocity.y=-1000;
gx.play();
var times = game.time.events.add(Phaser.Timer.SECOND * Math.random() * 3, doSpaceship, this);
var timess = game.time.events.add(Phaser.Timer.SECOND * 1, kill, this);
}
}
function kill(){
if(gameOver == false){
score++;
}
spaceShip.destroy();
}
}
cursor = game.add.sprite(0,0,'Ufo');
var ships = true;
text = game.add.text(0,0,"Score: " + score);
text.font = 'Saira Extra Condensed';
doSpaceship();
function collisionHandler(){
gameOver = true;
}
},
update: function(){
cursor.x = game.input.mousePointer.x;
cursor.y = game.input.mousePointer.y;
text.setText("Score: " + score);
}
};

You should move the line
game.physics.arcade.collide(veggies, cursor, collisionHandler);
to the update function.

Related

Ending a p5js game when the score becomes 200

I have made a small trex game, but I'm having a bit trouble here. Whenever the score becomes 300, the game ends. I am not sure how I'm supposed to do that. What I have tried is making an if condition and giving it score === and score = 200, the game should end. Thanks.
(Also I wrote this code 7 months ago I am just working on some improvements here)
var trex, trex_running, trex_collided;
var ground, invisibleGround, groundImage;
var PLAY = 1;
var END = 0;
var gameState = PLAY;
var gameOver, restart, gameOverImage, restartImage;
var score = 0;
var cloudsGroup, cloudImage;
var obstaclesGroup, obstacle1, obstacle2, obstacle3, obstacle4, obstacle5, obstacle6;
//var score;
function preload() {
trex_running = loadAnimation("Screen Shot 2021-04-05 at 8.47.52 PM.png");
trex_collided = loadImage("trex_collided.png");
restartImage = loadImage("restart.png");
gameOverImage = loadImage("gameOver.png");
groundImage = loadImage("ground2.png");
cloudImage = loadImage("cloud.png");
obstacle1 = loadImage("obstacle1.png");
obstacle2 = loadImage("obstacle2.png");
obstacle3 = loadImage("obstacle3.png");
obstacle4 = loadImage("obstacle4.png");
obstacle5 = loadImage("obstacle5.png");
obstacle6 = loadImage("obstacle6.png");
}
function setup() {
createCanvas(600, 200);
trex = createSprite(50, 180, 20, 50);
trex.addAnimation("running", trex_running);
trex.scale = 0.1;
ground = createSprite(200, 180, 400, 20);
ground.addImage("ground", groundImage);
ground.x = ground.width / 2;
ground.velocityX = -(4 + 3 * score / 100);
invisibleGround = createSprite(200, 190, 400, 10);
invisibleGround.visible = false;
cloudsGroup = new Group();
obstaclesGroup = new Group();
gameOver = createSprite(300, 100, 10, 10);
gameOver.addImage(gameOverImage);
gameOver.scale = 0.5;
gameOver.visible = false;
restart = createSprite(300, 140, 10, 10);
restart.addImage(restartImage);
restart.scale = 0.5
restart.visible = false;
}
function draw() {
background("white");
text("Score: " + score, 500, 50);
if (gameState == PLAY) {
score = score + Math.round(getFrameRate() / 60);
if (keyDown("space")) {
trex.velocityY = -10;
}
trex.velocityY = trex.velocityY + 0.8
if (ground.x < 0) {
ground.x = ground.width / 2;
}
trex.collide(invisibleGround);
spawnClouds();
spawnObstacles();
if (obstaclesGroup.isTouching(trex)) {
gameState = END;
}
} else if (gameState === END) {
gameOver.visible = true;
restart.visible = true;
//set velcity of each game object to 0
ground.velocityX = 0;
trex.velocityY = 0;
obstaclesGroup.setVelocityXEach(0);
cloudsGroup.setVelocityXEach(0);
//change the trex animation
trex.addAnimation("trex_collided", trex_collided);
//set lifetime of the game objects so that they are never destroyed
obstaclesGroup.setLifetimeEach(-1);
cloudsGroup.setLifetimeEach(-1);
}
if (mousePressedOver(restart)) {
reset();
}
textSize(22);
text('Mrs K, survive all the obstacles, and save the students!', 10, 30);
drawSprites();
}
function spawnClouds() {
//write code here to spawn the clouds
if (frameCount % 60 === 0) {
var cloud = createSprite(600, 120, 40, 10);
cloud.y = Math.round(random(80, 120));
cloud.addImage(cloudImage);
cloud.scale = 0.5;
cloud.velocityX = -3;
//assign lifetime to the variable
cloud.lifetime = 200;
//adjust the depth
cloud.depth = trex.depth;
trex.depth = trex.depth + 1;
//add each cloud to the group
cloudsGroup.add(cloud);
}
}
function spawnObstacles() {
if (frameCount % 60 === 0) {
var obstacle = createSprite(600, 165, 10, 40);
obstacle.velocityX = -(4 + 3 * score / 100);
//generate random obstacles
var rand = Math.round(random(1, 6));
switch (rand) {
case 1:
obstacle.addImage(obstacle1);
break;
case 2:
obstacle.addImage(obstacle2);
break;
case 3:
obstacle.addImage(obstacle3);
break;
case 4:
obstacle.addImage(obstacle4);
break;
case 5:
obstacle.addImage(obstacle5);
break;
case 6:
obstacle.addImage(obstacle6);
break;
default:
break;
}
//assign scale and lifetime to the obstacle
obstacle.scale = 0.5;
obstacle.lifetime = 300;
//add each obstacle to the group
obstaclesGroup.add(obstacle);
}
}
function reset() {
gameState = PLAY;
gameOver.visible = false;
restart.visible = false;
obstaclesGroup.destroyEach();
cloudsGroup.destroyEach();
trex.addAnimation("trex", trex_running);
score = 0;
}
Have you tried it in your draw function? You could do something like,
if (mousePressedOver(restart) || score >= 200) {
reset();
}

Converting jquery controls to javascript

So i am trying to implement simple touch controls on a javascript game. I have the following answer from a search:
Snake Game with Controller Buttons for Mobile Use **UPDATED**
However I was trying to change this jquery into javascript so that it would work with my game
Jquery:
$(document).on('click', '.button-pad > button', function(e) {
if ($(this).hasClass('left-btn')) {
e = 37;
}
Javascript:
var contoller = document.getElementById("button-pad").on('click',
'.button-pad > button', function(e) {
if ('.button-pad > button'(this).hasClass('btn-left')) {
e = 37;
}
I thought I had it sorted but it is not working at all
Codepen here:
https://codepen.io/MrVincentRyan/pen/VqpMrJ?editors=1010
Your existing code has some problems with it, but it was close enough where I could translate it. However, your current code seems to want to reassign the event argument being passed to the click handler (e) to 37. This makes no sense. Most likely you just want another variable set to 37 and that's what I've done below:
spaceInvader(window, document.getElementById('space-invader'));
window.focus();
let game = null;
let ship = null;
function spaceInvader (window, canvas) {
canvas.focus();
var context = canvas.getContext('2d');
/* GAME */
function Game () {
this.message = '';
this.rebel = [];
this.republic = [];
this.other = [];
this.size = {x: canvas.width, y: canvas.height};
this.wave = 0;
this.refresh = function () {
this.update();
this.draw();
requestAnimationFrame(this.refresh);
}.bind(this);
this.init();
}
Game.MESSAGE_DURATION = 1500;
Game.prototype.init = function () {
this.ship = new Ship(this);
this.addRebel(this.ship);
this.refresh();
};
Game.prototype.update = function () {
this.handleCollisions();
this.computeElements();
this.elements.forEach(Element.update);
if (!this.rebel.length) {
this.showText('Gatwick closed', true);
return;
}
if (!this.republic.length) this.createWave();
};
Game.prototype.draw = function () {
context.clearRect(0, 0, this.size.x, this.size.y);
this.elements.forEach(Element.draw);
Alien.drawLife(this.republic);
if (this.message) {
context.save();
context.font = '30px Arial';
context.textAlign='center';
context.fillStyle = '#FFFFFF';
context.fillText(this.message, canvas.width / 2, canvas.height / 2);
context.restore();
}
};
Game.prototype.computeElements = function () {
this.elements = this.other.concat(this.republic, this.rebel);
};
Game.prototype.addRebel = function (element) {
this.rebel.push(element);
};
Game.prototype.addRepublic = function (element) {
this.republic.push(element);
};
Game.prototype.addOther = function (element) {
this.other.push(element);
};
Game.prototype.handleCollisions = function () {
this.rebel.forEach(function(elementA) {
this.republic.forEach(function (elementB) {
if (!Element.colliding(elementA, elementB)) return;
elementA.life--;
elementB.life--;
var sizeA = elementA.size.x * elementA.size.y;
var sizeB = elementB.size.x * elementB.size.y;
this.addOther(new Explosion(this, sizeA > sizeB ? elementA.pos : elementB.pos));
}, this);
}, this);
this.republic = this.republic.filter(Element.isAlive);
this.rebel = this.rebel.filter(Element.isAlive);
this.other = this.other.filter(Element.isAlive);
this.republic = this.republic.filter(this.elementInGame, this);
this.rebel = this.rebel.filter(this.elementInGame, this);
};
Game.prototype.elementInGame = function (element) {
return !(element instanceof Bullet) || (
element.pos.x + element.halfWidth > 0 &&
element.pos.x - element.halfWidth < this.size.x &&
element.pos.y + element.halfHeight > 0 &&
element.pos.y - element.halfHeight < this.size.x
);
};
Game.prototype.createWave = function () {
this.ship.life = Ship.MAX_LIFE;
this.ship.fireRate = Math.max(50, Ship.FIRE_RATE - 50 * this.wave);
this.wave++;
this.showText('Wave: ' + this.wave);
var waveSpeed = Math.ceil(this.wave / 2);
var waveProb = (999 - this.wave * 2) / 1000;
var margin = {x: Alien.SIZE.x + 10, y: Alien.SIZE.y + 10};
for (var i = 0; i < 2; i++) {
var x = margin.x + (i % 8) * margin.x;
var y = -200 + (i % 3) * margin.y;
this.addRepublic(new Alien(this, {x: x, y: y}, waveSpeed, waveProb));
}
};
Game.prototype.showText = function (message, final) {
this.message = message;
if (!final) setTimeout(this.showText.bind(this, '', true), Game.MESSAGE_DURATION);
};
/* GENERIC ELEMENT */
function Element (game, pos, size) {
this.game = game;
this.pos = pos;
this.size = size;
this.halfWidth = Math.floor(this.size.x / 2);
this.halfHeight = Math.floor(this.size.y / 2);
}
Element.update = function (element) {
element.update();
};
Element.draw = function (element) {
element.draw();
};
Element.isAlive = function (element) {
return element.life > 0;
};
Element.colliding = function (elementA, elementB) {
return !(
elementA === elementB ||
elementA.pos.x + elementA.halfWidth < elementB.pos.x - elementB.halfWidth ||
elementA.pos.y + elementA.halfHeight < elementB.pos.y - elementB.halfHeight ||
elementA.pos.x - elementA.halfWidth > elementB.pos.x + elementB.halfWidth ||
elementA.pos.y - elementA.halfHeight > elementB.pos.y + elementB.halfHeight
);
};
/* SHIP */
function Ship(game) {
var pos = {
x: Math.floor(game.size.x / 2) - Math.floor(Ship.SIZE.x / 2),
y: game.size.y - Math.floor(Ship.SIZE.y / 2)
};
Element.call(this, game, pos, Ship.SIZE);
this.kb = new KeyBoard();
this.speed = Ship.SPEED;
this.allowShooting = true;
this.life = Ship.MAX_LIFE;
this.fireRate = Ship.FIRE_RATE;
}
Ship.SIZE = {x: 67, y: 100};
Ship.SPEED = 8;
Ship.MAX_LIFE = 5;
Ship.FIRE_RATE = 200;
Ship.prototype.update = function () {
if (this.kb.isDown(KeyBoard.KEYS.LEFT) && this.pos.x - this.halfWidth > 0) {
this.pos.x -= this.speed;
} else if (this.kb.isDown(KeyBoard.KEYS.RIGHT) && this.pos.x + this.halfWidth < this.game.size.x) {
this.pos.x += this.speed;
}
if (this.allowShooting && this.kb.isDown(KeyBoard.KEYS.SPACE)) {
var bullet = new Bullet(
this.game,
{x: this.pos.x, y: this.pos.y - this.halfHeight },
{ x: 0, y: -Bullet.SPEED },
true
);
this.game.addRebel(bullet);
this.toogleShooting();
}
};
Ship.prototype.draw = function () {
var img = document.getElementById('ship');
context.save();
context.translate(this.pos.x - this.halfWidth, this.pos.y - this.halfHeight);
context.drawImage(img, 0, 0);
context.restore();
this.drawLife();
};
Ship.prototype.drawLife = function () {
context.save();
context.fillStyle = 'white';
context.fillRect(this.game.size.x -112, 10, 102, 12);
context.fillStyle = 'red';
context.fillRect(this.game.size.x -111, 11, this.life * 100 / Ship.MAX_LIFE, 10);
context.restore();
};
Ship.prototype.toogleShooting = function (final) {
this.allowShooting = !this.allowShooting;
if (!final) setTimeout(this.toogleShooting.bind(this, true), this.fireRate);
};
/* ALIENS */
function Alien(game, pos, speed, shootProb) {
Element.call(this, game, pos, Alien.SIZE);
this.speed = speed;
this.shootProb = shootProb;
this.life = 3;
this.direction = {x: 1, y: 1};
}
Alien.SIZE = {x: 51, y: 60};
Alien.MAX_RANGE = 350;
Alien.CHDIR_PRO = 0.990;
Alien.drawLife = function (array) {
array = array.filter(function (element) {
return element instanceof Alien;
});
context.save();
context.fillStyle = 'white';
context.fillRect(10, 10, 10 * array.length + 2, 12);
array.forEach(function (alien, idx) {
switch (alien.life) {
case 3:
context.fillStyle = 'green';
break;
case 2:
context.fillStyle = 'yellow';
break;
case 1:
context.fillStyle = 'red';
break;
}
context.fillRect(10 * idx + 11, 11, 10, 10);
});
context.restore();
};
Alien.prototype.update = function () {
if (this.pos.x - this.halfWidth <= 0) {
this.direction.x = 1;
} else if (this.pos.x + this.halfWidth >= this.game.size.x) {
this.direction.x = -1;
} else if (Math.random() > Alien.CHDIR_PRO) {
this.direction.x = -this.direction.x;
}
if (this.pos.y - this.halfHeight <= 0) {
this.direction.y = 1;
} else if (this.pos.y + this.halfHeight >= Alien.MAX_RANGE) {
this.direction.y = -1;
} else if (Math.random() > Alien.CHDIR_PRO) {
this.direction.y = -this.direction.y;
}
this.pos.x += this.speed * this.direction.x;
this.pos.y += this.speed * this.direction.y;
if (Math.random() > this.shootProb) {
var bullet = new Bullet(
this.game,
{x: this.pos.x, y: this.pos.y + this.halfHeight },
{ x: Math.random() - 0.5, y: Bullet.SPEED },
false
);
this.game.addRepublic(bullet);
}
};
Alien.prototype.draw = function () {
var img = document.getElementById('fighter');
context.save();
context.translate(this.pos.x + this.halfWidth, this.pos.y + this.halfHeight);
context.rotate(Math.PI);
context.drawImage(img, 0, 0);
context.restore();
};
/* BULLET */
function Bullet(game, pos, direction, isRebel) {
Element.call(this, game, pos, Bullet.SIZE);
this.direction = direction;
this.isRebel = isRebel;
this.life = 1;
try {
var sound = document.getElementById('sound-raygun');
sound.load();
sound.play().then(function () {}, function () {});
}
catch (e) {
// only a sound issue
}
}
Bullet.SIZE = {x: 6, y: 20};
Bullet.SPEED = 3;
Bullet.prototype.update = function () {
this.pos.x += this.direction.x;
this.pos.y += this.direction.y;
};
Bullet.prototype.draw = function () {
context.save();
var img;
if (this.isRebel) {
context.translate(this.pos.x - this.halfWidth, this.pos.y - this.halfHeight);
img = document.getElementById('rebel-bullet');
}
else {
context.translate(this.pos.x + this.halfWidth, this.pos.y + this.halfHeight);
img = document.getElementById('republic-bullet');
context.rotate(Math.PI);
}
context.drawImage(img, 0, 0);
context.restore();
};
/* EXPLOSION */
function Explosion(game, pos) {
Element.call(this, game, pos, Explosion.SIZE);
this.life = 1;
this.date = new Date();
try {
var sound = document.getElementById('sound-explosion');
sound.load();
sound.play().then(function () {}, function () {});
}
catch (e) {
// only a sound issue
}
}
Explosion.SIZE = {x: 115, y: 100};
Explosion.DURATION = 150;
Explosion.prototype.update = function () {
if (new Date() - this.date > Explosion.DURATION) this.life = 0;
};
Explosion.prototype.draw = function () {
var img = document.getElementById('explosion');
context.save();
context.translate(this.pos.x - this.halfWidth, this.pos.y - this.halfHeight);
context.drawImage(img, 0, 0);
context.restore();
};
/* KEYBOARD HANDLING */
function KeyBoard() {
var state = {};
window.addEventListener('keydown', function(e) {
state[e.keyCode] = true;
});
window.addEventListener('keyup', function(e) {
state[e.keyCode] = false;
});
this.isDown = function (key) {
return state[key];
};
}
KeyBoard.KEYS = {
LEFT: 37,
RIGHT: 39,
SPACE: 32
};
window.addEventListener('load', function() {
game = new Game();
});
// Get all the button elements that are children of elements that have
// the .button-pad class and convert the resulting node list into an Array
let elements =
Array.prototype.slice.call(document.querySelectorAll('.button-pad button'));
// Loop over the array
elements.forEach(function(el){
el.textContent = "XXXX";
// Set up a click event handler for the current element being iterated:
el.addEventListener('click', function(e) {
// When the element is clicked, check to see if it uses the left-btn class
if(this.classList.contains('left-btn')) {
// Perform whatever actions you need to:
ship.update();
}
});
});
}
<h1>Gatwick invaders</h1>
<p>Press <b>left arrow</b> to go left, <b>right arrow</b> to go right, and <b>space</b> to shoot...</p>
<canvas id="space-invader" width="640" height="500" tabindex="0"></canvas>
<img id="fighter" src="https://raw.githubusercontent.com/MrVIncentRyan/assets/master/drone1.png" />
<img id="ship" src="https://raw.githubusercontent.com/MrVIncentRyan/assets/master/cop1.png" />
<img id="rebel-bullet" src="https://raw.githubusercontent.com/OlivierB-OB/starwars-invader/master/rebelBullet.png" />
<img id="republic-bullet" src="https://raw.githubusercontent.com/OlivierB-OB/starwars-invader/master/republicBullet.png" />
<img id="explosion" src="https://raw.githubusercontent.com/OlivierB-OB/starwars-invader/master/explosion.png" />
<audio id="sound-explosion" src="https://raw.githubusercontent.com/OlivierB-OB/starwars-invader/master/explosion.mp3"></audio>
<audio id="sound-raygun" src="https://raw.githubusercontent.com/OlivierB-OB/starwars-invader/master/raygun.mp3"></audio>
</div>
<div class="button-pad">
<div class="btn-up">
<button type="submit" class="up">
<img src="http://aaronblomberg.com/sites/ez/images/btn-up.png" />
</button>
</div>
<div class="btn-right">
<button type="submit" class="right">
<img src="http://aaronblomberg.com/sites/ez/images/btn-right.png" />
</button>
</div>
<div class="btn-down">
<button type="submit" class="down">
<img src="http://aaronblomberg.com/sites/ez/images/btn-down.png" />
</button>
</div>
<div class="btn-left">
<button type="submit" class="left">
<img src="http://aaronblomberg.com/sites/ez/images/btn-left.png" />
</button>
</div>
</div>
A custom solution for emulating keypresses on mobile in both vanilla Javascript as well as jQuery!
// jQuery (edge), for use with ES2015-19
/*
$(document).on("click", ".example-btn", e => { // Click event handler
if($(this).hasClass("example-btn")) { // Verifying that element has class
e = 37
jQuery.event.trigger({type: "keypress", which: character.charCodeAt(e)}) // Simulating keystroke
// The following is simply for debugging, remove if needed
alert("Button validation confirmed!")
console.log("E: ", e)
}
})
*/
// Pure Javascript (ECMA Standard)
document.querySelector(".example-btn").addEventListener("click", function(e) { // Click event handler
if(this.classList.contains("example-btn")) { // Verifying that element has class
e = 37
if(document.createEventObject) {
var eventObj = document.createEventObject();
eventObj.keyCode = e;
document.querySelector(".example-btn").fireEvent("onkeydown", eventObj);
} else if(document.createEvent) {
var eventObj2 = document.createEvent("Events");
eventObj2.initEvent("keydown", true, true);
eventObj2.which = e;
document.querySelector(".example-btn").dispatchEvent(eventObj2);
}
// The following is simply for debugging, remove if needed
alert("Button validation confirmed!");
console.log("E: ", e);
}
});
// ---------------------------------------------------------------------------------------------------
/*
You can not use the "this" statement when referring to an embedded element. In your previous code "this" would refer to ".button-container > .example-btn" which the compiler will interpret as only the parent element, being .button-container (.button-pad in your code) not the child element in which you want. Also there is no such thing as returning a character code and expecting it to automatically know what to do with it. I assume you are doing this to emulate a keystroke on a mobile device and I assure you that this design works although it might be flawed. Give it a try and I hope it does something to at least help if not solve your problem.
*/
// ---------------------------------------------------------------------------------------------------
When an event listener is attached to an element, that listener is not unique for the element, but it propagates to its children.
This functionality is enabled in jQuery by adding a parameter on an event listener a parameter that targets the element that we want.
This is not case in vanillaJS, but using e.target we can inspect in which elements the event is executed.
Probably your are looking something like this. However, I would prefer to add an id in the button so you can more easily work with it.
document.addEventListener('click', function(e){
if(e.target.tagName === 'BUTTON' && e.target.classList.value.includes('btn-left')){
// execute your code
}
});

Improving Existing Horizontal "Roulette" Scroller

I created a prototype for a horizontal scroller which will select a winner in an animated fashion. I am looking to improve this by programmatically highlighting the selected image under the indicator. I have figured out how to get it to scroll where I want, but I cannot figure out how to programmatically select the image after it's won.
Currently using:
HTML
CSS
jQuery
GSAP TimeLineMax
Working Example: http://codepen.io/ByteKnight13/pen/950a1a0d277fc0204d1827120bdcc090/
Current Code:
if (!String.prototype.format) {
String.prototype.format = function () {
var args = arguments;
return this.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match;
});
};
}
$(window).load(function () {
console.log('Window loaded!');
var $roulette = $('#roulette-images-list');
$roulette.html(generateRouletteImages(200));
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getPositionOfWinner(winner) {
var widthOfImg = $('#roulette-img0').width();
var minDistanceToEdgeAllowed = 4;
var desiredImg = $('#roulette-img' + winner.toString());
var minPos = desiredImg.position().left + minDistanceToEdgeAllowed;
var maxPos = desiredImg.position().left + widthOfImg - minDistanceToEdgeAllowed;
console.log('Position.Left: {0} | Offset().left: {1}'.format(desiredImg.position().left, desiredImg.offset().left));
return getRandomInt(minPos, maxPos);
}
function printLeftOfRouletteSpinner() {
var pos = $('#roulette-images-list').position().left;
if (pos % 100 == 0) console.log(pos);
}
function rouletteSpin(destImg) {
if (!destImg) destImg = 40;
var tl = new TimelineMax({onUpdate: printLeftOfRouletteSpinner}),
rouletteImages = $('#roulette-images-list'),
startLeft = rouletteImages.position().left;
tl//.to(rouletteImages, 0, {x: 5000})
.to(rouletteImages, 10, {x: getPositionOfWinner(destImg) * -1, ease:Power4.easeOut})
.to(rouletteImages, 0, {x: 0}, 11);
}
$('#spin').click(function () {
var winner = $('#winner-text').val();
//if (isNaN(winner) || winner > 49) alert('Enter 0 through 49');
rouletteSpin(winner);
});
function getRandomColor() {
return ((1 << 24) * Math.random() | 0).toString(16)
}
function generateRouletteImages(howMany) {
var imgTemplate = '<img src="{0}" class="{1}" id="roulette-img{2}">';
var imgClass = 'roulette-img';
var imgSrcTemplate = 'http://placehold.it/{0}/{1}?text={2}';
var completedRouletteImages = [];
for (var i = 0; i < howMany; i++) {
var color = getRandomColor();
var imgSrc = imgSrcTemplate.format('80', color, i);
var completedTemplate = imgTemplate.format(imgSrc, imgClass, i);
completedRouletteImages.push('<li>' + completedTemplate + '</li>');
}
return completedRouletteImages;
}
});
There is an onComplete parameter on TimelineMax. Combining that with the onCompleteParams parameter, you can pass the winner image reference to the onComplete callback.
new TimelineMax({
onComplete: timelineFinished,
onCompleteParams: [ destImg ]
})
function timelineFinished(destImg){
// this is where you highlight your winner
$('#roulette-img' + destImg).css({
border: '3px solid red'
});
}
Also, the roulette was resetting after to completed the spin, so I removed the last: .to(rouletteImages, 0, {x: 0}, 11)
Its a pretty rough selection, but you can clean it up with some CSS or whatever you are trying to achieve.
Working Example:
http://codepen.io/kingkode/pen/EyKwJW

Null Reference after restarting a State

I created a little game with Phaser for presentation purposes. After you've won or lost you can restart the game. This is done with states. When I try to fire a bullet after the game has been restarted, a null reference error occurs and the game freezes. It seems the null reference occurs because the this.game property is not set correctly in the Weapon classes after the state is restarted.
var PhaserGame = function () {
this.background = null;
this.stars = null;
this.player = null;
this.enemies = null;
this.cursors = null;
this.speed = 300;
this.weapons = [];
this.currentWeapon = 0;
this.weaponName = null;
this.score = 0;
};
PhaserGame.prototype = {
init: function () {
this.game.renderer.renderSession.roundPixels = true;
this.physics.startSystem(Phaser.Physics.ARCADE);
},
preload: function () {
this.game.time.advancedTiming = true;
},
create: function () {
this.background = this.add.tileSprite(0, 0, this.game.width, this.game.height, 'background');
this.background.autoScroll(-40, 0);
this.stars = this.add.tileSprite(0, 0, this.game.width, this.game.height, 'stars');
this.stars.autoScroll(-60, 0);
this.weapons.push(new Weapon.SingleBullet(this.game));
//this.weapons.push(new Weapon.FrontAndBack(this.game));
this.weapons.push(new Weapon.ThreeWay(this.game));
//this.weapons.push(new Weapon.EightWay(this.game));
this.weapons.push(new Weapon.ScatterShot(this.game));
this.weapons.push(new Weapon.Beam(this.game));
this.weapons.push(new Weapon.SplitShot(this.game));
//this.weapons.push(new Weapon.Pattern(this.game));
this.weapons.push(new Weapon.Rockets(this.game));
this.weapons.push(new Weapon.ScaleBullet(this.game));
//this.weapons.push(new Weapon.Combo1(this.game));
//this.weapons.push(new Weapon.Combo2(this.game));
this.currentWeapon = 0;
for (var i = 1; i < this.weapons.length; i++)
{
this.weapons[i].visible = false;
}
this.player = this.add.existing(new Spaceship(this.game, 100, 200, 'player'));
this.player.events.onKilled.add(this.toGameOver, this);
this.physics.arcade.enable(this.player);
this.player.body.collideWorldBounds = true;
this.player.animations.add('flame', [0, 1, 2, 3], 10, true);
this.player.animations.play('flame');
//Enemies
this.enemies = this.add.group();
//Enable Physics for Enemies
//this.physics.arcade.enable(this.enemies);
this.enemies.enableBody = true;
for (var i = 0; i < 24; i++) {
//create a star inside the group
var enemy = this.enemies.add(new Enemy(this.game, 1000 + (i * 50), 10 + Math.random() * 300, 'enemy'));
enemy.events.onKilled.add(this.raiseCounter, this);
}
//this.weaponName = this.add.bitmapText(8, 364, 'shmupfont', "ENTER = Next Weapon", 24);
// Cursor keys to fly + space to fire
this.cursors = this.input.keyboard.createCursorKeys();
this.input.keyboard.addKeyCapture([ Phaser.Keyboard.SPACEBAR ]);
var changeKey = this.input.keyboard.addKey(Phaser.Keyboard.ENTER);
changeKey.onDown.add(this.nextWeapon, this);
},
nextWeapon: function () {
// Tidy-up the current weapon
this.weapons[this.currentWeapon].visible = false;
this.weapons[this.currentWeapon].callAll('reset', null, 0, 0);
this.weapons[this.currentWeapon].setAll('exists', false);
// Activate the new one
this.currentWeapon++;
if (this.currentWeapon === this.weapons.length)
{
this.currentWeapon = 0;
}
this.weapons[this.currentWeapon].visible = true;
//this.weaponName.text = this.weapons[this.currentWeapon].name;
},
enemyHit: function (bullet, enemy) {
bullet.kill();
enemy.dealDamage(2);
},
playerHit: function (player, enemy) {
player.dealDamage(10);
enemy.dealDamage(1);
},
raiseCounter: function () {
this.score++;
},
toGameOver: function () {
this.game.state.start('GameOver', true, false, this.score);
},
update: function () {
//Framerate
this.game.debug.text(this.time.fps || '--', 2, 14, "#00ff00");
this.game.debug.text('Health: ' + this.player.health || 'Health: ---', 2, 30, "#00ff00");
this.game.debug.text('Counter: ' + this.score || 'Counter: ---', 2, 44, "#00ff00");
this.game.physics.arcade.overlap(this.weapons[this.currentWeapon], this.enemies, this.enemyHit, null, this);
this.game.physics.arcade.overlap(this.player, this.enemies, this.playerHit, null, this);
this.player.body.velocity.set(0);
this.enemies.setAll('body.velocity.x', -50);
if (this.cursors.left.isDown)
{
this.player.body.velocity.x = -this.speed;
}
else if (this.cursors.right.isDown)
{
this.player.body.velocity.x = this.speed;
}
if (this.cursors.up.isDown)
{
this.player.body.velocity.y = -this.speed;
}
else if (this.cursors.down.isDown)
{
this.player.body.velocity.y = this.speed;
}
if (this.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR))
{
this.weapons[this.currentWeapon].fire(this.player);
}
}
};
The weapon-classes were taken from Phaser-Coding-Tips 7:
Weapon.SingleBullet = function (game) {
console.log(game);
Phaser.Group.call(this, game, game.world, 'Single Bullet', false, true, Phaser.Physics.ARCADE);
this.nextFire = 0;
this.bulletSpeed = 600;
this.fireRate = 200;
for (var i = 0; i < 64; i++)
{
this.add(new Bullet(game, 'bullet5'), true);
}
return this;
};
Weapon.SingleBullet.prototype = Object.create(Phaser.Group.prototype);
Weapon.SingleBullet.prototype.constructor = Weapon.SingleBullet;
Weapon.SingleBullet.prototype.fire = function (source) {
//Here occurs the problem, because this.game is null after restarting the state
if (this.game.time.time < this.nextFire) { return; }
var x = source.x + 50;
var y = source.y + 15;
this.getFirstExists(false).fire(x, y, 0, this.bulletSpeed, 0, 0);
this.nextFire = this.game.time.time + this.fireRate;
};
The problem occurs consistent in all Weapon classes after restarting the state.
In the beginning of the create-method before weapons is filled, i forgot to empty the array. The funny thing is: I tried emptying the array before and it didn't work. When i logged the length of weapons it suddenly started to work as expected. Maybe the cause was a strange optimization made by the javascript-engine.

Javascript replay user input

I'm trying to capture user input (jquery event objects) in a captured array. I am tacking a t property on to the event, which is each event's elapsed time from the start of recording. Then I want to walk back through that array, using a setTimeout within a closure in a for loop in order to trigger those events with the same timing as user input.
I just don't understand why the animations won't play on the way back... !??!
Please, if anyone has insight into this... HELP!
$(function() {
var dancer = document.getElementById('dancer');
var $dancer = $(dancer);
var dancerContainer = document.querySelector('.dancer-container');
var $dancerContainer = $(dancerContainer);
var count = 3;
var captured = [];
var countInterval;
function replayDance(captured) {
for (i = 0; i < captured.length; i++) {
e = captured[i];
t = e.t;
setTimeout((function (e) {
return function () {
// $dancer.trigger(e.type);
// this should be
$dancer.trigger(e.originalEvent);
};
})(e), t);
}
}
function countdown() {
console.log(count);
--count;
if (count == 0) {
console.log('recording')
captureInput();
clearInterval(countInterval);
count = 3;
}
}
function captureInput() {
var mouseCapture = [];
var keyCapture = [];
var start = new Date().getTime();
$(document).on('mousemove.capture', function(event) {
event.t = new Date().getTime() - start;
captured.push(event);
});
$(document).on('keyup.capture', function(event) {
event.t = new Date().getTime() - start;
captured.push(event);
});
setTimeout(function() {
console.log('finished capturing');
$(document).off('.capture');
}, 3000);
}
function followMouse(event) {
var width = $(window).width();
var height = $(window).height();
var mouseX = event.pageX - (width * 0.25);
var mouseY = event.pageY - (height * 0.25);
var angleX = (mouseY / height) * 45;
var angleY = (mouseX / width) * 45;
dancer.style.webkitTransform = "rotateX(" + angleX + "deg) rotateY(" + angleY + "deg)";
console.log(dancer.style.webkitTransform);
}
function resize() {
var y = ($(window).height() - 250) * 0.5;
$("#box").css('margin-top', y + 'px');
}
function triggerAnimation(el, klassName) {
el.stop(true, false).addClass(klassName).one('webkitAnimationEnd', function() { el.removeClass(klassName) });
}
$(document).on('keyup', function(event) {
switch (event.which) {
case 49:
triggerAnimation($dancerContainer, 'shake');
break;
case 50:
triggerAnimation($dancerContainer, 'bounce');
break;
case 51:
triggerAnimation($dancerContainer, 'swing');
break;
case 52:
triggerAnimation($dancerContainer, 'wobble');
break;
}
});
$('#button-record').on('click', function(e) {
countInterval = setInterval(countdown, 1000);
});
$('#button-replay').on('click', function(e) {
if (captured.length) {
replayDance(captured);
} else {
console.log('nothing captured!');
}
})
$(window).on('resize', resize);
$(document).ready(resize);
$(document).on('mousemove', followMouse);
});
I needed to trigger the originalEvent attached to the Event object, rather than trying to trigger the e.type again. Corrected the offending line of code in my post.

Categories

Resources