How to create objects on runtime and move them? - javascript

I'm trying to create objects on my game update and move them. This is my banana object:
function Banana() {
this.height = 1.96;
this.width = 3.955;
this.pos_x = CENTER - this.width/2;
this.pos_y = -475;
this.banana_image = banana_image;
};
And this is the Move method:
Banana.prototype.move = function(){
if (this.pos_y > 500) {
//this.banana_image.parentElement.removeChild(this.banana_image);
}
this.height += ZOOM_RATE;
this.width += ZOOM_RATE;
this.pos_y += 3;
this.pos_x -= SIDES_RATE;
};
This is the Game Update part:
Game.update = function() {
this.player.move();
//creating bananas
if (objs.lenght <= 0) {
this.banana = new Banana();
} else {
for (i = 0; i < 10; i++) {
objs.push(new Banana());
}
}
//moving bananas
for (i = 0; i < objs.lenght; i++) {
this.objs[0].move();
}
};
Game Draw:
function Game.draw = function() {
this.context.drawImage(road, 0,0, rw, rh);
this.context.drawImage(
this.player.player_image,
this.player.pos_x, this.player.pos_y,
this.player.width, this.player.height);
this.context.drawImage(
this.banana.banana_image,
this.banana.pos_x, this.banana.pos_y,
this.banana.width, this.banana.height);
};
I tried to ask this to multiple people, but I can't find an answer for it.

Let's say you want to move the objects 10 times and then stop.
First you need to add a line to the start of Game.draw, so that it clears the canvas making you always start drawing from scratch:
this.context.clearRect(0,0,500,500); // clear canvas, adjust box size if needed
Then make a function to call both update and draw, and queue that function to be called again:
var count = 10;
function updateAndDraw() {
Game.update();
Game.draw();
count--;
if (count) requestAnimationFrame(updateAndDraw);
}
// start moving:
requestAnimationFrame(updateAndDraw);
The movement may go too fast to your liking, so then adjust the move method to make smaller changes, or use setTimeout instead of requestAnimationFrame (but that will make the animation less fluent).
Note that you have a few errors in your code, which you will need to fix first:
lenght should be length
function Game.draw = function() {: remove function before Game.draw.
... check the error messages you get in console.

Related

html canvas element blinking and then bugging out

I'm trying to have asteroids moving across the screen for a game. The first few asteroids work and then each asteroid will start blinking and bugging out to the point where they won't move across the screen. The variables acx and acy are the x and y coordinates for the asteroids respectively.
setInterval(throwAsteroid1A, 5000);
function throwAsteroid1A() {
var asteroidCanvas = document.getElementById('asteroidCanvas');
var context = asteroidCanvas.getContext('2d');
var acx = Math.floor(Math.random() * 200);
var acy = Math.floor(Math.random() * 10);
setInterval( () => {
asteroid.onload = function() {
context.drawImage(asteroid, asx, asy, aswidth, asheight, acx, acy, 20, 20);
acx += 1;
acy += 1;
}
asteroid.src = 'https://i.imgur.com/WfQKE6T.png';
}, 10)
setInterval(asteroidPath, 50)
}
function asteroidPath() {
// let computedStyle = getComputedStyle(canvasDisplay)
var asteroidCanvas = document.getElementById('asteroidCanvas');
let ctx = asteroidCanvas.getContext("2d");
ctx.clearRect(acx,acy, canvasDisplay.width, canvasDisplay.height);
}
Well there's obviously something conceptually wrong with your approach. I think the blinking is caused by a timing issue in-between the numerous individual interval timers you set up. The callback function asteroidPath() clears a part of the canvas and this might happen at the same time a new Asteroid has been added to the screen - which will delete it either entirely or partly depending on it's screen position.
To work around it you should:
keep a list of all asteroid objects
clear the screen completely once
update all asteroid's at once - not each one with it's own timer
So an example based on your code might look a little something like this (just click 'Run code snippet'):
Asteroid = function() {
this.acx = Math.floor(Math.random() * 200);
this.acy = Math.floor(Math.random() * 10);
this.image = new Image();
this.image.onload = function(e) {
this.loaded = true;
this.aswidth = e.target.naturalWidth;
this.asheight = e.target.naturalHeight;
}
this.image.src = 'https://i.imgur.com/WfQKE6T.png';
}
var asteroidCanvas = document.getElementById('asteroidCanvas');
var context = asteroidCanvas.getContext('2d');
let asteroids = [];
function spawnAsteroid() {
asteroids.push(new Asteroid());
}
function updateCanvas() {
context.clearRect(0, 0, asteroidCanvas.width, asteroidCanvas.height);
let asteroid;
for (let a = 0; a < asteroids.length; a++) {
asteroid = asteroids[a];
if (asteroid.image.loaded) {
context.drawImage(asteroid.image, 0, 0, asteroid.image.aswidth, asteroid.image.asheight, asteroid.acx, asteroid.acy, 20, 20);
asteroid.acx += 1;
asteroid.acy += 1;
}
}
}
setInterval(spawnAsteroid, 2000);
setInterval(updateCanvas, 50);
spawnAsteroid();
<canvas id="asteroidCanvas"></canvas>

JS Game - cannot set property of undefined typeerror

I know there are similar questions as mine but they did not work for my case and I can not waste more time.
I am learning JS so I am trying to code an easy pacman game. In this case, every time pacman eats a powerup, all the active ghosts have to turn into weak ghosts.
The problems comes when while I am playing and I grab a powerup, the game crashes saying:
Uncaught TypeError: Cannot set property 'isWeak' of undefined.
I did not post all the code in this question. Only the main part where the error comes from(I think so).
My code in main.js:
var activeGhosts = [];
var powerups = [];
for (var i = 0; i < powerups.length; i++) {
if (pacman.collision(powerups[i])) {
makeWeak();
powerups.splice(i,1);
}
}
function makeWeak() {
for (var i = 0; i < activeGhosts.length; i++) activeGhosts[i].isWeak = true;
}
My code in ghost.js:
function Ghost(x,y,img){
this.x = x;
this.y = y;
this.img = img;
this.direction = 0;
this.radius = 16; // half of 32 px because every image is 32x32 px
this.crash = false;
this.isWeak = false;
this.show = function () {
if (this.isWeak) {
image(weakghostimg, this.x, this.y);
} else {
// img can be the all the different ghosts
image(img, this.x, this.y);
}
};

Pixi.js keeps accelerating on page refresh

These are my references created in pixi.js here:
http://brekalo.info/en/reference
If we go to references it loads pixiJS and everything works fine on first load! Then, if we go to another page let's say: http://brekalo.info/en/contact, and the go back to references again - now my references have accelerated text movement and rotation and it keeps accelerate on each reference page load!
Here is my javascript/pixi code below:
function initiatePixi() {
Object.keys(PIXI.utils.TextureCache).forEach(function(texture) {
PIXI.utils.TextureCache[texture].destroy(true);}
);
// create an new instance of a pixi stage
var container = new PIXI.Container();
// create a renderer instance.
renderer = PIXI.autoDetectRenderer(frameWidth, frameHeight, transparent = false, antialias = true);
// set renderer frame background color
renderer.backgroundColor = 0xFFFFFF;
// add the renderer view element to the DOM
document.getElementById('pixi-frame').appendChild(renderer.view);
// create references
createReferences(animate); // callback to animate frame
function createReferences(callback) {
// Create text container
textContainer = new PIXI.Container();
textContainer.x = 0;
textContainer.y = 0;
for (i = 0; i < references.length; i++) {
var style = {
font:"22px Verdana",
fill:getRandomColor()
};
var text = new PIXI.Text(references[i], style);
text.x = getRandomInteger(20, 440); // text position x
text.y = getRandomInteger(20, 440); // text position y
text.anchor.set(0.5, 0.5); // set text anchor point to the center of text
text.rotation = getRandomInteger(0, rotationLockDeg) * 0.0174532925; // set text rotation
// make the text interactive
text.interactive = true;
// create urls on text click
text.on("click", function (e) {
var win = window.open("http://" + this.text, '_blank');
win.focus();
});
textContainer.addChild(text);
rotateText(); // rotate text each second
}
container.addChild(textContainer);
// callback
if (callback && typeof(callback) === "function") {
callback();
}
}
function animate() {
requestAnimationFrame(animate);
// render the stage
renderer.render(container);
}
function rotateText() {
var rotateTimer = setInterval(function () {
for (var key in textContainer.children) { // loop each text object
var text = textContainer.children[key];
if(text.rotation / 0.0174532925 < -rotationLockDeg || text.rotation / 0.0174532925 > rotationLockDeg) {
if(text.rotation / 0.0174532925 < -rotationLockDeg)
text.rotation = -rotationLockRad;
if(text.rotation / 0.0174532925 > rotationLockDeg)
text.rotation = rotationLockRad;
rotation = -rotation;
}
text.rotation += rotation; // rotate text by rotate speed in degree
if(text.x < 0 || text.x > 460)
dx = -dx;
if(text.y < 0 || text.y > 460)
dy = -dy;
text.x += dx;
text.y += dy;
}
}, 75);
}
// get random integer between given range (eg 1-10)
function getRandomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// random hex color generator
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
Thanks in advance!
:: cheers ::
Josip
To expand #Cristy's comment to an answer:
The answer lies in the same reason as why your question title is wrong: There is indeed NO page refresh when doing what you describe. If there were, you wouldn't have that problem in the first place. Try it out, hit F5 a few times on you animated page, it will stay the same speed.
The reason is that you are running a angular based single page application, and only exchange the loaded view content on a route change. This does not stop your already running animation code from continuing to run in the background while you navigate to another view, so that when you return to the animated tab you will create another set of interval timers for your animation, which will result in more executions and thus a visually faster animation.
#Cristy thanks for the advice!
Here is how I manage to solve this..
I put one property in my pixi-parameters.js:
pixiWasLoaded = false;
Then, when I call initiatePixi() function, I set:
pixiWasLoaded = true;
Now in my controllers.js I have this piece of code:
.run( function($rootScope, $location, $window) {
$rootScope.$watch(function() {
return $location.path();
},
function(page){
if(page == "/hr/reference" || page == "/en/references"){
if($window.pixiWasLoaded)
$window.addRendererElementToDOM();
else
loadReferences();
}
});
});
It checks if references page is loaded and then uses $window to find my global variable "pixiWasLoaded" and if it's not loaded then it loads PixiJS using loadReferences() function.. and if is already loaded it calls my part of code to add render-view to DOM so my animate function can render it..
:: cheers ::
Josip

ActivePointer location not updating

I'm making a sidescroller using Phaser (latest version) and I want the player's projectiles to go towards the pointer when the player clicks, like they do in this example http://phaser.io/examples/v2/games/tanks. I've used some of the code from the example but in my game, the activePointer x and y co-ordinates seem to only initialise when the game starts and never change. So when the player shoots, it's always going towards the same co-ordinates.
I have the following code (note I have removed bits about item collection, enemies etc. for posting on here):
var SideScroller = SideScroller || {};
var startPosX = 100;
var startPosY = 300;
var shooter;
var playerBullets;
var nextFire = 0;
var fireRate = 100;
var cursors;
var currentLoc;
SideScroller.Game = function () {};
SideScroller.Game.prototype = {
create: function () {
//create player
//params = (game, startPositionX,startPositionY, key, frame)
this.player = this.game.add.sprite(startPosX, startPosY, 'player');
//get canvas width and height for later use
canvasWidth = this.game.canvas.width;
canvasHeight = this.game.canvas.height;
//create enemy
var x = this.game.rnd.between(80, this.game.world.width);
var y = this.game.rnd.between(0, 113);
// Point to shoot projectiles from
// allows rotation, if this had been done on the player object, the graphic would have rotated, which we don't want
this.shooter = this.game.add.sprite(startPosX, startPosY, 'blank');
this.shooter.anchor.setTo(0.5, 0.5);
//make a group of player projectiles
playerBullets = this.game.add.group();
playerBullets.enableBody = true;
playerBullets.physicsBodyType = Phaser.Physics.ARCADE;
playerBullets.createMultiple(1000, 'peePower');
playerBullets.setAll('anchor.x', 0.5);
playerBullets.setAll('anchor.y', 0.5);
playerBullets.setAll('outOfBoundsKill', true);
playerBullets.setAll('checkWorldBounds', true);
//enable physics on the player
this.game.physics.arcade.enable(this.player);
//bring player shooting point to the top (not totally necessary)
this.shooter.bringToTop();
//player gravity
this.player.body.gravity.y = gravity;
//player collides with all four edges of the game world
this.player.body.collideWorldBounds = true;
this.player.anchor.setTo(0.5, 0.5);
//the camera will follow the player in the world
this.game.camera.follow(this.player);
//move player with cursor keys
cursors = this.game.input.keyboard.createCursorKeys();
},
update: function () {
currentLoc = this.game.input.activePointer;
//collision between player and platforms
this.game.physics.arcade.collide(this.player, this.blockedLayer, null, null, this);
//make co-ordinates match
this.shooter.x = this.player.x;
this.shooter.y = this.player.y;
//this.shooter's angle towards
this.shooter.rotation = this.game.physics.arcade.angleToPointer(this.shooter, this.game.input.activePointer);
//only respond to keys if the player is alive
if (this.player.alive) {
this.player.body.velocity.x = 0;
if (this.game.input.activePointer.isDown) {
console.log("pointer is down");
this.fire();
}
else if (cursors.right.isDown) {
this.playerForward();
}
else if (cursors.left.isDown) {
this.playerBack();
}
else if (cursors.up.isDown) {
this.playerJump();
}
else if (cursors.down.isDown) {
this.fire();
this.playerDuck();
}
}
},
fire: function () {
//for debugging
console.log("fire was called");
console.log(this.game.input.activePointer.x);
console.log(this.game.input.activePointer.y);
if (this.game.time.now > nextFire && playerBullets.countDead() > 0)
{
nextFire = this.game.time.now + fireRate;
var bullet = playerBullets.getFirstExists(false);
bullet.reset(this.shooter.x, this.shooter.y);
currentLoc = this.game.input.activePointer;
bullet.rotation = this.game.physics.arcade.moveToPointer(bullet, 1000, currentLoc, 1000);
console.log(this.game.input.activePointer);
}
},
playerForward: function () {
this.player.loadTexture('player');
this.player.body.setSize(this.player.standDimensions.width, this.player.standDimensions.height);
this.player.body.velocity.x = 700;
this.player.isMoving = true;
//console.log("Forward height:" + this.player.standDimensions.height);
//console.log("Forward width:" + this.player.standDimensions.width);
},
playerBack: function () {
this.player.loadTexture('playerBack');
this.player.body.velocity.x -= 700;
this.player.isMoving = true;
},
playerJump: function () {
if (this.player.body.blocked.down) {
this.player.body.velocity.y -= 700;
this.player.loadTexture('playerJump');
//console.log("Jump height:" + this.player.jumpDimensions.height);
//console.log("Jump width:" + this.player.jumpDimensions.width);
}
},
playerDuck: function () {
//change image and update the body size for the physics engine
this.player.loadTexture('playerDuck');
this.player.body.setSize(this.player.duckedDimensions.width, this.player.duckedDimensions.height);
//keep track of whether player is ducked or not
this.player.isDucked = true;
},
playerDead: function () {
//set to dead (this doesn't affect rendering)
this.player.alive = false;
//stop moving to the right
this.player.body.velocity.x = 0;
//change sprite image
this.player.loadTexture('playerDead');
},
};
Shooter is a blank sprite on top of the player (much like the turret in the tank example) to allow for rotation without the player rotating (please let me know also if there's a better way to do that!).
I tried updating the currentLoc variable in the update method to the activePointer location but that didn't work.
In addition, this condition has never been hit:
if (this.game.input.activePointer.isDown) {
console.log("pointer is down");
this.fire();
}
So something must be going awry with detecting mouse clicks and I don't know if that's part of the problem?
I think you should look it up in the API. There are few points in your code that are questionable.
http://phaser.io/docs/2.3.0/Phaser.Pointer.html
http://phaser.io/docs/2.3.0/Phaser.Physics.Arcade.html#moveToPointer
The point is that you are actually giving the reference to the pointer (to currentLoc) but not the position. So it should always fire to 0;0.
And for the isDown detection, have you done it in the update function or somewhere else?
Hope i could help!

Canvas game only starts drawing when the window is inactive

I noticed something weird in my canvas code: Im making a game with little flying ghosts. The class for the ghost is below. When I just draw 1 or 2 of em by manually adding the code and having em fly to the right by updating the x every frame for example everything runs smoothly and fine.
Now I ran another test and added a ghost every 100 frames to an array, update its x by 100 and then draw that ghost to the frame. (code is below the first block, the draw function).
Now the problem is that they are actually added and drawn, but I dont see em on the board until I make the window inactive by clicking on the taskbar for example.
Any1 got a clue what is going wrong here?
/*
* Class for little ghosts
*/
function Ghost (name) {
this.name = name;
this.ghost = new Image();
this.ghost.src = "img/ghost.png";
this.ghostWidth = 150;
this.ghostHeight = 100;
this.ghostSpriteOffsetX = 0;
this.ghostSpriteOffsetY = 0;
this.ghostX = 0;
this.ghostY = 0;
}
Ghost.prototype.drawGhost = function() {
context2D.drawImage(this.ghost, this.ghostSpriteOffsetX, this.ghostSpriteOffsetY, this.ghostWidth, this.ghostHeight, this.ghostX, this.ghostY, this.ghostWidth, this.ghostHeight);
};
Ghost.prototype.goToX = function(x) {
this.ghostX = x;
};
Ghost.prototype.goToY = function(y) {
this.ghostY = y;
};
Ghost.prototype.turnPink = function() {
this.ghostSpriteOffsetX = 0;
};
Ghost.prototype.turnBlue = function() {
this.ghostSpriteOffsetX = 150;
};
Ghost.prototype.turnPurple = function() {
this.ghostSpriteOffsetX = 300;
};
-
function draw()
{
// clear board
context2D.clearRect(0, 0, canvas.width, canvas.height);
if(frame%100==0){
ghosts[ghostId] = new Ghost("g-"+frame);
ghosts[ghostId].goToX(frame-100);
ghostId++;
}
// Draw ghost
for (i=0; i<ghosts.length; i++)
{
ghosts[i].drawGhost();
}
frame++;
}

Categories

Resources