I am making a flappy bird game using phaser.js.
My problem is that it doesn't collide with the ledges. And how do you change the camera (you know in flappy bird they like move the camera)?
Any other tips on making my game would be greatly appreciated!
JSFiddle
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-demo', {
preload: preload,
create: create,
update: update,
render: render
});
var player;
var starfield;
var cursors;
var fireButton;
var gameOver;
var upLedge;
var vaRandomUpLedgeSize;
var bottomLedge;
function preload() {
game.load.image('starfield', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJAAAAEACAYAAABcV/9PAAAEWklEQVR42u3ZsW7UShSA4XltxAMgxGPwHHSwRSQaKpR0FCDRQY+AgAzeiccej8fesf0Vn8Llru2zJ//aubnh+bv3P6FUsAQEhIAQEAICASEgBISAQEAIiJYDevv7D1BIQAgIASEgBAQCQkDsKCC/DMNvohEQAkJAICAEhIAQEAgIASEgBAQCQkAICAGBgBAQAkJACAgEhIAQEAICASEgBISAQEAICAEhIBAQAkJACAgBgYAQEAJCQCAgBISAEBAICAEhIAQEAkJACAgBISBLQEAICAEhIBAQAkJACAgEhIAQEAICASEgBISAQEAICAEhIAQEAkJACAgBgYAQEAJCQCAgBISAEBAICAEhIASEgEBACAgBISAQEAJCQAgIBISAEBACAgEhIASEgEBACAgBISAEBAJCQAgIAYGAEBACQkAgIASEgBAQCAgBISAEhIBAQAgIATHD1x8PgwREUTh7Cykc9ZPR6t0iN5y97D0c9ZNxi7vF1F5K42l552FPn4ytZ6j5zV4aT+p93vr7EvbwyVhjjqlz1PiGd+erda6S+db8gD7+u1D7jbVwB1jzMbJXtT+g3d+FrYbc8vGx1iPkaBHVOGeTAd3qdn+miGqdL2xxq6zxWtq0akBrHsNBA0JAICAEhICuvfly+ef1x/snzjbHEXayeUAP3+/+eByq+3P3z2eb4wg7WRTQp28fnki9dqjqx+G6wZcsq5U5zriTUGu4nCH7VcdKltXKHGfeSZj7vE0NN1Rx/7xx1fHXuc/+VuY4+07CnNvlWN1DFXc/kOUOmTtLK3PYSXQHmio+Z8j+D2NDQ47dJnNnaWUOO7n/fwcaOih+fs65NZbcJnNmaWUOO/lrcUCpavu/U9hiWVvPYSdRQEMH5SwrdXx/yKk3FA85Nksrc9jJZbuAuq+3XlbNOezkst4jLPW83fp2veYcdrLiIywevv93OUPW+rStOYedzHyEpf7zcGzIscGXPDpaneOMO8l+hOX+gqr/P+OmBi99dLQ6xxl3ErqDh752wzy7e3El/l1DfFx/+PjY1PXi1835tKWOzTl36WNjbCdTj4742NT1au+k/70p3Ul87GhA3Ytefn51pR9DKqCpY+Nhxl6XWtbUsbkzzHls5OwkFdDedzJ0bBi61aUukvvGc46fe41uYTWvEX9D4jvC2XfSjyZ1XIhvYzlvYG7VU+fIOWfNawxdZ+haJTtZY94WdpI6dyj5BJR+YsbeyJJl5F5jzfd4lJ3MPXfIufBQlaWfyrl3sKXXyLlOSRhH3EnJucNat+Ean6yly6o9v51kBlTjFrnlebe4jp1kBlTrFrn0vEuXVfP1dpJ+TSgdCCZ/BgIBISAEhIBAQAgIASEgEBACQkAICAGBgBAQAkJAICAEhIAQEAgIASEgBAQCQkAICAEhIBAQAkJACAgEhIAQEAICASEgBISAQEAICAEhIBAQAkJACAgBgYAQEAJCQCAgBISAEBAICAHRlF+C+UHwNeMuEwAAAC10RVh0U29mdHdhcmUAYnkuYmxvb2RkeS5jcnlwdG8uaW1hZ2UuUE5HMjRFbmNvZGVyqAZ/7gAAAABJRU5ErkJggg==');
game.load.image('player', 'https://i.imgur.com/JArA3tQ.png');
game.load.image('upLedge', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAACGCAYAAADZ0np4AAAAiklEQVR42u3UsQ2DQAwF0FslPT0jpE+BmIQBaLMDw2QUSpY45IIrTggFQVK94tvds2TJTnN+52npS4ZPU/q36cZH6ZFX+8wJDAaDwWAwGAwGg8FgMBgMBoPBYDAYDAaDwWAwGAwGg8FgMBgM3oej/CJpm3J30pUVHK0DDP4nHCd9JjG8fgP1Swh4Bcd7BZH+S2fyAAAALXRFWHRTb2Z0d2FyZQBieS5ibG9vZGR5LmNyeXB0by5pbWFnZS5QTkcyNEVuY29kZXKoBn/uAAAAAElFTkSuQmCC');
game.load.image('bottomLedge', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAB6CAYAAABQtRgZAAAAgklEQVR42u3TsQmAMBQFwKxib+8I9hbiJA5g6w4O4yiWLhFRUERslAgWF3h5pDmSwA9VUcbUCVPs45MMc3P0Xdoxj+F82PtN6i47GgpNja5b6oTPxvQ6Zk+/4fz07aZQKBQKhUKhUCgUCoVCoVAoFAqFQqFQKBQKhUKhUCj0n+gXawGd+WGo+T+h1gAAAC10RVh0U29mdHdhcmUAYnkuYmxvb2RkeS5jcnlwdG8uaW1hZ2UuUE5HMjRFbmNvZGVyqAZ/7gAAAABJRU5ErkJggg==');
}
function create() {
// The scrolling starfield background
game.physics.startSystem(Phaser.Physics.ARCADE);
starfield = game.add.tileSprite(0, 0, 800, 600, 'starfield');
starfield.scale.setTo(1, 2.5);
starfield.enableBody = true;
// The hero!
player = game.add.sprite(50, 400, 'player');
player.anchor.setTo(0.5, 0.5);
player.scale.setTo(1.25, 1.5);
game.physics.arcade.enable(player);
game.physics.enable(player, Phaser.Physics.ARCADE);
player.body.gravity.y = 450;
player.body.collideWorldBounds = true;
upLedge = game.add.sprite(400, 0, 'upLedge');
bottomLedge = game.add.sprite(400, 365, 'bottomLedge');
randomLedgeSize();
upLedge.scale.setTo(1, vaRandomUpLedgeSize);
randomLedgeSize();
bottomLedge.scale.setTo(1, vaRandomUpLedgeSize);
fireButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
// And some controls to play the game with
cursors = game.input.keyboard.createCursorKeys();
}
function update() {
// Scroll the background
starfield.tilePosition.x -= 2;
player.x++;
//SPACEBAR
if (player.y >= 591.75) {
player.y = 591.75;
player.x--;
}
if (fireButton.isDown) {
player.body.velocity.y = -250;
}
game.physics.arcade.collide(player, upLedge);
game.physics.arcade.collide(player, bottomLedge);
}
function render() {
}
function randomLedgeSize() {
vaRandomUpLedgeSize = Math.floor(Math.random() * (3 - 1)) + 1;
if (vaRandomUpLedgeSize <= 1.5) {
vaRandomUpLedgeSize = 1;
} else {
vaRandomUpLedgeSize = 2;
}
}
function randomLedgeSizeBot() {
vaRandomUpLedgeSize = Math.floor(Math.random() * (3 - 1)) + 1;
if (vaRandomUpLedgeSize <= 1.5) {
bottomLedge.y = 500;
} else {
vaRandomUpLedgeSize = 2;
}
}
See here:
The collisions only fire if the sprite.body has velocity.
So what I did was change the update() function: I removed the call to player.x++; and in the create() function I added an X velocity to the player.
JSfiddle
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-demo', {
preload: preload,
create: create,
update: update,
render: render
});
var player;
var starfield;
var cursors;
var fireButton;
var gameOver;
var ledges;
function preload() {
game.load.image('starfield', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJAAAAEACAYAAABcV/9PAAAEWklEQVR42u3ZsW7UShSA4XltxAMgxGPwHHSwRSQaKpR0FCDRQY+AgAzeiccej8fesf0Vn8Llru2zJ//aubnh+bv3P6FUsAQEhIAQEAICASEgBISAQEAIiJYDevv7D1BIQAgIASEgBAQCQkDsKCC/DMNvohEQAkJAICAEhIAQEAgIASEgBAQCQkAICAGBgBAQAkJACAgEhIAQEAICASEgBISAQEAICAEhIBAQAkJACAgBgYAQEAJCQCAgBISAEBAICAEhIAQEAkJACAgBISBLQEAICAEhIBAQAkJACAgEhIAQEAICASEgBISAQEAICAEhIAQEAkJACAgBgYAQEAJCQCAgBISAEBAICAEhIASEgEBACAgBISAQEAJCQAgIBISAEBACAgEhIASEgEBACAgBISAEBAJCQAgIAYGAEBACQkAgIASEgBAQCAgBISAEhIBAQAgIATHD1x8PgwREUTh7Cykc9ZPR6t0iN5y97D0c9ZNxi7vF1F5K42l552FPn4ytZ6j5zV4aT+p93vr7EvbwyVhjjqlz1PiGd+erda6S+db8gD7+u1D7jbVwB1jzMbJXtT+g3d+FrYbc8vGx1iPkaBHVOGeTAd3qdn+miGqdL2xxq6zxWtq0akBrHsNBA0JAICAEhICuvfly+ef1x/snzjbHEXayeUAP3+/+eByq+3P3z2eb4wg7WRTQp28fnki9dqjqx+G6wZcsq5U5zriTUGu4nCH7VcdKltXKHGfeSZj7vE0NN1Rx/7xx1fHXuc/+VuY4+07CnNvlWN1DFXc/kOUOmTtLK3PYSXQHmio+Z8j+D2NDQ47dJnNnaWUOO7n/fwcaOih+fs65NZbcJnNmaWUOO/lrcUCpavu/U9hiWVvPYSdRQEMH5SwrdXx/yKk3FA85Nksrc9jJZbuAuq+3XlbNOezkst4jLPW83fp2veYcdrLiIywevv93OUPW+rStOYedzHyEpf7zcGzIscGXPDpaneOMO8l+hOX+gqr/P+OmBi99dLQ6xxl3ErqDh752wzy7e3El/l1DfFx/+PjY1PXi1835tKWOzTl36WNjbCdTj4742NT1au+k/70p3Ul87GhA3Ytefn51pR9DKqCpY+Nhxl6XWtbUsbkzzHls5OwkFdDedzJ0bBi61aUukvvGc46fe41uYTWvEX9D4jvC2XfSjyZ1XIhvYzlvYG7VU+fIOWfNawxdZ+haJTtZY94WdpI6dyj5BJR+YsbeyJJl5F5jzfd4lJ3MPXfIufBQlaWfyrl3sKXXyLlOSRhH3EnJucNat+Ean6yly6o9v51kBlTjFrnlebe4jp1kBlTrFrn0vEuXVfP1dpJ+TSgdCCZ/BgIBISAEhIBAQAgIASEgEBACQkAICAGBgBAQAkJAICAEhIAQEAgIASEgBAQCQkAICAEhIBAQAkJACAgEhIAQEAICASEgBISAQEAICAEhIBAQAkJACAgBgYAQEAJCQCAgBISAEBAICAHRlF+C+UHwNeMuEwAAAC10RVh0U29mdHdhcmUAYnkuYmxvb2RkeS5jcnlwdG8uaW1hZ2UuUE5HMjRFbmNvZGVyqAZ/7gAAAABJRU5ErkJggg==');
game.load.image('player', 'https://i.imgur.com/JArA3tQ.png');
game.load.image('upLedge', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAACGCAYAAADZ0np4AAAAiklEQVR42u3UsQ2DQAwF0FslPT0jpE+BmIQBaLMDw2QUSpY45IIrTggFQVK94tvds2TJTnN+52npS4ZPU/q36cZH6ZFX+8wJDAaDwWAwGAwGg8FgMBgMBoPBYDAYDAaDwWAwGAwGg8FgMBgM3oej/CJpm3J30pUVHK0DDP4nHCd9JjG8fgP1Swh4Bcd7BZH+S2fyAAAALXRFWHRTb2Z0d2FyZQBieS5ibG9vZGR5LmNyeXB0by5pbWFnZS5QTkcyNEVuY29kZXKoBn/uAAAAAElFTkSuQmCC');
game.load.image('bottomLedge', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAB6CAYAAABQtRgZAAAAgklEQVR42u3TsQmAMBQFwKxib+8I9hbiJA5g6w4O4yiWLhFRUERslAgWF3h5pDmSwA9VUcbUCVPs45MMc3P0Xdoxj+F82PtN6i47GgpNja5b6oTPxvQ6Zk+/4fz07aZQKBQKhUKhUCgUCoVCoVAoFAqFQqFQKBQKhUKhUCj0n+gXawGd+WGo+T+h1gAAAC10RVh0U29mdHdhcmUAYnkuYmxvb2RkeS5jcnlwdG8uaW1hZ2UuUE5HMjRFbmNvZGVyqAZ/7gAAAABJRU5ErkJggg==');
}
function create() {
// The scrolling starfield background
game.physics.startSystem(Phaser.Physics.ARCADE);
starfield = game.add.tileSprite(0, 0, 800, 600, 'starfield');
starfield.scale.setTo(1, 2.5);
// The hero!
player = game.add.sprite(50, 400, 'player');
player.anchor.setTo(0.5, 0.5);
player.scale.setTo(1.25, 1.5);
game.physics.arcade.enable(player);
game.physics.enable(player, Phaser.Physics.ARCADE);
player.enableBody = true;
player.body.gravity.y = 450;
player.body.collideWorldBounds = true;
player.body.velocity.x = 100;
// The ledges
ledges = game.add.group();
ledges.enableBody = true;
var upLedge = ledges.create(200, 0, 'upLedge');
upLedge.body.immovable = true;
var bottomLedge = ledges.create(200, 465, 'bottomLedge');
bottomLedge.body.immovable = true;
// Controls to play the game with
fireButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
cursors = game.input.keyboard.createCursorKeys();
}
function update() {
// Scroll the background
starfield.tilePosition.x -= 2;
// If spacebar is pressed, increase Y velocity
if (fireButton.isDown) {
player.body.velocity.y = -250;
}
// Check for collisions
game.physics.arcade.collide(player, ledges);
}
function render() {
}
Related
i am trying to make my bullet travel towards the cursor location. I have tried lots of things and I just can't get it to work. I have the player arm set up to always move to the player shoulder level. The player's arm and the gun has the same rotation value. The rotation value is calculated using Phaser.Math.Angle.BetweenPoints(playerArm, player1Aim);. I found a couple examples but i couldn't get them to work. Please teach me how to use it. I am a newbie. Please help. Here is my code:
var config = {
type: Phaser.AUTO,
width: 512,
height: 512,
physics: {
default: 'arcade',
arcade: {
gravity: {
y: 1500
},
debug: false
}
},
scene: {
preload: preload,
create: create,
update: update
}
// plugins: {
// global: [{
// key: 'PhaserPauseRenderPlugin',
// plugin: PhaserPauseRenderPlugin,
// mapping: 'render'
// }]
// }
};
// class SceneMain extends Phaser.Scene {
// constructor() {
// super('SceneMain');
// }
// preload() {}
// create() {
// //make 3 bars
// let healthBar = this.makeBar(140, 100, 0x2ecc71);
// this.setValue(healthBar, 100);
// // let powerBar = this.makeBar(140, 200, 0xe74c3c);
// // this.setValue(powerBar, 50);
// // let magicBar = this.makeBar(140, 300, 0x2980b9);
// // this.setValue(magicBar, 33);
// }
// makeBar(x, y, color) {
// //draw the bar
// let bar = this.add.graphics();
// //color the bar
// bar.fillStyle(color, 1);
// //fill the bar with a rectangle
// bar.fillRect(0, 0, 200, 50);
// //position the bar
// bar.x = x;
// bar.y = y;
// //return the bar
// return bar;
// }
// setValue(bar, percentage) {
// //scale the bar
// bar.scaleX = percentage / 100;
// }
// update() {}
// }
var player;
var platforms;
var cursors;
var gameOver = false;
var score = 0;
var time;
var waves;
var enemies;
var enemy;
var health;
var hacking = false;
var timer;
var enemyCount = 0;
var startGame = false;
var timeSpeed = 1;
var keys;
var damageStrike = 0;
var toMouse = 0;
var toPlayer = 0;
var bullets;
var ship;
var speed;
var stats;
var cursors;
var lastFired = 0;
var fire = false;
var pointerDown = false;
// var healthBar = new SceneMain();
// spaceBar input
// var spaceBar = Phaser.Input.Keyboard.KeyCodes.SPACE;
var game = new Phaser.Game(config);
function preload() {
//this.load.image('platform', 'images/platform.png');
// this.load.image('background', 'images/background.png');z
this.load.image('background', 'images/background.png');
this.load.image('platform', 'images/platform.png');
this.load.image('longPlatform', 'images/platform long.png');
this.load.image('itembg', 'images/item bg.png');
this.load.image('playerArm', 'images/player arm.png');
this.load.image('enemyArm', 'images/enemy arm.png');
this.load.image('playerGun', 'images/player gun.png');
this.load.image('enemyGun', 'images/enemy gun.png');
this.load.image('medkit', 'images/medkit.png');
this.load.image('aim', 'images/aim.png');
this.load.image('bullet', 'images/laser.png');
this.load.spritesheet('player', 'images/player idle-1.png', {
frameWidth: 49,
frameHeight: 128
});
this.load.spritesheet('enemy', 'images/enemy.png', {
frameWidth: 49,
frameHeight: 128
});
}
function create() {
// var Bullet = new Phaser.Class({
// Extends: Phaser.GameObjects.Image,
// initialize:
// // Bullet Constructor
// function Bullet(scene) {
// Phaser.GameObjects.Image.call(this, scene, 0, 0, 'bullet');
// this.speed = 1;
// this.born = 0;
// this.direction = 0;
// this.xSpeed = 0;
// this.ySpeed = 0;
// this.setSize(12, 12, true);
// },
// // Fires a bullet from the player to the reticle
// fire: function(player, target) {
// this.setPosition(player.x, player.y); // Initial position
// this.direction = Math.atan((target.x - this.x) / (target.y - this.y));
// // Calculate X and y velocity of bullet to moves it from shooter to target
// if (target.y >= this.y) {
// this.xSpeed = this.speed * Math.sin(this.direction);
// this.ySpeed = this.speed * Math.cos(this.direction);
// } else {
// this.xSpeed = -this.speed * Math.sin(this.direction);
// this.ySpeed = -this.speed * Math.cos(this.direction);
// }
// this.rotation = player.rotation; // angle bullet with shooters rotation
// this.born = 0; // Time since new bullet spawned
// },
// // Updates the position of the bullet each cycle
// update: function(time, delta) {
// this.x += this.xSpeed * delta;
// this.y += this.ySpeed * delta;
// this.born += delta;
// if (this.born > 500) {
// this.setActive(false);
// this.setVisible(false);
// }
// }
// });
// playerBullets = this.physics.add.group({
// classType: Bullet,
// runChildUpdate: true
// });
speed = Phaser.Math.GetSpeed(300, 1);
// healthBar.makeBar(32, 32, 0xffffff);
// console.log(timer);
// add background
// this.add.image(256, 256, 'background');
background = this.add.image(256, 256, 'background');
background.alpha = 0.8;
itemBg = this.add.image(256, 520, 'itembg')
platforms = this.physics.add.staticGroup();
// Here we create the ground.
platforms.create(256, 450, 'longPlatform').refreshBody();;
// platforms.create(256, 450, 'platform');
platforms.create(50, 175, 'platform');
platforms.create(460, 175, 'platform');
platforms.create(50, 350, 'platform');
platforms.create(460, 350, 'platform');
platforms.create(265, 250, 'platform');
player = this.physics.add.sprite(256, 10, 'player');
player.setScale(0.5);
player.setBounce(0.1);
player.setCollideWorldBounds(true);
playerArm = this.add.image(256, 256, 'playerArm');
playerArm.setScale(0.5);
playerArm.angle = 0;
playerGun = this.add.image(256, 256, 'playerGun');
playerGun.setScale(0.5);
playerGun.angle = 0;
enemyArm = this.add.image(256, 256, 'enemyArm');
enemyArm.setScale(0.5);
enemyArm.angle = 0;
enemyGun = this.add.image(256, 256, 'enemyGun');
enemyGun.setScale(0.5);
enemyGun.angle = 0;
player1Aim = this.add.image(256, 256, 'aim');
player1Aim.setScale(2);
player1Aim.angle = 0;
bullet = this.add.image(256, 10, 'bullet');
bullet.setScale(0.25);
bullet.angle = 0;
var playerX = player.x;
var playerY = player.y;
enemies = this.physics.add.group();
medkits = this.physics.add.group();
spawn = (x, enemyName) => {
enemyPlayer = this.physics.add.sprite(x, 20, enemyName);
// enemyPlayer = this.physics.add.sprite.destroy(true);
console.log(enemyPlayer);
enemyPlayer.setScale(0.5);
enemyPlayer.setBounce(0.1);
enemyPlayer.setCollideWorldBounds(true);
enemyPlayer.allowGravity = true;
return enemyPlayer;
}
spawnMedkit = (x, enemyName) => {
enemyPlayer = this.physics.add.sprite(x, 20, enemyName);
// enemyPlayer = this.physics.add.sprite.destroy(true);
console.log(enemyPlayer);
enemyPlayer.setScale(1);
enemyPlayer.setBounce(0.1);
enemyPlayer.setCollideWorldBounds(true);
enemyPlayer.allowGravity = true;
return enemyPlayer;
}
enemy = spawn(450, 'enemy');
medkit = spawnMedkit(100, 'medkit');
enemyCount += 1;
console.log(enemyCount);
// enemy = enemies.create(450, 20, 'enemy')
// // enemies.create(250, 20, 'enemy')
// enemy.setScale(0.5)
// enemy.setBounce(0.1);
// enemy.setCollideWorldBounds(true);
// enemy.allowGravity = true;
cursors = this.input.keyboard.createCursorKeys();
this.physics.add.collider(player, platforms);
this.physics.add.collider(enemy, platforms);
this.physics.add.collider(medkit, platforms);
// this.physics.add.collider(bombs, platforms);
health = 100;
waves = 0;
// timer = this.time.create(false);
// The score
scoreText = this.add.text(16, 16, 'score: 0', {
fontSize: '25px',
fill: '#00FFFF'
});
// FPS
fps = this.add.text(16, 50, game.loop.actualFps, {
fontSize: '15px',
fill: '#00FFFF'
});
timeScale = this.add.text(16, 70, this.physics.world.timeScale, {
fontSize: '15px',
fill: '#00FFFF'
});
gunRotation = this.add.text(16, 100, 'gun rotation: 0', {
fontSize: '15px',
fill: '#00FFFF'
});
// gameStatus = this.add.text(16, 60, 'Game Status: Alive', {
// fontSize: '25px',
// fill: '#00FFFF'
// });
// hp = this.add.text(16, 100, 'Health: ' + health, {
// fontSize: '25px',
// fill: '#00FFFF'
// });
// add collisions
this.physics.add.collider(player, enemy, damage, null, this);
this.physics.add.collider(player, medkit, healByMedkit, null, this);
// this.physics.add.collider(laser, enemy, hit, null, this);
keys = this.input.keyboard.addKeys('W,A,S,D,F,J,K,L,SPACE');
var r1 = this.add.rectangle(playerX, playerY - 15, 200, 69, 10, 0x6666ff);
this.input.on('pointermove', function(pointer) {
toMouse = Phaser.Math.Angle.BetweenPoints(playerArm, player1Aim);
});
this.input.on('pointerdown', function(pointer) {
// shoot the bullet towards the cursor (player1Aim)
});
startGame = true;
}
function update(time, delta) {
var playerX = player.x;
var playerY = player.y;
var enemyX = enemy.x;
var enemyY = enemy.y;
var playerArmX = playerArm.x;
var playerArmY = playerArm.y;
var playerArmRotation = playerArm.angle;
var mouseX = game.input.mousePointer.x;
var mouseY = game.input.mousePointer.y;
// var theta =
// console.log(playerArmRotation);
// position the arm to the shoulder level of the player
playerArm.x = playerX;
playerArm.y = playerY - 5;
playerGun.x = playerX;
playerGun.y = playerY - 3;
enemyArm.x = enemyX;
enemyArm.y = enemyY - 5;
enemyGun.x = enemyX;
enemyGun.y = enemyY - 5;
player1Aim.x = mouseX;
player1Aim.y = mouseY;
toPlayer = Phaser.Math.Angle.BetweenPoints(enemy, player);
playerArm.rotation = Phaser.Math.Angle.BetweenPoints(playerArm, player1Aim);
playerGun.rotation = Phaser.Math.Angle.BetweenPoints(playerArm, player1Aim);
enemyArm.rotation = toPlayer;
enemyGun.rotation = toPlayer;
// rotate gun for player
if (playerGun.angle >= 90 || playerGun.angle <= -90) {
playerGun.flipY = true;
// console.log('flipped')
} else {
playerGun.flipY = false;
}
// rotate gun for player
if (enemyGun.angle >= 90 || enemyGun.angle <= -90) {
enemyGun.flipY = true;
// console.log('flipped')
} else {
enemyGun.flipY = false;
}
// this.input.on('pointerdown', function(pointer) {
// if (pointerDown == false) {
// pointerDown = true;
// fire();
// console.log('FIRE');
// } else {
// pointerDown = false;
// }
// });
// this.input.on('pointerdown', function(pointer, time, lastFired) {
// if (player.active === false)
// return;
// // Get bullet from bullets group
// var bullet = playerBullets.get().setActive(true).setVisible(true);
// if (bullet) {
// bullet.fire(playerGun, player1Aim);
// // this.physics.add.collider(enemy, bullet, enemyHitCallback);
// }
// }, this);
// this.input.on('pointerdown', function(pointer) {
// if (time > lastFired) {
// var bullet = bullets.get();
// console.log('test2');
// if (bullet) {
// // bullet.rotation = playerGun.rotation;
// bullet.fire(playerGun.x, playerGun.y);
// lastFired = time + 50;
// }
// }
// });
if (startGame == true) {
if (keys.J.isDown) {
this.physics.world.timeScale = 1.75;
// console.log(this.physics.world.timeScale);
// timeSpeed = 0.5;
// console.log(timeSpeed);
} else
if (keys.K.isDown) {
this.physics.world.timeScale = 0.75;
// timeSpeed = 1;
}
if (keys.L.isDown) {
}
if (gameOver) {
return;
gameStatus.setText('Game Status: Dead')
}
if (cursors.left.isDown || keys.A.isDown) {
player.setVelocityX(-160 * timeSpeed);
} else if (cursors.right.isDown || keys.D.isDown) {
player.setVelocityX(160 * timeSpeed);
} else {
player.setVelocityX(0 * timeSpeed);
}
if (cursors.up.isDown && player.body.touching.down) {
player.setVelocityY(-650 * timeSpeed);
}
if (keys.W.isDown && player.body.touching.down) {
player.setVelocityY(-650 * timeSpeed);
}
if (keys.SPACE.isDown && player.body.touching.down) {
player.setVelocityY(-650 * timeSpeed);
}
if (waves == 0) {
waves += 1;
console.log(waves)
}
fps.setText('fps: ' + game.loop.actualFps);
scoreText.setText('Score: ' + score);
timeScale.setText('timeScale: ' + this.physics.world.timeScale);
gunRotation.setText('gun rotation: ' + playerGun.angle);
}
}
function damage(player, enemy) {
enemy.disableBody(true, true);
// enemy.body.enable = false;
// enemy.body.gameObject.active = false;
enemyCount -= 1;
console.log(enemyCount);
health -= 10;
score -= 10;
damageStrike += 1;
if (enemyCount === 0) {
var randomX = Phaser.Math.FloatBetween(0, 500);
enemy.enableBody(true, randomX, 15, true, true);
enemyCount += 1;
console.log(enemyCount);
}
if (damageStrike === 3 && medkits.countActive(false) == 0) {
var randomX = Phaser.Math.FloatBetween(0, 500);
medkit.enableBody(true, randomX, 15, true, true);
damageStrike = 0;
}
console.log('Health: ' + health);
if (health <= 0) {
gameOver = true;
}
}
function hit(laser, enemy) {
score += 10;
enemy.disableBody(true, true);
}
function healByMedkit(player, medkit) {
score += 5;
health += 15;
console.log(health);
medkit.disableBody(true, true);
}
Well if you want to rotate a gameObjects and shoot something in a specific angle, in Phaser you should have to keep somethings in mind:
Origin of the gameObject (since the rotation occurs around this point)
The direction / angle offset of the gameObject you want to rotate
Apart from that, everything is more or less straightforward, calculate the vector for "shooting" a bullet and set the velocity of that bullet.
Here a short demo:
In this Demo, the both main factors are shown, origin and "angle-offset".
(It should cover the basic from your code)
document.body.style = 'margin:0;';
var config = {
type: Phaser.AUTO,
width: 536,
height: 183,
physics: {
default: 'arcade',
arcade: {
gravity:{ y: 50 },
}
},
scene: {
create,
update
},
banner: false
};
function create () {
this.add.text(10, 10, 'Click to shoot bullets')
.setOrigin(0);
// head
this.add.circle ( 42, 60, 8, 0xffffff)
.setOrigin(0);
// body
let player = this.add.rectangle( 40, 80, 20, 50, 0xffffff)
.setOrigin(0);
// sholder
this.add.circle ( 50, 90, 5, 0xff0000)
.setOrigin(0.5);
// arm
let playerArm = this.add.rectangle( 50, 90, 10, 30, 0xff0000)
// Point #1: the Point of rotation is more or less the shoulder
.setOrigin(.5, 0)
.setDepth(10);
// create bullet Group
this.bullets = this.add.group();
this.input.on('pointermove', pointer => {
let rotation = Phaser.Math.Angle.BetweenPoints(playerArm, pointer);
// Point #2: Angle-Offset since the 0 Degrees is on the right,
// and the arm is pointing down I need to subtract 90° 0 PI/2
playerArm.rotation = rotation - Math.PI / 2;
});
this.input.on('pointerdown', pointer => {
let speed = 300;
// create bullet
let bullet = this.add.circle( playerArm.x, playerArm.y, 4, 0xffff00)
.setDepth(9);
this.physics.add.existing(bullet);
// get Vector where to shoot bullet
let vector = new Phaser.Math.Vector2( pointer.x - playerArm.x, pointer.y - playerArm.y );
// set Speed of bullet
vector.setLength(speed);
// DEMO: to shoot in a straightline, just comment the following line in
// bullet.body.setAllowGravity(false);
// DEMO: QuickFix to destroy the bullet after 1 Second automatically
// setTimeout( () => bullet.destroy(), 1000);
// add bullet to group
this.bullets.add(bullet);
bullet.body.setVelocity(vector.x, vector.y);
});
}
function update(){
this.bullets.getChildren().forEach(bullet => {
if(bullet.x > config.width){
bullet.destroy();
}
})
}
new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>
If you want the bullet to fly without gravity / in a straight line, just add this line bullet.body.setAllowGravity(false); after the creation of the bullet, to turn off the physics effect for the bullet.
I'm trying to make a browser game with pure javascript. I was using codesandbox.io for writing it at first, but the I decided I was done for the day and needed to check if it works in a browser. Lo and behold, it does not. I genuinely have no idea why it's not working.
All the code is supposed to do, is make a square jump. which it does do, however right when you let go of the up key, the page hangs, it won't even refresh. Doesn't crash the browser though. Anyways, here's my code.
class player {
constructor(gameW, gameH) {
this.gameH = gameH;
this.width = 50;
this.heigth = 50;
this.maxUpV = 5;
this.currV = 0;
this.gravConst = 50;
this.position = {
x: 50,
y: 150
};
}
jumpUp() {
this.currV = -this.maxUpV;
}
fall(falling) {
while (this.position.y < 150) {
this.currV = this.maxUpV;
}
return (falling = false);
}
draw(ctx) {
ctx.fillStyle = "#F00";
ctx.fillRect(this.position.x, this.position.y, this.width, this.heigth);
}
update(deltaTime) {
if (!deltaTime) {
return;
}
this.position.y += this.currV;
if (this.position.y + this.heigth > 200) {
this.position.y = 150;
}
}
}
class input {
constructor(Player) {
this.falling = false;
document.addEventListener("keydown", event => {
if (event.keyCode === 38) {
if (!Player.fall(this.falling)) {
Player.jumpUp();
}
}
});
document.addEventListener("keyup", event => {
if (event.keyCode === 38) {
this.falling = true;
Player.fall(this.falling);
}
});
}
}
const GAME_WIDTH = 800;
const GAME_HEIGHT = 300;
var canvas = document.getElementById("gameScreen");
var ctx = canvas.getContext("2d");
var Player = new player(GAME_WIDTH, GAME_HEIGHT);
ctx.clearRect(0, 0, 800, 300);
ctx.fillRect(0, 200, 800, 200);
ctx.fillRect(400, 100, 50, 1);
Player.draw(ctx);
new input(Player);
var lastTime = 0;
function gameLoop(timeStamp) {
var deltaTime = timeStamp - lastTime;
lastTime = timeStamp;
ctx.clearRect(0, 0, 800, 200);
Player.update(deltaTime);
Player.draw(ctx);
requestAnimationFrame(gameLoop);
}
gameLoop();
Oh and also, when I was writing it in codesandbox.io, the classes were separate files that I imported into the main .js file. That gave me an error in the browser, so I just put everything in one file. I tried both Vivaldi and Firefox, to no avail.
I originally misread the question. Your code is locking up in your fall function. Once you hit the max height you were getting stuck in a loop waiting for the fall but never returning control to anywhere that could generate a fall. I'm having some difficulty understanding your max height validation.
The fall function will always return false.
fall(falling) {
while (this.position.y < 150) {
this.currV = this.maxUpV;
}
return (falling = false);
}
The return value of an assignment is the value assigned, so in this case your return value will always be false
I also had to modify the logic for the end button press
if (!Player.fall(this.falling)) {
Player.jumpUp();
}
The conditional was basically always returning true and could be simplified.
I hope this helps!
class player {
constructor(gameW, gameH) {
this.gameH = gameH;
this.width = 50;
this.height = 50;
this.maxUpV = 5;
this.currV = 0;
this.gravConst = 50;
this.position = {
x: 50,
y: 150
};
}
jumpUp() {
this.currV = -this.maxUpV;
}
fall(falling) {
if (this.position.y <150) {
this.currV = this.maxUpV;
return true
}
return false;
}
draw(ctx) {
ctx.fillStyle = "#F00";
ctx.fillRect(this.position.x, this.position.y, this.width, this.height);
}
update(deltaTime) {
if (!deltaTime) {
return;
}
this.position.y += this.currV;
if (this.position.y + this.height > 200) {
this.position.y = 150;
}
}
}
class input {
constructor(Player) {
this.falling = false;
document.addEventListener("keydown", event => {
if (event.keyCode === 38) {
if (!this.falling) {
Player.jumpUp();
}
}
});
document.addEventListener("keyup", event => {
if (event.keyCode === 38) {
this.falling = true;
this.falling = Player.fall();
}
});
}
}
const GAME_WIDTH = 800;
const GAME_HEIGHT = 300;
var canvas = document.getElementById("gameScreen");
var ctx = canvas.getContext("2d");
var Player = new player(GAME_WIDTH, GAME_HEIGHT);
ctx.clearRect(0, 0, 800, 300);
ctx.fillRect(0, 200, 800, 200);
ctx.fillRect(400, 100, 50, 1);
Player.draw(ctx);
new input(Player);
var lastTime = 0;
function gameLoop(timeStamp) {
var deltaTime = timeStamp - lastTime;
lastTime = timeStamp;
ctx.clearRect(0, 0, 800, 200);
Player.update(deltaTime);
Player.draw(ctx);
requestAnimationFrame(gameLoop);
}
gameLoop();
<canvas id="gameScreen" width=400 height=400></canvas>
I'm relatively new to asking questions here, so please bear with me. I am trying to create a top down driving game with Matter.js as the primary physics engine. I would like the red car to collide with the green square. However, I am still stuck on knowing how to implement Matter.js onto my game. Any form of response will be greatly appreciated!
<html>
<canvas width=1000 height=500 style='border:1px solid black'>
</canvas>
<body onload='start()'>
<script src='matter.js'>
</script>
<script>
function start() {
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var x = 100;
var y = 100;
var s = 0;
var rot = 0;
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.keyCode == 39) {
rightPressed = true;
} else if (e.keyCode == 37) {
leftPressed = true;
} else if (e.keyCode == 38) {
upPressed = true;
} else if (e.keyCode == 40) {
downPressed = true;
}
}
function keyUpHandler(e) {
if (e.keyCode == 39) {
rightPressed = false;
} else if (e.keyCode == 37) {
leftPressed = false;
} else if (e.keyCode == 38) {
upPressed = false;
} else if (e.keyCode == 40) {
downPressed = false;
}
}
function car() {
ctx.fillStyle = 'red';
ctx.fillRect(-20, -20, 40, 40);
ctx.beginPath();
ctx.moveTo(-20, -19);
ctx.lineTo(-20, -20);
ctx.lineTo(0, -30);
ctx.lineTo(20, -20);
ctx.lineTo(20, -19);
ctx.fill();
ctx.closePath();
ctx.fillStyle = 'black';
ctx.fillRect(-25, -20, 5, 10);
ctx.fillRect(-25, 10, 5, 10);
ctx.fillRect(20, -20, 5, 10);
ctx.fillRect(20, 10, 5, 10);
ctx.fillRect(-15, -5, 30, 20);
}
function block() {
ctx.fillStyle = 'green';
ctx.fillRect(200, 100, 50, 50);
}
function draw() {
requestAnimationFrame(draw);
ctx.clearRect(0, 0, 1000, 500);
if (s > 15) {
s = 15;
}
if (s < -15) {
s = -15;
}
if (upPressed) {
s++;
}
if (downPressed) {
s *= .9;
}
if (!upPressed) {
s *= .99;
}
if (leftPressed) {
rot -= s / 3;
}
if (rightPressed) {
rot += s / 3;
}
ctx.fillText(upPressed, 10, 10);
x += s * Math.cos(rot * Math.PI / 180);
y += s * Math.sin(rot * Math.PI / 180);
ctx.save();
ctx.translate(x, y);
ctx.rotate((rot + 90) * Math.PI / 180);
car();
ctx.restore();
block();
}
draw();
}
</script>
</body>
</html>
You would have to redo most of your code, but the movement code CAN be moved over fairly easily.
First you need to make a new engine and run it:
//Create engine - All the game stuff
var Engine = Matter.Engine,
Render = Matter.Render,
Runner = Matter.Runner,
Composites = Matter.Composites,
Common = Matter.Common,
World = Matter.World,
Bodies = Matter.Bodies,
Body = Matter.Body;
// create an engine
var engine = Engine.create(),
world = engine.world;
// create a renderer
var render = Render.create({
canvas: document.getElementById("canv"),
engine: engine,
options: {
width: 500,
height: 500,
wireframes: false,
background: '#6DDA4A'
}
});
engine.world.gravity.y = 0;
Render.run(render);
// create runner
var runner = Runner.create();
Runner.run(runner, engine);
Next, you should make and add a new car object and the block into the world. You can edit these values to whatever you need them to be.
Note: rot is not an actual parameter you need, I'm just using it to set the rotation of the car later.
var car = Bodies.rectangle(100, 100, 50, 80, {
friction: 1,
frictionAir: 0.1,
rot: 0,
restitution: 0,//Makes it so the car won't bounce off of objects
render: {
fillStyle: "#FF0000",
/*sprite: {
//You can use this to apply a background image to the car
texture: "Path/To/Image.png",
xScale: number,
yScale: number
}/**/
}
});
var block = Bodies.rectangle(350, 100, 100, 400, {
isStatic: true,//Makes block unmovable
friction: 1,
frictionAir: 0.1,
rot: 0,
restitution: 0,
render: {
fillStyle: "#0000FF",
/*sprite: {
texture: "Path/To/Image.png",
xScale: number,
yScale: number
}/**/
}
});
World.add(world, [car, block]);
For updating the car, you can either use body.setPosition or body.applyForce. Since it's a car, I would use body.applyForce so that the car keeps rolling after you've stopped pressing a button. Rotation can also be done with body.setAngle or body.rotate. This time, I'm going to use body.setAngle so the turning feels better.
function updateCar() {
//Declare variables for velocity
var speed = 5;
var carRot = car.rot*180/Math.PI;
var velY = speed * Math.cos(carRot * Math.PI / 180);
var velX = speed * Math.sin(carRot * Math.PI / 180)*-1;
var pushRot = 0;
//Update variables
if (upPressed==false&&downPressed==false) {
velY = 0;
velX = 0;
}
else {
//alert(carX+", "+carY);
}
if (downPressed == true) {
velY *= -1;
velX *= -1;
}
if (leftPressed) {
pushRot = -0.1;
}
if (rightPressed) {
pushRot = 0.1;
}
car.rot += pushRot;
//Set position of car
carX += velX;
carY += velY;
Body.applyForce(car, {x:carX,y:carY}, {x:velX/200,y:velY/200});
Body.setAngle(car, car.rot);
requestAnimationFrame(updateCar);
}
window.requestAnimationFrame(updateCar);
Check out a demo here
I stuck in one place for few hours, so I decided to go for help here. I'm beginner and i wish to try write a simple pong game.
At this link in Khan Academy you'll see result.
KHAN ACADEMY my pong game
My issue is:
I can't move two players at once. Only player can move - who hit last the keyboard. Last hit key win.
I know there are few ready pong games, but a lot of it is in Java, or all different logic. Can you help me good people? :)
//THIS IS GAME FOR 2 PEOPLE
//PLAYER 1 CONTROLS: UP ARROW (MOVE UP), DOWN ARROW (MOVE DOWN)
//PLAYER 2 CONTROLS: W KEY (MOVE UP), S KEY (MOVE DOWN)
var player1Y = height/2;
var player2Y = height/2;
var player1Score = 0;
var player2Score = 0;
var ball;
var gameStarted = false;
var t = 0;
//Constants
var PAUSE_TIME = 60;
var PLAYER_MOVE_SPEED = 2;
var BALL_SPEED = 3;
var PADDLE_HEIGHT = 80;
var PADDLE_WIDTH = 8;
angleMode = "degrees";
var Ball = function(position, speed) {
this.position = position;
this.speed = speed || BALL_SPEED;
this.radius = 6;
this.resetVelocity = function() {
this.theta = random(0, 75);
this.velocity = new PVector(
this.speed*cos(this.theta), -this.speed*sin(this.theta));
};
this.resetVelocity();
this.draw = function() {
fill(0, 0, 0);
noStroke();
ellipse(this.position.x, this.position.y,
this.radius*2, this.radius*2);
};
this.collideWithPaddle = function(x, y) {
if (this.position.x - this.radius < x + PADDLE_WIDTH/2 &&
this.position.x + this.radius > x - PADDLE_WIDTH/2) {
if (dist(0, this.position.y, 0, y) <
PADDLE_HEIGHT/2 + this.radius) {
if (this.position.x > x) {
this.position.x = x +
this.radius + PADDLE_WIDTH/2;
}
else if (this.position.x < x) {
this.position.x = x -
this.radius - PADDLE_WIDTH/2;
}
this.velocity.mult(new PVector(-1, 1));
}
}
};
this.update = function() {
//Handle wall collisions
if (this.position.x < 0) {
player2Score++;
this.position = new PVector(width/2, height/2);
gameStarted = false;
this.resetVelocity();
}
else if (this.position.x > width) {
player1Score++;
this.position = new PVector(width/2, height/2);
gameStarted = false;
this.resetVelocity();
}
if (this.position.y < 0) {
this.position.y = 0;
this.velocity.mult(new PVector(1, -1));
}
else if (this.position.y > height) {
this.position.y = height;
this.velocity.mult(new PVector(1, -1));
}
//Handle paddle collisions
this.collideWithPaddle(20, player1Y);
this.collideWithPaddle(width-20, player2Y);
this.position.add(this.velocity);
};
};
ball = new Ball(new PVector(width/2, height/2));
var drawScores = function() {
var s;
fill(0, 0, 0);
textSize(16);
s = "Player 1: " + player1Score;
text(s, width*0.25-textWidth(s)/2, 25);
s = "Player 2: " + player2Score;
text(s, width*0.75-textWidth(s)/2, 25);
};
//Move the player1 up
var movePlayer1Up = function() {
player1Y -= PLAYER_MOVE_SPEED;
};
//Move the player1 down
var movePlayer1Down = function() {
player1Y += PLAYER_MOVE_SPEED;
};
//Move the player2 up
var movePlayer2Up = function() {
player2Y -= PLAYER_MOVE_SPEED;
};
//Move the player2 down
var movePlayer2Down = function() {
player2Y += PLAYER_MOVE_SPEED;
};
var drawPlayers = function() {
//Constrain the player movement
player1Y = constrain(player1Y, 0, 400);
player2Y = constrain(player2Y, 0, 400);
rectMode(CENTER);
fill(0, 0, 0);
rect(20, player1Y, PADDLE_WIDTH, PADDLE_HEIGHT);
rect(width-20, player2Y, PADDLE_WIDTH, PADDLE_HEIGHT);
};
draw = function() {
//Control Player 1
if (keyIsPressed) {
if (keyCode===38){
movePlayer1Up();
}
else if(keyCode===40) {
movePlayer1Down();
}
}
//Control Player 2
if (keyIsPressed) {
if (key.toString()==="w"){
movePlayer2Up();
}
else if(key.toString()==="s"){
movePlayer2Down();
}
}
//Draw the environment
background(255, 255, 255);
drawPlayers();
drawScores();
stroke(100, 100, 100);
line(width/2, 0, width/2, height);
//Draw the ball
ball.draw();
if (!gameStarted) {
t++;
if (t >= PAUSE_TIME) {
t = 0;
gameStarted = true;
}
return;
}
ball.update();
};
You should be watching the onkeyup, onkeydown events for moving players, see this related question here. JavaScript multiple keys pressed at once
Now I understand concept, and I just did something like that:
Scope for multiple keys:
var keys = [];
var keyPressed = function(){
keys[keyCode] = true;
};
var keyReleased = function(){
keys[keyCode] = false;
};
and drawing function:
//Controls
if (keys[87]) {
movePlayer2Up();
}
if (keys[83]) {
movePlayer2Down();
}
if (keys[38]) {
movePlayer1Up();
}
if (keys[40]) {
movePlayer1Down();
}
And now it's working! The same link to the Khan Academy - there's the effect. Thank you one more time.
This is a game I am making. I cant figure out why it is not working. I have the JS fiddle here http://jsfiddle.net/aa68u/4/
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);
// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "http://6269-9001.zippykid.netdna-cdn.com/wp-content/uploads/2013/11/Woods-Wallpaper.jpg";
// Ship image
var shipReady = false;
var shipImage = new Image();
shipImage.onload = function () {
shipImage = true;
};
shipImage.src = "http://s29.postimg.org/3widtojzn/hero.png";
// Astroid image
var astroidReady = false;
var astroidImage = new Image();
astroidImage.onload = function () {
astroidReady = true;
};
astroidImage.src = "http://s29.postimg.org/4r4xfprub/monster.png";
// Game objects
var ship = {
speed: 256;
};
var astroid = {};
var health = 100;
window.keyStates = {};
addEventListener('keydown', function (e) {
keyStates[e.keyCode || e.key] = true;
e.preventDefault();
e.stopPropagation();
}, true);
addEventListener('keyup', function (e) {
keyStates[e.keyCode || e.key] = false;
e.preventDefault();
e.stopPropagation();
}, true);
var reset = function () {
astroid.width = 10;
astroid.height = 10;
astroid.x = 32 + (Math.random() * (canvas.width - 64));
astroid.y = 32 + (Math.random() * (canvas.height - 64));
ship.speed = 256;
for (var p in keyStates) keyStates[p]= false;
};
// Update game objects
function update (modifier) {
if (keyStates[38] ==true) { // Player holding up
astroid.x -= ship.speed * modifier;
}
if (keyStates[40]==true) { // Player holding down
astroid.x += ship.speed * modifier;
}
if (keyStates[37]==true) { // Player holding left
astroid.y -= ship.speed * modifier;
}
if (keyStates[39]==true) { // Player holding right
astroid.y += ship.speed * modifier;
}
if (astroid.width) < 200{
astroid.width +=10;
astroid.height += 10;
}
if (astroid.width) > 200{
reset();
}
// Are they touching?
if (keyStates[32] == true && ship.x <= (astroid.x + 32) && astroid.x <= (ship.x + 32) && ship.y <= (astroid.y + 32) && astroid.y <= (ship.y + 32)) {
monstersCaught += 1;
reset();
}
};
// Draw everything
var render = function () {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
if (shipReady) {
ctx.drawImage(heroImage, hero.x, hero.y);
}
if (astroidReady) {
ctx.drawImage(monsterImage, monster.x, monster.y);
}
// Score
ctx.fillStyle = "rgb(250, 250, 250)";
ctx.font = "24px Helvetica";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Your Health: " + health, 32, 32);
};
// The main game loop
var main = function () {
var now = Date.now();
var delta = now - then;
if (delta > 20) delta = 20;
update(delta / 1000);
render();
then = now;
};
// Let's play this game!
reset();
var then = Date.now();
setInterval(main, 1); // Execute as fast as possible
The game is supposed to be a ship(shoe image) that is avoiding astroids that get bigger(ants) but when you move your ship(shoe) stays in the same place and the astroids(ants) move. The ants/astroids also get bigger like you are going close to them.
var ship = {
speed: 256;
};
Remove the ; after the value.
if astroid.width < 200{
and
if astroid.width > 200{
Need parentheses around the if conditions.
The error console is helpful! But now it's just stuck in an infinite loop of monsterImage is not defined. Just... go back, write your code more carefully, and use the error console! It's there for a reason!