Javscript animation is blinking - javascript

I am making a javascript game, and the animated sprite blinks when he moves i think it has to do with the speed of the animation because I also need to slow it down. here is my code for updateign the animation
var playerani = setInterval(function(){
if(animate == true){
if(aniframe == maxframes){
aniframe = 1
}else{
aniframe += 1;
}
}
if(controller.left == true){
animate = true;
window.aniimgY = 576;
}else if(controller.up == true){
animate = true;
window.aniimgY = 512;
}else if(controller.down == true){
animate = true;
window.aniimgY = 640;
}else if(controller.right == true){
animate = true;
window.aniimgY = 704;
}else{
animate = false;
aniframe = 0;
}
},10)
Here is The spritesheet
, And a Gif of the animation
You can test the game here

As #HanYolo suggested, set var maxframes = 8; :
var aniframe = 0;
var maxframes = 8;
var animate = false;
window.aniimg = document.getElementById("aniimg1")
var timer = null;
var aniTimer = null;
var levelnum = 0;
var img = document.getElementById("img")
var img2 = document.getElementById("img2")
var c = document.getElementById("c");
var ctx = c.getContext('2d')
var props = document.getElementById("props");
var prps = c.getContext('2d')
var tilesize = 32;
var tiles = 10;
player = {
size: 10,
x: 150,
y: 150,
v: 2,
}
controller = {
up: false,
right: false,
left: false,
down: false,
keyParse: function(key) {
switch (key) {
//keydowns
case 38:
this.up = true;
break;
case 37:
this.left = true;
break;
case 39:
this.right = true;
break;
case 40:
this.down = true;
break;
}
},
keyStop: function(key) {
switch (key) {
//keydowns
case 38:
this.up = false;
break;
case 37:
this.left = false;
break;
case 39:
this.right = false;
break;
case 40:
this.down = false;
break;
}
}
}
function drawlvl() {
for (y = 0; y < lvl[levelnum].length; y++) {
for (x = 0; x < lvl[levelnum][y].length; x++) {
switch (lvl[levelnum][y][x]) {
case 0:
//nw grass
var imgvar = img
var sx = 32;
var sy = 192;
break;
case 1:
//w dirt
var imgvar = img
var sx = 224;
var sy = 160;
break;
case 2:
//nw top dirt
var imgvar = img
var sx = 128;
var sy = 96;
break;
case 3:
//nw bottom dirt
var imgvar = img2
var sx = 95;
var sy = 320;
break;
case 4:
//lvl up dirt
var imgvar = img
var sx = 224;
var sy = 160;
break;
case 5:
//lvl down dirt
var imgvar = img
var sx = 224;
var sy = 160;
break;
case 6:
//w water
var imgvar = img
var sx = 0;
var sy = 416;
break;
case 7:
//w water side left
var imgvar = img
var sx = 0;
var sy = 288;
break;
case 8:
//w water side right
var imgvar = img2
var sx = 223;
var sy = 128;
break;
}
ctx.drawImage(imgvar, sx, sy, 32, 32, x * tilesize, y * tilesize, tilesize, tilesize)
}
}
}
walkable_blocks = [1, 6, 7, 8]
walkable_props = [0, 8, 9, 10, 11, 12]
lvlup_blocks = [4]
lvldown_blocks = [5]
function gameLoop() {
if (controller.up == true) {
player.newY = player.y - player.v
} else if (controller.left == true) {
player.newX = player.x - player.v
} else if (controller.right == true) {
player.newX = player.x + player.v
} else if (controller.down == true) {
player.newY = player.y + player.v
} else {
player.newY = player.y;
player.newX = player.x;
}
function playerani() {
if (animate == true) {
if (aniframe == maxframes) {
aniframe = 1
} else {
aniframe += 1;
}
}
if (window.aniimgY == null) {
window.aniimgY = 640;
}
if (controller.left == true) {
animate = true;
window.aniimgY = 576;
} else if (controller.up == true) {
animate = true;
window.aniimgY = 512;
} else if (controller.down == true) {
animate = true;
window.aniimgY = 640;
} else if (controller.right == true) {
animate = true;
window.aniimgY = 704;
} else {
animate = false;
aniframe = 0;
}
}
player.col = Math.floor((player.newX + 5) / tilesize)
player.row = Math.floor((player.newY + 5) / tilesize)
tileval = lvl[levelnum][player.row][player.col]
propval = propsArr[levelnum][player.row][player.col]
ctx.fillStyle = "black"
if (walkable_blocks.includes(tileval) && walkable_props.includes(propval)) {
player.y = player.newY;
player.x = player.newX;
if (player.x <= 0) {
player.x = 0
}
if (player.y <= 0) {
player.y = 0
}
if (player.x + player.size >= c.width) {
player.x = c.width - player.size;
}
if (player.y + player.size >= c.height) {
player.y = c.height - player.size;
}
} else if (lvlup_blocks.includes(tileval)) {
document.getElementById("body").style.ainmation = "fadeInAnimation";
document.getElementById('body').style.animationPlayState = "running";
if (timer == null) {
timer = setTimeout(function() {
levelnum++;
player.x = 280;
player.y = 150;
timer = null;
}, 2500)
if (aniTimer == null) {
aniTimer = setTimeout(function() {
document.getElementById("body").style.animationPlayState = "paused";
clearTimeout(aniTimer)
aniTimer = null;
}, 5000)
}
} else {
}
} else if (lvldown_blocks.includes(tileval)) {
document.getElementById("body").style.ainmation = "fadeInAnimation";
document.getElementById('body').style.animationPlayState = "running";
if (timer == null) {
timer = setTimeout(function() {
levelnum--;
player.x = 33;
player.y = 150;
timer = null;
}, 2500)
}
if (aniTimer == null) {
aniTimer = setTimeout(function() {
document.getElementById("body").style.animationPlayState = "paused";
clearTimeout(aniTimer);
aniTimer = null;
}, 5000)
}
} else {
player.y = player.y;
player.x = player.x;
if (player.x <= 0) {
player.x = 0
}
if (player.y <= 0) {
player.y = 0
}
if (player.x + player.size >= c.width) {
player.x = c.width - player.size;
}
if (player.y + player.size >= c.height) {
player.y = c.height - player.size;
}
}
ctx.fillRect(0, 0, c.width, c.height)
drawlvl()
drawprops()
drawEnemy()
playerani()
ctx.drawImage(window.aniimg, 64 * (Math.floor(aniframe)), window.aniimgY, 64, 64, player.x - 16, player.y - 16, 48, 48)
}
var gameintertval = setInterval(function() {
gameLoop()
}, 10)
document.addEventListener('keydown', function(event) {
controller.keyParse(event.keyCode)
})
document.addEventListener('keyup', function(event) {
controller.keyStop(event.keyCode)
})
body {
zoom: 100%;
animation: fadeInAnimation ease 5s;
animation-play-state: paused;
animation-iteration-count: infinite;
}
#keyframes fadeInAnimation {
0% {
opacity: 1;
}
50% {
opacity: 0;
}
100% {
opacity: 1;
}
}
canvas{
position: absolute;
}
#props{
z-index: 1000;
}
#c{
z-index: -1000;
}
<html>
<head>
<title>TileGame</title>
<base href="http://ryangrube.com/projects/tilegame/">
</head>
<body id="body">
<img id="img" style="display: none;" src="TileSet_V1.png">
<img id="img2" style="display: none;" src="TileSet_V2.png">
<img id="img3" style="display: none;" src="TileSet_V3.png">
<img id="aniimg1" style="display: none;" src="no_dagger.png">
<img id="aniimg2" style="display: none;" src="dagger.png">
<canvas id="c" width="320" height="320" style="background-color: black;border:3px solid black;"></canvas>
<canvas id="props" width="320" height="320" style="border:3px solid black;"></canvas>
<script src="map.js"></script>
<script src="props.js"></script>
<script src="drawprops.js"></script>
<script src="enemy.js"></script>
<script src="drawenemy.js"></script>
</body>
</html>

Related

i cant get my shot to travel directly to my cursor

I am making a 2d game with javascript and i can't get the shot to travel in a line directly to the cursor. I want it so when the shoot function is called th make the shot travel to the cursor and not alter the path when the cursor is moved after the shot is already out. Right now it is onnly going diagonal to the player
<!DOCTYPE html>
<html lang="en" onclick="shoot()">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta charset="utf-8">
<style>
canvas {
border:4px solid #000000;
background-color: #26af2d;
}
</style>
<body onload="startGame()">
<div name="buttonDiv">
<button type="button" id="startRoundBtn" onclick= startWave();>dont mind this</button>
</div>
<p id="demo">
</p>
<script>
let playerHealth = 100;
let shot = false;
let enemyOut = false;
let waveActive = false;
let enemyDmg = 25;
let playerImmuneTime = 0;
//start
var player;
var TopEdge;
var BottomEdge;
var RightEdge;
var LeftEdge;
let Enemy;
var projectile;
function startGame() {
player = new component(30, 30, "red", 10, 120);
TopEdge = new component(10000, 200, "purple", 0, -200);
BottomEdge = new component(10000, 1, "purple", 0, 500);
RightEdge = new component(1000, 500, "purple", 1150, 0);
LeftEdge = new component(1000, 500, "purple", -1000, 0);
var x = document.getElementById("startRoundBtn");
myGameArea.start();
}
//game area
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 1150;
this.canvas.height = 500;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas,
document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 10);
window.addEventListener('keydown', function (e) {
myGameArea.keys = (myGameArea.keys || []);
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
},
clear : function(){
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function(){
clearInterval(this.interval);
}
}
//coords
var pointerX = 0;
var pointerY = 0;
document.onmousemove = function(event) {
pointerX = event.pageX;
pointerY = event.pageY;
}
setInterval(pointerCheck, 1);
function pointerCheck() {
var cursorCoords = 'Cursor Location: '+pointerX+'X, '+pointerY+'Y health: ' + playerHealth + ' imune time:' +playerImmuneTime
document.getElementById("demo").innerHTML = cursorCoords;
}
//compenents
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
//new pos
this.newPos = function() {
this.X += this.speedX;
this.Y += this.speedY;
}
//crashing
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) ||
(mytop > otherbottom) ||
(myright < otherleft) ||
(myleft > otherright)) {
crash = false;
}
return crash;
}
}
//updates
function updateGameArea() {
myGameArea.clear();
if (playerHealth > 0) {
player.newPos();
player.update();
}
TopEdge.update();
BottomEdge.update();
RightEdge.update();
LeftEdge.update();
if (shot == true) {
projectile.update();
projectile.newPos();
projectile.speedX = 0;
projectile.speedY = 0;
}
if (enemyOut == true && playerHealth > 0) {
if (Enemy.crashWith(player) && playerImmuneTime <= 0) {
playerHealth = playerHealth -= enemyDmg;
playerImmuneTime = 50;
} if (playerImmuneTime >= 0) {
playerImmuneTime -= 1;
}
Enemy.newPos();
Enemy.update();
Enemy.speedX = 0;
Enemy.speedY = 0;
}
player.speedX = 0;
player.speedY = 0;
//movement
if (myGameArea.keys[65] ) {player.speedX = -2.5; }
if (myGameArea.keys[68] ) {player.speedX = 2.5; }
if (myGameArea.keys[87] ) {player.speedY = -2.5; }
if (myGameArea.keys[83] ) {player.speedY = 2.5; }
if (myGameArea.keys[82]) {waveActive = true;}
if (myGameArea.keys[75]) {waveActive = false;}
if (enemyOut == true && player.x >= Enemy.x) {Enemy.speedX = 1; }
if (enemyOut == true && player.x <= Enemy.x) {Enemy.speedX = -1; }
if (enemyOut == true && player.y >= Enemy.y) {Enemy.speedY = 1; }
if (enemyOut == true && player.y <= Enemy.y) {Enemy.speedY = -1; }
if (waveActive == true && enemyOut == false) {
createEnemy();
}
if (shot == true && pointerX > player.x) {projectile.speedX = 10};
if (shot == true && pointerX < player.x) {projectile.speedX = -10};
if (shot == true && pointerY > player.y) {projectile.speedY = 10};
if (shot == true && pointerY < player.y) {projectile.speedY = -10};
if (shot == true && enemyOut == true && projectile.crashWith(Enemy)) {
shot = false;
enemyOut = false;
waveActive = false;
}
//edges of game area
if (player.crashWith(TopEdge) && myGameArea.keys[87]) {
player.speedY = 0;
}
if (player.crashWith(RightEdge) && myGameArea.keys[68]) {
player.speedX = 0;
}
if (player.crashWith(BottomEdge) && myGameArea.keys[83]) {
player.speedY = 0;
}
if (player.crashWith(LeftEdge) && myGameArea.keys[65]) {
player.speedX = 0;
}
player.x += player.speedX;
player.y += player.speedY;
Enemy.x += Enemy.speedX;
Enemy.y += Enemy.speedY;
projectile.x += projectile.speedX;
projectile.y += projectile.speedY;
}
function createEnemy() {
Enemy = new component(30, 30, "purple",
Math.floor(Math.random() * 1100),
Math.floor(Math.random() * 500));
enemyOut = true;
}
function shoot() {
let midPlayerX = player.x + 12;
let midPlayerY = player.y + 12;
projectile = new component(5, 5, "white", midPlayerX, midPlayerY);
shot = true;
}
</script>
</body>
</html>
you need to 'freeze' the pointerX and pointerY values between the shot being fired and reaching its destination (otherwise those values will change on mousemove).
You already have shot=true when the projectile is launched so it can be read in a conditional you add to your mousemove event listener. That will take care of freezing the pointers when the projectile is fired :
document.onmousemove = function (event) {
if (!shot) {
pointerX = event.pageX
pointerY = event.pageY
} // prevent updates to pointers when shot is fired;
}
but you will need to reactivate the listener by setting shot to false when the projectile colides with the stored pointerX and pointerY values.

Uncaught TypeError: Cannot read property 'getContext' of null. In chrome app development

I am making an app for the Chrome Web Store. It is a clone of the Doodle Jump game. When I test and load it as an unpacked extension, this error keeps coming up.
Uncaught TypeError: Cannot read property 'getContext' of null
My code is here:
Javascript
function startGame() {
// RequestAnimFrame: a browser API for getting smooth animations
window.requestAnimFrame = (function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var width = 422,
height = 552;
canvas.width = width;
canvas.height = height;
//Variables for game
var platforms = [],
image = document.getElementById("sprite"),
player, platformCount = 10,
position = 0,
gravity = 0.2,
animloop,
flag = 0,
menuloop, broken = 0,
dir, score = 0, firstRun = true;
//Base object
var Base = function() {
this.height = 5;
this.width = width;
//Sprite clipping
this.cx = 0;
this.cy = 614;
this.cwidth = 100;
this.cheight = 5;
this.moved = 0;
this.x = 0;
this.y = height - this.height;
this.draw = function() {
try {
ctx.drawImage(image, this.cx, this.cy, this.cwidth, this.cheight, this.x, this.y, this.width, this.height);
} catch (e) {}
};
};
var base = new Base();
//Player object
var Player = function() {
this.vy = 11;
this.vx = 0;
this.isMovingLeft = false;
this.isMovingRight = false;
this.isDead = false;
this.width = 55;
this.height = 40;
//Sprite clipping
this.cx = 0;
this.cy = 0;
this.cwidth = 110;
this.cheight = 80;
this.dir = "left";
this.x = width / 2 - this.width / 2;
this.y = height;
//Function to draw it
this.draw = function() {
try {
if (this.dir == "right") this.cy = 121;
else if (this.dir == "left") this.cy = 201;
else if (this.dir == "right_land") this.cy = 289;
else if (this.dir == "left_land") this.cy = 371;
ctx.drawImage(image, this.cx, this.cy, this.cwidth, this.cheight, this.x, this.y, this.width, this.height);
} catch (e) {}
};
this.jump = function() {
this.vy = -8;
document.getElementById('audio').innerHTML='<audio src="sounds/pup.mp3" preload="auto" autoplay autobuffer></audio>'
};
this.jumpHigh = function() {
this.vy = -16;
document.getElementById('audio').innerHTML='<audio src="sounds/high.mp3" preload="auto" autoplay autobuffer></audio>'
};
};
player = new Player();
//Platform class
function Platform() {
this.width = 70;
this.height = 17;
this.x = Math.random() * (width - this.width);
this.y = position;
position += (height / platformCount);
this.flag = 0;
this.state = 0;
//Sprite clipping
this.cx = 0;
this.cy = 0;
this.cwidth = 105;
this.cheight = 31;
//Function to draw it
this.draw = function() {
try {
if (this.type == 1) this.cy = 0;
else if (this.type == 2) this.cy = 61;
else if (this.type == 3 && this.flag === 0) this.cy = 31;
else if (this.type == 3 && this.flag == 1) this.cy = 1000;
else if (this.type == 4 && this.state === 0) this.cy = 90;
else if (this.type == 4 && this.state == 1) this.cy = 1000;
ctx.drawImage(image, this.cx, this.cy, this.cwidth, this.cheight, this.x, this.y, this.width, this.height);
} catch (e) {}
};
//Platform types
//1: Normal
//2: Moving
//3: Breakable (Go through)
//4: Vanishable
//Setting the probability of which type of platforms should be shown at what score
if (score >= 5000) this.types = [2, 3, 3, 3, 4, 4, 4, 4];
else if (score >= 2000 && score < 5000) this.types = [2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4];
else if (score >= 1000 && score < 2000) this.types = [2, 2, 2, 3, 3, 3, 3, 3];
else if (score >= 500 && score < 1000) this.types = [1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3];
else if (score >= 100 && score < 500) this.types = [1, 1, 1, 1, 2, 2];
else this.types = [1];
this.type = this.types[Math.floor(Math.random() * this.types.length)];
//We can't have two consecutive breakable platforms otherwise it will be impossible to reach another platform sometimes!
if (this.type == 3 && broken < 1) {
broken++;
} else if (this.type == 3 && broken >= 1) {
this.type = 1;
broken = 0;
}
this.moved = 0;
this.vx = 1;
}
for (var i = 0; i < platformCount; i++) {
platforms.push(new Platform());
}
//Broken platform object
var Platform_broken_substitute = function() {
this.height = 30;
this.width = 70;
this.x = 0;
this.y = 0;
//Sprite clipping
this.cx = 0;
this.cy = 554;
this.cwidth = 105;
this.cheight = 60;
this.appearance = false;
this.draw = function() {
try {
if (this.appearance === true) ctx.drawImage(image, this.cx, this.cy, this.cwidth, this.cheight, this.x, this.y, this.width, this.height);
else return;
} catch (e) {}
};
};
var platform_broken_substitute = new Platform_broken_substitute();
//Spring Class
var spring = function() {
this.x = 0;
this.y = 0;
this.width = 26;
this.height = 30;
//Sprite clipping
this.cx = 0;
this.cy = 0;
this.cwidth = 45;
this.cheight = 53;
this.state = 0;
this.draw = function() {
try {
if (this.state === 0) this.cy = 445;
else if (this.state == 1) this.cy = 501;
ctx.drawImage(image, this.cx, this.cy, this.cwidth, this.cheight, this.x, this.y, this.width, this.height);
} catch (e) {}
};
};
var Spring = new spring();
function init() {
//Variables for the game
var dir = "left",
jumpCount = 0;
firstRun = false;
//Function for clearing canvas in each consecutive frame
function paintCanvas() {
ctx.clearRect(0, 0, width, height);
}
//Player related calculations and functions
function playerCalc() {
if (dir == "left") {
player.dir = "left";
if (player.vy < -7 && player.vy > -15) player.dir = "left_land";
} else if (dir == "right") {
player.dir = "right";
if (player.vy < -7 && player.vy > -15) player.dir = "right_land";
}
//Adding keyboard controls
document.onkeydown = function(e) {
var key = e.keyCode;
if (key == 37) {
dir = "left";
player.isMovingLeft = true;
} else if (key == 39) {
dir = "right";
player.isMovingRight = true;
}
if(key == 32) {
if(firstRun === true)
init();
else
reset();
}
};
document.onkeyup = function(e) {
var key = e.keyCode;
if (key == 37) {
dir = "left";
player.isMovingLeft = false;
} else if (key == 39) {
dir = "right";
player.isMovingRight = false;
}
};
//Accelerations produces when the user hold the keys
if (player.isMovingLeft === true) {
player.x += player.vx;
player.vx -= 0.15;
} else {
player.x += player.vx;
if (player.vx < 0) player.vx += 0.1;
}
if (player.isMovingRight === true) {
player.x += player.vx;
player.vx += 0.15;
} else {
player.x += player.vx;
if (player.vx > 0) player.vx -= 0.1;
}
//Jump the player when it hits the base
if ((player.y + player.height) > base.y && base.y < height) player.jump();
//Gameover if it hits the bottom
if (base.y > height && (player.y + player.height) > height && player.isDead != "lol") {
player.isDead = true;
document.getElementById('audio').innerHTML='<audio src="sounds/gameover.mp3" preload="auto" autoplay autobuffer></audio>'
}
//Make the player move through walls
if (player.x > width) player.x = 0 - player.width;
else if (player.x < 0 - player.width) player.x = width;
//Movement of player affected by gravity
if (player.y >= (height / 2) - (player.height / 2)) {
player.y += player.vy;
player.vy += gravity;
}
//When the player reaches half height, move the platforms to create the illusion of scrolling and recreate the platforms that are out of viewport...
else {
platforms.forEach(function(p, i) {
if (player.vy < 0) {
p.y -= player.vy;
}
if (p.y > height) {
platforms[i] = new Platform();
platforms[i].y = p.y - height;
}
});
base.y -= player.vy;
player.vy += gravity;
if (player.vy >= 0) {
player.y += player.vy;
player.vy += gravity;
}
score++;
}
//Make the player jump when it collides with platforms
collides();
if (player.isDead === true) gameOver();
}
//Spring algorithms
function springCalc() {
var s = Spring;
var p = platforms[0];
if (p.type == 1 || p.type == 2) {
s.x = p.x + p.width / 2 - s.width / 2;
s.y = p.y - p.height - 10;
if (s.y > height / 1.1) s.state = 0;
s.draw();
} else {
s.x = 0 - s.width;
s.y = 0 - s.height;
}
}
//Platform's horizontal movement (and falling) algo
function platformCalc() {
var subs = platform_broken_substitute;
platforms.forEach(function(p, i) {
if (p.type == 2) {
if (p.x < 0 || p.x + p.width > width) p.vx *= -1;
p.x += p.vx;
}
if (p.flag == 1 && subs.appearance === false && jumpCount === 0) {
subs.x = p.x;
subs.y = p.y;
subs.appearance = true;
jumpCount++;
}
p.draw();
});
if (subs.appearance === true) {
subs.draw();
subs.y += 8;
}
if (subs.y > height) subs.appearance = false;
}
function collides() {
//Platforms
platforms.forEach(function(p, i) {
if (player.vy > 0 && p.state === 0 && (player.x + 15 < p.x + p.width) && (player.x + player.width - 15 > p.x) && (player.y + player.height > p.y) && (player.y + player.height < p.y + p.height)) {
if (p.type == 3 && p.flag === 0) {
p.flag = 1;
jumpCount = 0;
return;
} else if (p.type == 4 && p.state === 0) {
player.jump();
p.state = 1;
} else if (p.flag == 1) return;
else {
player.jump();
}
}
});
//Springs
var s = Spring;
if (player.vy > 0 && (s.state === 0) && (player.x + 15 < s.x + s.width) && (player.x + player.width - 15 > s.x) && (player.y + player.height > s.y) && (player.y + player.height < s.y + s.height)) {
s.state = 1;
player.jumpHigh();
}
}
function updateScore() {
var scoreText = document.getElementById("score");
scoreText.innerHTML = score;
}
function gameOver() {
platforms.forEach(function(p, i) {
p.y -= 12;
});
if(player.y > height/2 && flag === 0) {
player.y -= 8;
player.vy = 0;
}
else if(player.y < height / 2) flag = 1;
else if(player.y + player.height > height) {
showGoMenu();
hideScore();
player.isDead = "lol";
}
}
//Function to update everything
function update() {
paintCanvas();
platformCalc();
springCalc();
playerCalc();
player.draw();
base.draw();
updateScore();
}
menuLoop = function(){return;};
animloop = function() {
update();
requestAnimFrame(animloop);
};
animloop();
hideMenu();
showScore();
}
function reset() {
hideGoMenu();
showScore();
player.isDead = false;
flag = 0;
position = 0;
score = 0;
base = new Base();
player = new Player();
Spring = new spring();
platform_broken_substitute = new Platform_broken_substitute();
platforms = [];
for (var i = 0; i < platformCount; i++) {
platforms.push(new Platform());
}
}
//Hides the menu
function hideMenu() {
var menu = document.getElementById("mainMenu");
menu.style.zIndex = -1;
}
//Shows the game over menu
function showGoMenu() {
var menu = document.getElementById("gameOverMenu");
menu.style.zIndex = 1;
menu.style.visibility = "visible";
var scoreText = document.getElementById("go_score");
scoreText.innerHTML = "Ваш результат " + score + " очков!";
}
//Hides the game over menu
function hideGoMenu() {
var menu = document.getElementById("gameOverMenu");
menu.style.zIndex = -1;
menu.style.visibility = "hidden";
}
//Show ScoreBoard
function showScore() {
var menu = document.getElementById("scoreBoard");
menu.style.zIndex = 1;
}
//Hide ScoreBoard
function hideScore() {
var menu = document.getElementById("scoreBoard");
menu.style.zIndex = -1;
}
function playerJump() {
player.y += player.vy;
player.vy += gravity;
if (player.vy > 0 &&
(player.x + 15 < 260) &&
(player.x + player.width - 15 > 155) &&
(player.y + player.height > 475) &&
(player.y + player.height < 500))
player.jump();
if (dir == "left") {
player.dir = "left";
if (player.vy < -7 && player.vy > -15) player.dir = "left_land";
} else if (dir == "right") {
player.dir = "right";
if (player.vy < -7 && player.vy > -15) player.dir = "right_land";
}
//Adding keyboard controls
document.onkeydown = function(e) {
var key = e.keyCode;
if (key == 37) {
dir = "left";
player.isMovingLeft = true;
} else if (key == 39) {
dir = "right";
player.isMovingRight = true;
}
if(key == 32) {
if(firstRun === true) {
init();
firstRun = false;
}
else
reset();
}
};
document.onkeyup = function(e) {
var key = e.keyCode;
if (key == 37) {
dir = "left";
player.isMovingLeft = false;
} else if (key == 39) {
dir = "right";
player.isMovingRight = false;
}
};
//Accelerations produces when the user hold the keys
if (player.isMovingLeft === true) {
player.x += player.vx;
player.vx -= 0.15;
} else {
player.x += player.vx;
if (player.vx < 0) player.vx += 0.1;
}
if (player.isMovingRight === true) {
player.x += player.vx;
player.vx += 0.15;
} else {
player.x += player.vx;
if (player.vx > 0) player.vx -= 0.1;
}
//Jump the player when it hits the base
if ((player.y + player.height) > base.y && base.y < height) player.jump();
//Make the player move through walls
if (player.x > width) player.x = 0 - player.width;
else if (player.x < 0 - player.width) player.x = width;
player.draw();
}
function update() {
ctx.clearRect(0, 0, width, height);
playerJump();
}
menuLoop = function() {
update();
requestAnimFrame(menuLoop);
};
menuLoop();
}
document.addEventListener("DOMContentLoaded", startGame, false);
<!DOCTYPE HTML>
<html>
<head>
<title>Doodle Jump</title>
<style type="text/css">
#import url(Gloria%20Hallelujah);
*{box-sizing: border-box;}
body {
margin: 0; padding: 0;
font-family: 'Gloria Hallelujah', cursive;
}
.container {
height: 552px;
width: 422px;
position: relative;
margin: 20px auto;
overflow: hidden;
}
canvas {
height: 552px;
width: 422px;
display: block;
background: url(images/Y0BMP.png) top left;
}
#scoreBoard {
width: 420px;
height: 50px;
background: rgba(182, 200, 220, 0.7);
position: absolute;
top: -3px;
left: 0;
z-index: -1;
border-image: url(images/5BBsR.png) 100 5 round;
}
#scoreBoard p {
font-size: 20px;
padding: 0;
line-height: 47px;
margin: 0px 0 0 5px;
}
img {display: none}
#mainMenu, #gameOverMenu {
height: 100%;
width: 100%;
text-align: center;
position: absolute;
top: 0;
left: 0;
z-index: 2;
}
#gameOverMenu {
visibility: hidden;
}
h2, h3, h1 {font-weight: normal}
h1 {
font-size: 60px;
color: #5a5816;
transform: rotate(-10deg);
margin: 0px;
}
h3 {text-align: right; margin: -10px 20px 0 0; color: #5e96be}
h3 a {color: #5a5816}
.button {
width: 105px;
height: 31px;
background: url(images/2WEhF.png) 0 0 no-repeat;
display: block;
color: #000;
font-size: 12px;
line-height: 31px;
text-decoration: none;
position: absolute;
left: 50%;
bottom: 50px;
margin-left: -53px;
}
.info {position: absolute; right: 20px; bottom: 00px; margin: 0; color: green}
.info .key {
width: 16px;
height: 16px;
background: url(images/2WEhF.png) no-repeat;
text-indent: -9999px;
display: inline-block;
}
.info .key.left {background-position: -92px -621px;}
.info .key.right {background-position: -92px -641px;}
</style>
</head>
<body><div style="position:absolute;z-index:999;padding:10px;top:0;right:0;background:#000" id="sxz03">
<div style="float:right;padding-left:10px"><img onclick="document.getElementById('sxz03').style.display='none'" src="images/x.gif" width="15" alt="" /></div>
<br>
<div style="position:absolute;top:-100px"></div>
</div>
<div class="container">
<canvas id="canvas"></canvas>
<div id="mainMenu">
<h1>doodle jump</h1>
<h3>A HTML5 game</h3>
<a class="button" href="javascript:init()">Play</a>
</div>
<div id="gameOverMenu">
<h1>Game Over!</h1>
<h3 id="go_score">Your score was ...</h3>
<a class="button" href="javascript:reset()">Play Again</a>
</div>
<!-- Preloading image ;) -->
<img id="sprite" src="images/2WEhF.png"/>
<div id="scoreBoard">
<p id="score">0</p>
</div>
</div>
<div id="audio"></div>
<script src="jquery.min.js"></script>
<script src="game.js"></script>
</body>
</html>
So when I run this, the intro works, but when I click the play button, nothing happens. If you want to run this code, I will put a download link for the folder that I used in this question.

JavaScript - moving object to a new location

I'm writing simple "snake" game and I'm facing this issue:
every tame my snake hits the red circle (apple) , apple should be moved to a new location on the canvas. Right now new apple appears, but the old one does not disappear ( it should) , and also when there are more than 2 apples on the canvas they create a filled figure... it looks like this: ibb.co/nrYdLQ (also shouldn't happen).
The code responsible for moving an apple is this:
if (!this.objectCollide(myApple)) {
this.segments.pop();
} else {
myApple = new block(Math.floor(Math.random() * gameField.width),Math.floor(Math.random() * gameField.height))
};
and I have no idea why It's working like I described above, instead just moving an apple to a new location and removing old one.
Please help.
JSFiddle: https://jsfiddle.net/e1ga0fpm/
full JavaScript code:
var gameField = document.getElementById('gameField');
var ctx = gameField.getContext("2d");
var blockSize = 10;
columnCt = gameField.width / blockSize;
rowsCt = gameField.height / blockSize;
var block = function(x, y) {
this.x = x;
this.y = y;
}
block.prototype.drawBlock = function() {
ctx.fillStyle = "blue";
ctx.fillRect(this.x * blockSize, this.y * blockSize, blockSize,
blockSize);
};
block.prototype.drawApple = function() {
ctx.fillStyle = "red";
ctx.textBaseline = "bottom";
ctx.arc(this.x, this.y, 6, 2 * Math.PI, false);
ctx.fill();
}
var Snake = function() {
this.segments = [new block(20, 20), new block(19, 20), new block(18, 20), new block(17, 20),
new block(16, 20), new block(15, 20), new block(14, 20), new block(13, 20), new block(12, 20),
new block(11, 20), new block(10, 20)
];
this.direction = "right";
}
Snake.prototype.drawSnake = function() {
for (i = 0; i < this.segments.length; i++) {
this.segments[i].drawBlock();
}
}
Snake.prototype.setDirection = function(dir) {
if (this.direction == "left" && dir == "right" || this.direction == "right" && dir == "left" || this.direction == "up" && dir == "down" ||
this.direction == "down" && dir == "up") {
return
} else {
this.direction = dir;
};
};
Snake.prototype.objectCollide = function(obj) {
if (this.segments[0].x == Math.round(obj.x / blockSize) && this.segments[0].y == Math.round(obj.y / blockSize)) {
return true
} else {
return false
}
};
Snake.prototype.move = function() {
var head = this.segments[0];
var newHead;
switch (this.direction) {
case "right":
newHead = new block(head.x + 1, head.y);
break;
case "left":
newHead = new block(head.x - 1, head.y)
break;
case "down":
newHead = new block(head.x, head.y + 1)
break;
case "up":
newHead = new block(head.x, head.y - 1)
break;
}
this.segments.unshift(newHead);
if (!this.objectCollide(myApple)) {
this.segments.pop();
} else {
myApple = new block(Math.floor(Math.random() * gameField.width),Math.floor(Math.random() * gameField.height))
};
var collision = newHead.x >= columnCt || newHead.x <= -1 ||
newHead.y >= rowsCt || newHead.y <= -1;
for (i = 1; i < this.segments.length; i++) {
if (this.segments[i].x == newHead.x && this.segments[i].y == newHead.y) {
collision = true;
break;
};
};
if (collision) {
clearInterval(myFun);
};
};
var mySnake = new Snake()
mySnake.drawSnake();
var myApple = new block(Math.floor(Math.random() * gameField.width),
Math.floor(Math.random() * gameField.height));
var myFun = setInterval(function() {
ctx.clearRect(0, 0, gameField.width, gameField.height);
mySnake.move();
mySnake.drawSnake();
myApple.drawApple();
}, 100)
var directions = {
37: "left",
38: "up",
39: "right",
40: "down"
};
document.onkeydown = function(event) {
var newDirection = directions[event.keyCode]
if (newDirection != undefined) {
mySnake.setDirection(newDirection);
};
Im quite unshure why the apple is not "eaten" however, i might know why it looks so weird:
If you draw to a canvas it looks like a pen. So whenever you draw a new apple, the pen moves to that position, and draws a line. After a few apples, if you call .fill(), this (yet invisible) line, gets filled. So you need to move the pen before you draw:
block.prototype.drawApple = function() {
ctx.fillStyle = "red";
ctx.textBaseline = "bottom";
ctx.moveTo(this.x,this.y);
ctx.arc(this.x, this.y, 6, 2 * Math.PI, false);
ctx.fill();
}
You forgot to beginpath while you draw apple. Also when apple eaten, you have to add new block to snake. Check edited code below.
Here is updated fiddle
block.prototype.drawApple = function() {
ctx.fillStyle = "red";
ctx.textBaseline = "bottom";
ctx.beginPath();
ctx.arc(this.x, this.y, 6, 2 * Math.PI, false);
ctx.fill();
}
var gameField = document.getElementById('gameField');
var ctx = gameField.getContext("2d");
var blockSize = 10;
columnCt = gameField.width / blockSize;
rowsCt = gameField.height / blockSize;
var block = function(x, y) {
this.x = x;
this.y = y;
}
block.prototype.drawBlock = function() {
ctx.fillStyle = "blue";
ctx.fillRect(this.x * blockSize, this.y * blockSize, blockSize,
blockSize);
};
block.prototype.drawApple = function() {
ctx.fillStyle = "red";
ctx.textBaseline = "bottom";
ctx.beginPath();
ctx.arc(this.x, this.y, 6, 2 * Math.PI, false);
ctx.fill();
}
var Snake = function() {
this.segments = [new block(20, 20), new block(19, 20), new block(18, 20), new block(17, 20),
new block(16, 20), new block(15, 20)
];
this.direction = "right";
}
Snake.prototype.drawSnake = function() {
for (i = 0; i < this.segments.length; i++) {
this.segments[i].drawBlock();
}
}
Snake.prototype.setDirection = function(dir) {
if (this.direction == "left" && dir == "right" || this.direction == "right" && dir == "left" || this.direction == "up" && dir == "down" ||
this.direction == "down" && dir == "up") {
return
} else {
this.direction = dir;
};
};
Snake.prototype.objectCollide = function(obj) {
if (this.segments[0].x == Math.round(obj.x / blockSize) && this.segments[0].y == Math.round(obj.y / blockSize)) {
return true
} else {
return false
}
};
Snake.prototype.move = function() {
var head = this.segments[0];
var newHead;
switch (this.direction) {
case "right":
newHead = new block(head.x + 1, head.y);
break;
case "left":
newHead = new block(head.x - 1, head.y)
break;
case "down":
newHead = new block(head.x, head.y + 1)
break;
case "up":
newHead = new block(head.x, head.y - 1)
break;
}
this.segments.unshift(newHead);
if (!this.objectCollide(myApple)) {
this.segments.pop();
} else {
myApple = new block(Math.floor(Math.random() * gameField.width), Math.floor(Math.random() * gameField.height));
this.segments.push(new block(this.segments[0][0], 20))
};
var collision = newHead.x >= columnCt || newHead.x <= -1 ||
newHead.y >= rowsCt || newHead.y <= -1;
for (i = 1; i < this.segments.length; i++) {
if (this.segments[i].x == newHead.x && this.segments[i].y == newHead.y) {
collision = true;
break;
};
};
if (collision) {
clearInterval(myFun);
};
};
var mySnake = new Snake()
mySnake.drawSnake();
var myApple = new block(Math.floor(Math.random() * gameField.width),
Math.floor(Math.random() * gameField.height));
var myFun = setInterval(function() {
ctx.clearRect(0, 0, gameField.width, gameField.height);
mySnake.move();
mySnake.drawSnake();
myApple.drawApple();
}, 100)
var directions = {
37: "left",
38: "up",
39: "right",
40: "down"
};
document.onkeydown = function(event) {
var newDirection = directions[event.keyCode]
if (newDirection != undefined) {
mySnake.setDirection(newDirection);
};
};
canvas {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
border: 5px solid grey;
}
<canvas id="gameField" height="500" width="500">
</canvas>

Can't Make a Player Two

I am trying to add a second player to javascript game but the code isn't working. I need some instruction on how to follow through with this. The second player doesn't need to be fancy, a different color square would suffice. My current player is the green square. Any information would be helpful thank you.
var myObstacle;
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
function startGame() {}
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = 700,
height =600,
player = {
x : 1,
y : 7,
width : 25,
height : 25,
speed: 10,
velX: 0,
velY: 0,
jumping: false
},
keys = [],
friction = .9,
gravity = .8;
canvas.width = width;
canvas.height = height;
function update(){
// check keys
if (keys[38] || keys[32]) {
// up arrow or space
if(!player.jumping){
player.jumping = true;
player.velY = -player.speed*.1;
}
}
if (keys[39]) {
// right arrow
if (player.velX < player.speed) {
player.velX++;
}
}
if (keys[37]) {
// left arrow
if (player.velX > -player.speed) {
player.velX--;
}
}
player.velX *= friction;
player.velY += gravity;
player.x += player.velX;
player.y += player.velY;
if (player.x >= width-player.width) {
player.x = width-player.width;
} else if (player.x <= 0) {
player.x = 0;
}
if(player.y >= height-player.height){
player.y = height - player.height;
player.jumping = false;
}
ctx.clearRect(0,0,width,height);
ctx.fillStyle = "green";
ctx.fillRect(player.x, player.y, player.width, player.height);
requestAnimationFrame(update);
}
document.body.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
keys[e.keyCode] = false;
});
window.addEventListener("load",function(){
update();
});
<html>
<head>
<title>Square Stairs™</title>
</head>
<body bgcolor="#000">
<canvas id="canvas" style="border:3px solid #fff"></canvas>
</body>
</html>
Please help if you can, Thank You.
Use a little bit of OOP:
var myObstacle;
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
function Player(color){
this.x = 1;
this.y = 7
this.width = 25
this.height= 25
this.speed= 10
this.velX= 0
this.velY= 0
this.jumping= false
this.color = color;
}
function startGame() {}
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = 700,
height =600,
player = new Player('green'),
player2 = new Player('red')
keys = [],
friction = .9,
gravity = .8;
canvas.width = width;
canvas.height = height;
function update(){
// check keys
if (keys[38] || keys[32]) {
// up arrow or space
if(!player.jumping){
player.jumping = true;
player.velY = -player.speed*.1;
}
}
if (keys[39]) {
// right arrow
if (player.velX < player.speed) {
player.velX++;
}
}
if (keys[37]) {
// left arrow
if (player.velX > -player.speed) {
player.velX--;
}
}
player.velX *= friction;
player.velY += gravity;
player.x += player.velX;
player.y += player.velY;
if (player.x >= width-player.width) {
player.x = width-player.width;
} else if (player.x <= 0) {
player.x = 0;
}
if(player.y >= height-player.height){
player.y = height - player.height;
player.jumping = false;
}
player2.velY += gravity;
player2.x += player2.velX;
player2.y += player2.velY;
if (player2.x >= width-player2.width) {
player2.x = width-player2.width;
} else if (player2.x <= 0) {
player2.x = 0;
}
if(player2.y >= height-player2.height){
player2.y = height - player2.height;
player2.jumping = false;
}
ctx.clearRect(0,0,width,height);
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.width, player.height);
ctx.fillStyle = player2.color;
ctx.fillRect(player2.x, player2.y, player2.width, player2.height);
requestAnimationFrame(update);
}
document.body.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
keys[e.keyCode] = false;
});
window.addEventListener("load",function(){
update();
});
<html>
<head>
<title>Square Stairs™</title>
</head>
<body bgcolor="#000">
<canvas id="canvas" style="border:3px solid #fff"></canvas>
</body>
</html>
Okay, I couldn't resist... I added even more OOP. So, now you can add as many players as you'd like. The important distinction is the color and the key mappings. My example (arbitrarily) adds three players:
var players=[];
players.push(new Player('green', {
32: 'jump',
37: 'left',
38: 'jump',
39: 'right'
}))
players.push(new Player('red', {
56: 'jump',
52: 'left',
54: 'right'
}, width-25))
players.push(new Player('blue', {
87: 'jump',
65: 'left',
68: 'right'
}, (width-25)/2))
var myObstacle;
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
function startGame() {}
function Player(color,keymap,x) {
this.x = (typeof x === 'undefined') ? 1 : x;
this.y = 7;
this.width = 25;
this.height = 25;
this.speed = 10;
this.velX = 0;
this.velY = 0;
this.jumping= false;
this.keymap = {}
for (let key in keymap) {
switch (keymap[key]) {
case 'jump':
this.keymap[key] = this.jump
break;
case 'left':
this.keymap[key] = this.moveLeft
break;
case 'right':
this.keymap[key] = this.moveRight
break;
}
}
this.color = color;
} // Player()
Player.prototype.jump=function () {
if (!this.jumping) {
this.jumping = true;
this.velY = -this.speed*1.5;
}
}
Player.prototype.moveRight = function () {
if (this.velX < this.speed) {
this.velX++;
}
}
Player.prototype.moveLeft = function () {
if (this.velX > -this.speed) {
this.velX--;
}
}
// Globals
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = 700,
height =600,
keys = [],
friction = .9,
gravity = .8;
canvas.width = width;
canvas.height = height;
// Set up players
var players=[];
players.push(new Player('green', {
32: 'jump',
37: 'left',
38: 'jump',
39: 'right'
}))
players.push(new Player('red', {
56: 'jump',
52: 'left',
54: 'right'
}, width-25))
players.push(new Player('blue', {
87: 'jump',
65: 'left',
68: 'right'
}, (width-25)/2))
function update() {
ctx.clearRect(0,0,width,height);
players.forEach(player => {
// check player-specific keys
for (let i in player.keymap)
{
if (keys[i] && typeof player.keymap[i] === 'function')
player.keymap[i].bind(player)();
}
player.velX *= friction;
player.velY += gravity;
player.x += player.velX;
player.y += player.velY;
if (player.x >= width-player.width) {
player.x = width-player.width;
} else if (player.x <= 0) {
player.x = 0;
}
if (player.y >= height-player.height) {
player.y = height - player.height;
player.jumping = false;
}
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.width, player.height);
}) // player.forEach
requestAnimationFrame(update);
}
document.body.addEventListener("keydown", function(e) {
// console.log(e.keyCode);
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
keys[e.keyCode] = false;
});
window.addEventListener("load",function(){
update();
});
html>
<head>
<title>Square Stairs™</title>
</head>
<body bgcolor="#000">
<canvas id="canvas" style="border:3px solid #fff"></canvas>
</body>
</html>

javascript how to change variable on keyboard click

I have been trying to make my first game in javascript, its a pong like game where two players move their rectangles around to bump the ball in the other direction. I want it so that when player one hits the "a" key, their character moves left, when they hit the d key they move right.
Right now, nothing happens when I click the desired keys.
This is my current code:
$(document).ready(function() {
// things needed
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
//positions of elements at start
var ballposx = 400;
var ballposy = 50;
var balldx = 1;
var balldy = 2;
var balld2x = 0;
var balld2y = 0;
var p1posx = 80;
var p1posy = 225;
var p1dx = 0;
var p1dy = 0;
var p2posx = 620;
var p2posy = 225;
var p2dx = 0;
var p2dy = 0;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
//goal1
ctx.fillStyle = "#0F3F0F";
var goal1 = ctx.fillRect(0, 150, 50, 150);
//goal2
ctx.fillStyle = "#204050";
var goal2 = ctx.fillRect(750, 150, 50, 150);
ctx.beginPath();
//ball
var ball = ctx.arc(ballposx, ballposy, 60, 0, 2 * Math.PI);
ctx.stroke();
//p1
ctx.fillStyle = "#FF0000";
var p1 = ctx.fillRect(p1posx, p1posy, 40, 75);
//p2
ctx.fillStyle = "#0000FF";
var p1 = ctx.fillRect(p2posx, p2posy, 40, 75);
p1posx += p1dx;
p2posx += p2dx;
balldx += balld2x;
balldy += balld2y;
ballposx += balldx;
ballposy += balldy;
$(window).keypress(function(e) {
var code = e.which;
switch (code) {
case 65:
p1dx = 1;
case 68:
p1dx = -1;
case 37:
p2dx = -1;
case 39:
p2dx = 1;
default:
break;
}
});
if (ballposy === 240) {
balldy = -1;
} else if (ballposy === 60) {
balldy = 1;
} else if (ballposx === 60) {
balldx = 1;
} else if (ballposx === 740) {
balldx = -1;
} else if (ballposx === p1posx && ballposy < p1posy) {
balldx = 1;
} else if (ballposx === p2posx && ballposy < p2posy) {
balldx = -1;
}
}
setInterval(draw, 10);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<center>
<canvas id="myCanvas" width="800px" height="300px" style="border:1px solid #000000;"> Sorry your browser doesnt support this!</canvas></center>
You're adding another keypress handler every 10 ms. So after a few seconds there are thousands of handlers running every time you press a key, and this is probably bogging down the browser. You should just bind the handler once, outside the draw function.
And in the function, you need break statements in each case.
Your code tests are also wrong. Lowercase a is 97, not 65. And the values of p1dx are backwards -- if you want to go left, it should be -1, not 1.
$(document).ready(function() {
// things needed
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
//positions of elements at start
var ballposx = 400;
var ballposy = 50;
var balldx = 1;
var balldy = 2;
var balld2x = 0;
var balld2y = 0;
var p1posx = 80;
var p1posy = 225;
var p1dx = 0;
var p1dy = 0;
var p2posx = 620;
var p2posy = 225;
var p2dx = 0;
var p2dy = 0;
$(window).keypress(function(e) {
var code = e.which;
switch (code) {
case 97:
p1dx = -1;
break;
case 100:
p1dx = 1;
break;
case 37:
p2dx = -1;
break;
case 39:
p2dx = 1;
break;
default:
break;
}
});
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
//goal1
ctx.fillStyle = "#0F3F0F";
var goal1 = ctx.fillRect(0, 150, 50, 150);
//goal2
ctx.fillStyle = "#204050";
var goal2 = ctx.fillRect(750, 150, 50, 150);
ctx.beginPath();
//ball
var ball = ctx.arc(ballposx, ballposy, 60, 0, 2 * Math.PI);
ctx.stroke();
//p1
ctx.fillStyle = "#FF0000";
var p1 = ctx.fillRect(p1posx, p1posy, 40, 75);
//p2
ctx.fillStyle = "#0000FF";
var p1 = ctx.fillRect(p2posx, p2posy, 40, 75);
p1posx += p1dx;
p2posx += p2dx;
balldx += balld2x;
balldy += balld2y;
ballposx += balldx;
ballposy += balldy;
if (ballposy === 240) {
balldy = -1;
} else if (ballposy === 60) {
balldy = 1;
} else if (ballposx === 60) {
balldx = 1;
} else if (ballposx === 740) {
balldx = -1;
} else if (ballposx === p1posx && ballposy < p1posy) {
balldx = 1;
} else if (ballposx === p2posx && ballposy < p2posy) {
balldx = -1;
}
}
setInterval(draw, 10);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<center>
<canvas id="myCanvas" width="800px" height="300px" style="border:1px solid #000000;"> Sorry your browser doesnt support this!</canvas></center>
I didn't check the whole code, but ou should add the break; statement in every case, not just the default.
For example, your code should be something like:
$(window).keypress(function(e){
var code = e.which;
switch (code)
{
case 65:
p1dx = 1;
break;
case 68:
p1dx = -1;
break;
case 37:
p2dx = -1;
break;
case 39:
p2dx = 1;
break;
default:
break;
}
});

Categories

Resources