Javascript game - cannot read "y" property of undefined - javascript

So I was making this game today, and everything works perfectly, but sometimes this error shows up. I know what it means, and I've had it before, but this time it makes no sense. The game works perfectly fine, but sometimes when the bullet collides with the enemy the game freezes. I don't even know what to try anymore. Btw, if the error doesn't show up right away, just keep playing. Here's the code:
<html>
<head>
<title>Space shooter</title>
<style>
* {
margin:0;
}
canvas {
background: url("http://www.ufointernationalproject.com/wp-content/uploads/2017/03/space-03.jpg");
}
</style>
</head>
<body>
<canvas id="canvas" width="1350" height="630"></canvas>
<script>
var ctx = document.getElementById("canvas").getContext("2d"),
lastShot = Date.now(),
fireRate = 120,
bullets = [],
enemies = [],
enemySpeed = 1.5,
bulletSpeed = 20,
player = {
x: 600,
y: 250,
leftPressed: false,
rightPressed: false,
upPressed: false,
downPressed: false,
spacePressed: false,
speed: 5
};
var playerImage = new Image();
playerImage.src = "https://3.bp.blogspot.com/-jGC08Dy0zg8/U405cNq1-MI/AAAAAAAABqU/38d5rmV1S8Y/s1600/redfighter0006.png";
var enemyImage = new Image();
enemyImage.src = "https://a.fsdn.com/con/app/proj/partartspace/screenshots/Spaceship14.png/1";
function spawnEnemes() {
enemies.push({
x:Math.floor(Math.random() * 1250) + 1,
y:-100
})
}
setInterval(spawnEnemes, 500);
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(playerImage, player.x,player.y, 100, 100);
if (player.leftPressed) {
player.x -= player.speed;
}
if (player.rightPressed) {
player.x += player.speed;
}
if (player.upPressed) {
player.y -= player.speed;
}
if (player.downPressed) {
player.y += player.speed;
}
if (player.spacePressed && Date.now() - lastShot > fireRate) {
bullets.push({
x: player.x+50,
y: player.y
});
lastShot = Date.now();
}
bullets.forEach(function(bullet){
ctx.beginPath();
ctx.arc(bullet.x, bullet.y, 5, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();
bullet.y -= bulletSpeed;
});
enemies.forEach(function(enemy){
ctx.drawImage(enemyImage, enemy.x, enemy.y, 100,100);
enemy.y += enemySpeed;
});
for (var enemy = 0; enemy < enemies.length; enemy ++){
if(player.x < enemies[enemy].x + 80 &&
player.x + 80 > enemies[enemy].x &&
player.y < enemies[enemy].y + 65 &&
player.y + 100 > enemies[enemy].y)
{
document.location.reload();
}
for (var bullet = 0; bullet < bullets.length; bullet ++) {
if(bullets[bullet].y < enemies[enemy].y + 70 &&
bullets[bullet].y > enemies[enemy].y &&
bullets[bullet].x < enemies[enemy].x + 100 &&
bullets[bullet].x > enemies[enemy].x)
{
bullets.splice(bullet, 1);
enemies.splice(enemy, 1);
}
}
}
requestAnimationFrame(draw);
}
draw();
document.body.addEventListener("keydown", function(e) {
if (e.keyCode === 37) {
player.leftPressed = true;
}
else if (e.keyCode === 39) {
player.rightPressed = true;
}
else if (e.keyCode === 38) {
player.upPressed = true;
}
else if (e.keyCode === 40) {
player.downPressed = true;
}
else if (e.keyCode === 32) {
player.spacePressed = true;
}
});
document.body.addEventListener("keyup", function(e) {
if (e.keyCode === 37) {
player.leftPressed = false;
}
else if (e.keyCode === 39) {
player.rightPressed = false;
}
else if (e.keyCode === 38) {
player.upPressed = false;
}
else if (e.keyCode === 40) {
player.downPressed = false;
}
else if (e.keyCode === 32) {
player.spacePressed = false;
}
});
</script>
</body>
</html>

The problem seems to be when you splice. As you don't exit the loops, you end up accessing invalid positions after a removal.

Related

How to make my keyup function work inside of my game

This is somewhat a long shot, but I have been recently working on a game, and I have been pretty proud of it. Although it is no Minecraft, for my level of expertise, it is looking pretty good. There is just one problem with it though. My character travels all over the place. I have never been able to get him to only move one block. If there is anyone out there with a high level of coding expertise, please look at this code. There is a lot of code, so it might take a while, but I appreciate all the help I can get. If you can spot the problem, please notify me. Thank you.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
setInterval(terrainJumpLoop, 100);
setInterval(playerLeftLoop, 100);
setInterval(playerRightLoop, 100);
canvas.width = 1500;
canvas.height = 500;
var highTerrain = [];
var middleTerrain = [];
var lowTerrain = [];
var oreTerrain = [];
var biome = "";
var biomeSelector = 0;
var playerBlock = 0;
var terrainLength = canvas.width/25;
var unevenTerrainLocator = 0;
var gravityVar = 0;
var gravityStrength = 0;
var touchingGround = false;
var canMove = true;
var gameOn = false;
window.onerror = function (msg, url, lineNo, columnNo, error) {
document.getElementById("paragraph").innerHTML = "Game has Stopped Abruptly Due to Error in Code";
document.getElementById("wrongCodeLine").innerHTML = msg;
document.getElementById("errorLineNo").innerHTML = "Line Number: " + lineNo.toString();
window.stop();
};
var Player = {
x:0,
y:0,
width:25,
height:25,
color:"gold"
};
function paintGameTrees(x, y){
alert(x);
alert(y);
}
function paintGameTerrain(){
var grassBlock = {
width:25,
height:25,
color:"green"
};
var dirtBlock = {
width:25,
height:25,
color:"brown"
};
var stoneBlock = {
width:25,
height:25,
color:"gray"
};
var coalBlock = {
width:25,
height:25,
color:"#383838"
};
var ironBlock = {
width:25,
height:25,
color:"#C0C0C0"
};
var lava = {
width:25,
height:25,
color:"red"
};
var snowBlock = {
width:25,
height:25,
color:"white"
};
for(i = 0; i < terrainLength; i++){
if(highTerrain[i] === 0){
paintGameItems(i*25, canvas.height - 100, grassBlock.width, grassBlock.height, grassBlock.color);
}
else if(highTerrain[i] === 7){
paintGameItems(i*25, canvas.height - 100, snowBlock.width, snowBlock.height, snowBlock.color);
}
}
for(i = 0; i < terrainLength; i++){
if(middleTerrain[i] === 0){
paintGameItems(i*25, canvas.height - 75, grassBlock.width, grassBlock.height, grassBlock.color);
}
else if(middleTerrain[i] === 1){
paintGameItems(i*25, canvas.height - 75, dirtBlock.width, dirtBlock.height, dirtBlock.color);
}
else if(middleTerrain[i] === 7){
paintGameItems(i*25, canvas.height - 75, snowBlock.width, snowBlock.height, snowBlock.color);
}
}
for(i = 0; i < terrainLength; i++){
if(lowTerrain[i] === 0){
paintGameItems(i*25, canvas.height - 50, grassBlock.width, grassBlock.height, grassBlock.color);
}
else if(lowTerrain[i] === 1){
paintGameItems(i*25, canvas.height - 50, dirtBlock.width, dirtBlock.height, dirtBlock.color);
}
else if(lowTerrain[i] === 2){
paintGameItems(i*25, canvas.height - 50, stoneBlock.width, stoneBlock.height, stoneBlock.color);
}
else if(lowTerrain[i] === 7){
paintGameItems(i*25, canvas.height - 50, snowBlock.width, snowBlock.height, snowBlock.color);
}
}
for(i = 0; i < terrainLength; i++){
if(oreTerrain[i] === 2){
paintGameItems(i*25, canvas.height - 25, stoneBlock.width, stoneBlock.height, stoneBlock.color);
}
else if(oreTerrain[i] === 4){
paintGameItems(i*25, canvas.height - 25, coalBlock.width, coalBlock.height, coalBlock.color);
}
else if(oreTerrain[i] === 5){
paintGameItems(i*25, canvas.height - 25, ironBlock.width, ironBlock.height, ironBlock.color);
}
else if(oreTerrain[i] === 6){
paintGameItems(i*25, canvas.height - 25, lava.width, lava.height, lava.color)
}
else if(oreTerrain[i] === 7){
paintGameItems(i*25, canvas.height - 25, lava.width, lava.height, lava.color)
}
}
}
function setItemAttributes(){
console.log("ItemAttributes Successfully Set");
paintGameItems(Player.x, Player.y, Player.width, Player.height, Player.color);
console.log("paintGameItems Successfully Called");
}
function randomTerrain(){
console.log("randomTerrain successfully called");
/*
If the number passed is 0, then the block will be grass
If the number 1 is passed, then the block will be dirt
If the number 2 is passed, then the block will be stone
If the number 3 is passed, then the block will be nothing
If the number 4 is passed, then the block will be coal
If the number 5 is passed, then the block will be iron
If the number 6 is passed, then the block will be lava
If the number 7 is passed, then the block will be snow
*/
var terrainVar = Math.random() * 10;
var oreVar = Math.random() * 10;
if(biome === "plains") {
if (terrainVar > 0 && terrainVar < 6) {
highTerrain.push(0);
middleTerrain.push(1);
lowTerrain.push(2)
} else if (terrainVar > 6 && terrainVar < 9) {
highTerrain.push(3);
middleTerrain.push(0);
lowTerrain.push(1);
} else {
highTerrain.push(3);
middleTerrain.push(3);
lowTerrain.push(0);
}
console.log("oreVar = " + oreVar);
if (oreVar < 6) {
oreTerrain.push(2);
} else if (oreVar > 6 && oreVar < 8) {
oreTerrain.push(4);
} else if (oreVar > 8 && oreVar < 9) {
oreTerrain.push(5);
} else if (oreVar > 9) {
oreTerrain.push(6)
}
}
else if(biome === "taiga") {
if (terrainVar > 0 && terrainVar < 6) {
highTerrain.push(7);
middleTerrain.push(7);
lowTerrain.push(2)
} else if (terrainVar > 6 && terrainVar < 9) {
highTerrain.push(3);
middleTerrain.push(7);
lowTerrain.push(7);
} else {
highTerrain.push(3);
middleTerrain.push(3);
lowTerrain.push(7);
}
console.log("oreVar = " + oreVar);
if (oreVar < 6) {
oreTerrain.push(2);
} else if (oreVar > 6 && oreVar < 8) {
oreTerrain.push(4);
} else if (oreVar > 8 && oreVar < 9) {
oreTerrain.push(5);
} else if (oreVar > 9) {
oreTerrain.push(6)
}
}
}
function paintGameItems(itemX, itemY, itemWidth, itemHeight, itemColor){
//console.log(itemX, itemY, itemWidth, itemHeight);
ctx.beginPath();
ctx.fillStyle = itemColor;
ctx.fillRect(itemX, itemY, itemWidth, itemHeight);
ctx.fill();
}
function selectBiome(){
biomeSelector = Math.random() * 10;
if(biomeSelector <= 7){
biome = "plains";
}
else if(biomeSelector > 7){
biome = "taiga";
}
}
function playerLocationTracker(){
console.log("Player.x = " + Player.x + ". canMove = " + canMove + ". playerBlock = " + playerBlock);
}
function playerJump(e){
addEventListener("keydown", function(e) {
if (e.keyCode === 32 || e.keyCode === 87 || e.keyCode === 38) {
if (touchingGround) {
for (i = 0; i < 1; i++) {
Player.y -= 1;
}
}
}
});
}
function playerLeft(e){
addEventListener("keydown", function(e) {
if(canMove) {
if (e.keyCode === 65 || e.keyCode === 37){
console.log("Left");
canMove = false;
playerBlock -= 0.04;
Player.x -= 0.4;
canMove = true;
e.keyCode = 0;
}
}
});
}
function playerRight(e){
addEventListener("keydown", function(e) {
if (canMove){
if (e.keyCode === 68 || e.keyCode === 39) {
console.log("Right");
canMove = false;
playerBlock += 0.04;
Player.x += 0.4;
canMove = true;
e.keyCode = 0;
}
}
});
}
function playerGravity(){
unevenTerrainLocator = Math.round(playerBlock);
if(highTerrain[unevenTerrainLocator] === 0 || highTerrain[unevenTerrainLocator] === 7){
gravityVar = canvas.height - 12;
}
else if(middleTerrain[unevenTerrainLocator] === 0 || middleTerrain[unevenTerrainLocator] === 7){
gravityVar = canvas.height - 100;
}
else if(lowTerrain[unevenTerrainLocator] === 0 || lowTerrain[unevenTerrainLocator] === 7){
gravityVar = canvas.height - 75
}
if(gravityVar <= Player.y){
Player.y = gravityVar;
gravityStrength = 0;
touchingGround = true;
}
else if(gravityVar > Player.y){
touchingGround = false;
gravityStrength +=5;
Player.y += gravityStrength;
}
}
function terrainJumpLoop(){
if(gameOn){
ctx.clearRect(0, 0, canvas.width, canvas.height);
playerGravity();
playerJump();
playerLocationTracker();
paintGameItems(Player.x, Player.y, Player.width, Player.height, Player.color);
paintGameTerrain();
}
}
function playerLeftLoop(){
playerLeft();
}
function playerRightLoop(){
playerRight();
}
function initializeGame(){
var treeX = (Math.round(Math.random()*(canvas.width/25)))*25;
var treeY = 0;
if(highTerrain[treeX/25] === 0){
treeY = canvas.height - 100;
}
else if(middleTerrain[treeX/25] === 0){
treeY = canvas.height - 75;
}
else if(lowTerrain[treeX/25]){
treeY = canvas.height - 50;
}
paintGameTrees(treeX, treeY);
if (biome === "plains") {
document.getElementById('mediaOverworld').play();
}
else if(biome === "taiga"){
document.getElementById('mediaGlaciers').play();
}
}
function startGameFunction() {
console.clear();
ctx.clearRect(0, 0, canvas.width, canvas.height);
document.getElementById('mediaOverworld').pause();
document.getElementById('mediaOverworld').currentTime = 0;
document.getElementById('mediaGlaciers').pause();
document.getElementById('mediaGlaciers').currentTime = 0;
highTerrain = [];
middleTerrain = [];
lowTerrain = [];
oreTerrain = [];
selectBiome();
Player.x = 0;
Player.y = 0;
document.getElementById("paragraph").innerHTML = "Music and Game Has Successfully Started";
console.log("Game Has Successfully Started");
setItemAttributes();
for(i = 0; i < terrainLength; i++){
randomTerrain();
console.log("Terrain Layer Successfully Generated")
}
console.log(highTerrain);
console.log(middleTerrain);
console.log(lowTerrain);
console.log(oreTerrain);
initializeGame();
paintGameTerrain();
document.getElementById("startBtn").innerHTML = "Reset the Game";
gameOn = true;
}
body{
background-color:black;
color:white;
}
canvas{
background-color:aqua;
margin:0 auto;
}
#ifError {
color: red;
font-family: "Arial Black";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple 2D JavaScript Platformer</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas"></canvas>
<br>
<button onclick="startGameFunction()" id="startBtn">Start The Game</button>
<p id="paragraph"></p>
<div id="ifError">
<p id="wrongCodeLine"></p>
<p id="errorLineNo"></p>
</div>
<audio id="mediaOverworld">
<source src="Audio/Overworld.mp3">
</audio>
<audio id="mediaGlaciers">
<source src="Audio/Glaciers.mp3">
</audio>
<script src="game.js"></script>
</body>
</html>
This is a lot of code to debug, but if you can do it, I will thank you a lot.

Javascript Collision (Not Collision Detection)

I'm trying to make a platforming game, and I've been working on the collision for the past 2 weeks. The collision detection is working, but the collision itself (as in, keeping the player out of the tile) is not, no matter what I try. I've tried looking up how to do this, but all I'm finding is how to do the detection part, which I already have done. What do I do after I detect collision?
It was written from scratch, and the player is rectangular, and so are the tiles.
Here's the basic code:
var Player = function(hue, x, y, xSize, ySize, health) {
this.hue = hue;
this.position = new PVector(x, y);
this.originalPosition = new PVector(x, y);
//this.previousPosition = new PVector(x, y);
//this.ppp = new PVector(x, y);
//this.virtualPosition = new PVector(x, y);
//this.predictedPosition = new PVector(x, y);
this.velocity = new PVector(0, 0);
//this.predictedVelocity = new PVector(0, 0);
this.acceleration = new PVector(0, 0);
}
/*Player.prototype.testCollision = function(tile) {
if (this.predictedPosition.y < tile.position.y + tile.size.y && this.predictedPosition.y + this.size.y > tile.size.y && this.predictedPosition.x < tile.position.x + tile.size.x && this.predictedPosition.x + tile.size.x > tile.position.x) {
return false;
} else {
return true;
}
};*/
Player.prototype.ifColliding = function(tile) {
if (this.position.x < tile.position.x + tile.size.x && this.position.x + tile.size.x > tile.position.x) {
/*if (this.position.x + this.size.x > tile.position.x) {
this.position.set(tile.position.x - this.size.x, this.position.y);
} else if (this.position.x < tile.position.x + tile.size.x) {
this.position.set(tile.position.x + tile.size.x, this.position.y);
}*/
this.velocity.set(0, this.velocity.y);
//this.acceleration.set(0, this.acceleration.y);
/*if (this.ppp.x < tile.position.x + tile.size.x && this.ppp.x + tile.size.x > tile.position.x) {
if (this.ppp.x + this.size.x > tile.position.x) {
this.position.set(tile.position.x - this.size.x, this.position.y);
} else if (this.ppp.x < tile.position.x + tile.size.x) {
this.position.set(tile.position.x + tile.size.x, this.position.y);
}
} else if (this.previousPosition.x < tile.position.x + tile.size.x && this.previousPosition.x + tile.size.x > tile.position.x) {
this.position.set(this.ppp.x, this.position.y);
} else {
this.position.set(this.previousPosition.x, this.position.y);
}*/
}
if (this.position.y < tile.position.y + tile.size.y && this.position.y + this.size.y > tile.size.y) {
this.velocity.set(this.velocity.x, 0);
this.acceleration.set(this.acceleration.x, 0);
this.yColliding = true;
/*if (this.position.y + this.size.y > tile.position.y) {
this.position.set(this.position.x, tile.position.y - this.size.y);
rect(0, 20, 0, 0);
} else if (this.position.y < tile.position.y + tile.size.y) {
this.position.set(this.position.x, tile.position.y + tile.size.y);
rect(20, 20, 0, 0);
}*/
}
}
Player.prototype.update = function(tiles) {
//this.ppp.set(this.previousPosition.x, this.previousPosition.y);
//this.previousPosition.set(this.position.x, this.position.y);
this.velocity.add(this.acceleration);
/*this.predictedVelocity.set(this.velocity.x, this.velocity.y);
this.predictedVelocity.add(this.acceleration);
this.virtualPosition.set(this.position.x, this.position.y);
this.virtualPosition.add(this.velocity);
this.predictedPosition.set(this.virtualPosition.x, this.virtualPosition.y);
this.predictedPosition.add(this.predictedVelocity);
var collDcted = false;
for (var i = 0; i < tiles.length; i++) {
if (this.testCollision(tiles[i], true) === false) {
collDcted = false;
}
}*/
//if (collDcted) {
this.position.add(this.velocity);
//}
}
The commented out code is failed attempts. The non-commented code is the closest I could get it to working.
This is a sample collision I made:
<!DOCTYPE html>
<html>
<body>
<p id="Health">Health</p>
<canvas id="gameCanvas" width="600" height="480" style = "border:1px solid gray"></canvas>
<script>
// Adding keyboard evt listener
document.addEventListener("keydown", keyPressed);
document.addEventListener("keyup", keyReleased);
//defining canvas
var canvas;
var canvasContext;
//defining Player variables
var PLAYER_X = 100;
var PLAYER_Y = 100;
var PLAYER_WIDTH = 20;
var PLAYER_HEIGHT = 20;
var PLAYER_HEALTH = 100;
//defining keypress codes
var KEY_LEFT = 37;
var KEY_RIGHT = 39;
var KEY_UP = 38;
var KEY_DOWN = 40;
//variables used to test movement
var keyHeld_Up = false;
var keyHeld_Down = false;
var keyHeld_Left = false;
var keyHeld_Right = false;
//Keypress?
function keyPressed(evt) {
if(evt.keyCode == KEY_UP) {
keyHeld_Up = true;
}
if(evt.keyCode == KEY_DOWN) {
keyHeld_Down = true;
}
if(evt.keyCode == KEY_LEFT) {
keyHeld_Left = true;
}
if(evt.keyCode == KEY_RIGHT) {
keyHeld_Right = true;
}
//prevents page from scrolling when arrow keys are pressed
evt.preventDefault();
}
//Key Released?
function keyReleased(evt) {
if(evt.keyCode == KEY_UP) {
keyHeld_Up = false;
}
if(evt.keyCode == KEY_DOWN) {
keyHeld_Down = false;
}
if(evt.keyCode == KEY_LEFT) {
keyHeld_Left = false;
}
if(evt.keyCode == KEY_RIGHT) {
keyHeld_Right = false;
}
}
//Initialize Canvas and Game Loop
window.onload = function() {
console.log("Is this thing on?");
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
var framesPerSecond = 30;
setInterval(function() {
drawObjects();
movePlayer();
damageTest();
}, 1000/framesPerSecond);
}
// Drawing function
function colorRect(x,y, width,height, color, health) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.color = color;
this.health = health;
this.update = function() {
this.draw();
}
this.draw = function() {
canvasContext.beginPath();
canvasContext.rect(this.x, this.y, this.width, this.height);
canvasContext.fillStyle = this.color;
canvasContext.fill();
canvasContext.closePath();
}
};
// Creating Objects
var Screen = new colorRect( 0, 0, 600, 480, 'black', 0);
var Player = new colorRect( PLAYER_X, PLAYER_Y, PLAYER_WIDTH, PLAYER_HEIGHT, 'red', PLAYER_HEALTH);
var Box = new colorRect( 200, 200, 30, 30, 'green', 0);
var Spike = new colorRect( 300, 300, 25, 25, 'white', 0);
// Drawing Objects
function drawObjects() {
Screen.update();
Spike.update();
Player.update();
Box.update();
}
//Collision Test
function collides( a, b ) {
return a.x < b.x + b.width &&
a.x + a.width > b.x &&
a.y < b.y + b.height &&
a.y + a.height > b.y;
}
//Movement based on keypress events
function movePlayer() {
if(collides( Player, Box ) === false) {
if(keyHeld_Up) {
Player.y -= 2;
}
if(keyHeld_Down) {
Player.y += 2;
}
if(keyHeld_Left) {
Player.x -= 2;
}
if(keyHeld_Right) {
Player.x += 2;
}
}
}
//Testing Collision for damage
function damageTest() {
if(collides( Player, Spike ) === true) {
Player.health -= 1;
}
//Displaying Health in <body>
document.getElementById("Health").innerHTML = "Health: " + Player.health;
}
</script>
</body>
</html>
The code I made stops the player in its tracks completely when hitting the box, but you could create individual collision circumstances for when objects collide on each side of another object, and use those to detect collision.
I hope this helped! If you have any questions regarding this code, just ask! (To run code snippet you might want to go full screen and click inside canvas)

javascript jumping character not working

I'm having a few issues with my code. Can't get my cube to jump. Take a look at my code and let me know if you can help please.
My left, right and duck abilities all currently work at desired level, but I cannot get my cube to jump. I've been trying for three days and can't find anything online. My javascript is embedded within a tag in a html page.
var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
var coinRad = 8;
var coinX = 40;
var coinY = 80;
var x = 20;
var y = 510;
var w = 30;
var h = 50;
var rightPressed = false;
var leftPressed = false;
var ducked = false;
var jumping = 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 == 40) {
ducked = true;
} else if (e.keycode == 32) {
jumping = true;
}
}
function keyUpHandler(e) {
if (e.keyCode == 39) {
rightPressed = false;
} else if (e.keyCode == 37) {
leftPressed = false;
} else if (e.keyCode == 40) {
ducked = false;
} else if (e.keycode == 32) {
jumping = false;
}
}
function drawCube() {
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.fillStyle = "Green";
ctx.fill();
ctx.closePath();
}
function run() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (leftPressed) {
if (x > 0) {
x -= 2.5;
}
} else if (rightPressed) {
if (x < canvas.width - w) {
x += 2.5;
}
}
if (jumping) {
y -= 10;
h -= 10;
}
if (ducked) {
y = 535;
h = 25;
} else {
y = 510;
h = 50;
}
drawCube();
}
setInterval(run, 10);
<canvas id="gameCanvas"></canvas>
Additionally, your keyCode check is improperly capitalized for the jumping condition.
else if (e.keyCode == 40) {
ducked = false;
} else if (e.keycode == 32) { //should be keyCode
jumping = false;
}
because when the run method end, you do this.
if (jumping) {
y -= 10;
h -= 10;
}
if (ducked) {
y = 535;
h = 25;
} else {
y = 510;
h = 50;
}
even if you change the values from Y and H, their values always change to 510 and 50 respectively, because the else in ducked condition.
Remove this else or find another logic to do the same

canvas keyPress movement - broken

My keyPress movement seems to be broken, if I press arr.up/down twice then it gets broken and I can't move the element back. And the element doesn't even stop when I stop holding the arr.up/down, why?
rocket = new Image();
x = 50;
y = 185;
score = 0;
velY = 0;
speed = 2;
y += velY;
ctx.drawImage(rocket, x, y);
if(e.keyCode == 38) {
if(velY < speed) {
velY --;
}
}
if(e.keyCode == 40) {
if(velY < speed) {
velY ++;
}
}
Preview: http://game.stranger.tk/
I would have edited your code however your game via your link isn't working :(. I hope this code example I have provided helps you out.
jsFiddle : https://jsfiddle.net/w1z2c1cq/
javascript
var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
var rocket = function()
{
this.Sprite = new Image();
this.Sprite.src = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcS9zafp1ezdR2lSAxTdjZYe_nPhe6VeKKmAuK-GzWQCSs395WkzNA";
this.XPos = 100;
this.YPos = 100;
}
var player = new rocket();
setInterval(function()
{
ctx.fillRect(0,0,400,400);
ctx.drawImage(player.Sprite, player.XPos, player.YPos);
}, 3);
window.addEventListener("keydown", function(e){
// Left key
if(e.keyCode === 37) {
player.XPos -= 5;
}
// Right key
if(e.keyCode === 39) {
player.XPos += 5;
}
// Up key
if(e.keyCode === 38) {
player.YPos -= 5;
}
// Down key
if(e.keyCode === 40) {
player.YPos += 5;
}
});
Also in your code you are checking this same if statement for up and down if(velY < speed)
try
// Up
if(e.keyCode == 38) {
if(velY < speed) {
velY --;
}
}
// Down
if(e.keyCode == 40) {
if(velY > -speed) {
velY ++;
}
}

Trying to animate a jump in canvas / JS

I'm just trying to animate a jump in canvas, but I don't think I got the math formula properly, instead of doing a sine wave kind of motion, it just instantly telports, with no animation, any help would be great thanks.
var ctx = new CtxScene(500, 500, '1px solid black').create()
, player = {
x: 0,
y: 0,
moving: false,
dir: undefined
};
var i = 0;
(function draw() {
setTimeout(function() {
requestAnimationFrame(draw);
checkDir();
update();
}, 1000 / 60);
})();
document.onkeydown = function(e) {
if (e.which === 37) {
player.moving = true;
player.dir = 'left';
}
if (e.which === 39) {
player.moving = true;
player.dir = 'right';
}
if (e.which === 38) {
player.moving = true;
player.dir = 'up';
}
if (e.which === 40) {
player.moving = true;
player.dir = 'down';
}
if (e.which === 32) {
player.moving = true;
player.dir = 'jump';
}
console.log(e.which);
}
document.onkeyup = function(e) {
player.moving = false;
}
function update() {
ctx.clearRect(0, 0, 500, 500);
ctx.fillStyle = '#00A';
ctx.fillRect(player.x, player.y, 100, 100)
}
function checkDir() {
if (player.moving) {
if (player.dir === 'left') {
player.x -=5;
} else if (player.dir === 'right') {
player.x += 5;
} else if (player.dir === 'up') {
player.y -= 5;
} else if (player.dir === 'down') {
player.y += 5;
} else if (player.dir === 'jump') {
player.y = 100 * Math.sin(5*Math.PI/200);
}
}
}
the math is a few lines from the bottom (I'm almost 100% sure it's wrong)
Ok so the easiest way to do this is to use physics, really really basic physics. Give your character a gravity force and at least a velocity in the Y direction, similar to this:
player.gravity= 0.92;
var characterUpdate= function(){
player.y+=player.velocityY;
player.velocityY+=player.gravity;
}
This will cause the player to constantly want to go downward (gravity) and you increase the velocityY to counter act this during a jump. You'll want to set some bounds to avoid the character going off the screen for now, something like:
if (player.y+player.height >= ctx.height) {
player.y=ctx.height-player.height;
}
The added benefit of this method is that it takes care of any falls you might plan on including later.

Categories