jQuery updating css state of class instances in a main.js file - javascript

I have a main.js file which I am initiating a game with two class instances. Head and Apple. I want to monitor css changes from my main.js file but it is not staying updated on the changes happening in the Head instance, namely, every 500 ms the position of it changes due to changes in its css. I would like to do certain actions depending on that "head's" positioning and therefore its css. Should I be using a jquery method to monitor this? I am not sure where to go. I have tried accessing the css properties by defining them with this in the constructor and also using variables in the main.js file. neither have worked.
main.js
$(document).ready(function() {
const head = new Head($('#board'));
const apple = new Apple($('#board'));
$('body').on('keydown', function(e) {
if (e.keyCode === 37) {
console.log('pressed left');
head.currentDirection = 'left';
} else if (e.keyCode === 39) {
console.log('pressed right');
head.currentDirection = 'right';
} else if (e.keyCode === 38) {
console.log('pressed up');
head.currentDirection = 'up';
} else if (e.keyCode === 40) {
console.log('pressed down');
head.currentDirection = 'down';
}
});
let position = head.node.position();
if (position.top === apple.randomTop && position.left === apple.randomLeft) {
this.endGame();
}
});
Apple
class Apple {
constructor($el) {
this.node = $('<img id="apple"></img>');
this.node.attr('src', 'src/assets/apple.jpg');
$el.append(this.node);
this.randomTop = Math.floor(Math.random() * 13) * 50
this.randomLeft = Math.floor(Math.random() * 13) * 50
this.node.css({ top: this.randomTop, left: this.randomLeft });
}
}
Head
// creates a constructor function - research ES6 classes
class Head {
// this is what's called when you use the "new" keyword
constructor($el) {
this.node = $('<div id="head"></div>');
this.currentDirection = 'right';
this.SPEED = 500;
$el.append(this.node);
this.node.css({ top: 0, left: 0 });
this.toBeCleared = setTimeout(this.move.bind(this), this.SPEED);
}
// same as Head.prototype.move = function() {...}
move() {
let direction = this.currentDirection;
let position = this.node.position();
if (position.left === 700 || position.top === 700 || position.left === -50 || position.top === -50) {
console.log('Game Over');
this.endGame();
}
if (direction === 'right') {
position.left += 50;
} else if (direction === 'left') {
position.left -= 50;
} else if (direction === 'up') {
position.top -= 50;
} else if (direction === 'down') {
position.top += 50;
}
this.node.css(position);
this.toBeCleared = setTimeout(this.move.bind(this), this.SPEED);
}
endGame() {
console.log('game has ended')
// this.node.css(position);
clearTimeout(toBeCleared);
}
}

Related

Character will not jump after touching in JS

I am programming collision detection in JS for a platformer. For some reason, when my character touches the ground on the top, it won't jump again. Here's my code:
if (isCollideY(platforms[i].getBoundingClientRect(), document.getElementById('spriteNotReal').getBoundingClientRect()) == true) {
if (falling == true && (jumping == false)) {
moveY = platforms[i].getBoundingClientRect().y + 3;
momentumY = 0;
onSolidGround = true;
}
}
if (event.code == 'KeyW' && (moveY <= 300)) {
moveY += 1;
move (moveX, moveY);
momentumY = momentumY + 20;
onSolidGround = false;
falling = false;
jumping = true;
}
else if (onSolidGround == false) {
if (momentumY < 0) {
falling = true;
}
else if (momentumY > 0) {
jumping = true;
}
else {
jumping = false;
}
moveX += momentumX / 3 + 1;
document.getElementById("spriteNotReal").src = "jumpmain.gif";
}
My problem was somewhat stupid. After checking the input code, I realized that the jump wasn't happening because it would only jump while on the "platform" I set up to test, not while it was actually on a platform. Here's the improved code:
if (event.code == 'KeyW' && (onSolidGround == true)) {
moveY += 1;
move (moveX, moveY);
momentumY = momentumY + 20;
onSolidGround = false;
falling = false;
jumping = true;
}

Trouble with adding gravity to 2d platformer

I am trying to make a 2D platforming game and I am missing an essential part of it, gravity.
I have tried everything from look at questions on this website to looking at online tutorials and you-tube videos.
I really need help with getting gravity into this game as I am out of ideas.
As I said I have already tried looking at multiple tutorials and videos, including this one:
http://www.somethinghitme.com/2013/01/09/creating-a-canvas-platformer-tutorial-part-one/
but this one uses shapes created in canvas rather than images.
I already know that you have to use a velocity function as well as variable for the gravity. Then you have to put this all inside the key handler function so that it can get executed.
//spaceman variables
var sx = canvasWidth / 2; // start the spaceman in the centre
var sy = canvasHeight / 2;
var sdx = 0; // set initial speed to 0
var sdy = 0;
var sspeed = 3; // create a variable for speed
var gravity = 0.2;
var svX = 0;
var svY = (Math.random() * -10) - 5;
//set variables to use for key presses
//these are Boolean variables
//they can only be true or false
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
function keyDownHandler(e) {
if (e.keyCode == 39) {
rightPressed = true;
} else if (e.keyCode == 37) {
spaceman2Ready = true;
spacemanReady = false;
leftPressed = true;
} else if (e.keyCode == 38) {
upPressed = true;
} else if (e.keyCode == 40) {
downPressed = true;
}
}
function keyUpHandler(e) {
if (e.keyCode == 39) {
rightPressed = false;
sdx--;
} else if (e.keyCode == 37) {
spaceman2Ready = false;
spacemanReady = true;
leftPressed = false;
sdx--;
} else if (e.keyCode == 38) {
upPressed = false;
sdx--;
} else if (e.keyCode == 40) {
downPressed = false;
sdx--;
}
}
// add something to "listen" for an event
//an event is keypress, mouse movement, mouse click etc.
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (rightPressed == true) {
sdx = sspeed;
} else if (leftPressed == true) {
sdx = -sspeed;
} else if (upPressed == true) {
sdy = -sspeed;
} else if (downPressed == true) {
sdy = sspeed
}
if (rightPressed == false && leftPressed == false && upPressed == false && downPressed == false) {
sdx = 0;
sdy = 0;
}
sx = sx + sdx;
sy = sy + sdy;
}
if (spacemanReady) {
ctx.drawImage(spacemanImage, sx, sy);
if (spaceman2Ready) {
ctx.drawImage(spaceman2Image, sx, sy);
}
// basically the setTimeout part, but this time its requesting the function that we made at the top
requestAnimationFrame(draw);
}
// this is to get the loop for the animation to start going
window.addEventListener("load",
function() {
draw();
});
< /script>
</body >
</html>/
You should be using gravity to update your position every frame (in the draw function). This would look like:
if(sy > 0){
sdy += gravity
}
I have created a codepen with your game with gravity. I hope this helps!

Javascript move players with keys

I am trying to be able to control two players and make them move with a certain speed, I ain't getting any errors in the console and it writes out what it should be doing... But I see no action happening.
//control system
window.addEventListener('keydown', function (event) {
//left key
if (event.keyCode === 37) {
playerOne.x -= 1;
console.log("player 1 left");
}
//right key
else if (event.keyCode === 39) {
playerOne.x += 1;
console.log("player 1 right");
}
//up key
else if (event.keyCode === 38) {
playerOne.y -= 1;
console.log("player 1 up");
}
//down
else if (event.keyCode === 40) {
playerOne.y += 1;
console.log("player 1 down");
}
// bomb
else if (event.keyCode === 13) {
console.log("place bomb");
}
});
window.addEventListener('keydown', function (event) {
//left key
if (event.keyCode === 65) {
playerTwo.x -= 1;
console.log("player 2 left");
}
//right key
else if (event.keyCode === 68) {
playerTwo.x += 1;
console.log("player 2 right");
}
//up key
else if (event.keyCode === 87) {
playerTwo.y -= 1;
console.log("player 2 up");
}
//down
else if (event.keyCode === 83) {
playerTwo.y += 1;
console.log("player 2 down");
}
// bomb
else if (event.keyCode === 32) {
console.log("place bomb");
}
});
function movePlayers() {
"use strict";
if (keys.moveLeft) {
playerOne.x -= powerUps.speed;
if (playerOne.currentDirection != "left") {
playerOne.gotoAndPlay('left')
playerOne.currentDirection = "left";
}
}
if (keys.moveRight) {
playerOne.x += powerUps.speed;
if (playerOne.currentDirection != "right") {
playerOne.gotoAndPlay('right')
playerOne.currentDirection = "right";
}
}
if (keys.moveUp) {
playerOne.y -= powerUps.speed;
if (playerOne.currentDirection != "up") {
playerOne.gotoAndPlay('up')
playerOne.currentDirection = "up";
}
}
if (keys.moveDown) {
playerOne.y += powerUps.speed;
if (playerOne.currentDirection != "down") {
playerOne.gotoAndPlay('down')
playerOne.currentDirection = "down";
}
}
if (keys.moveLeft) {
playerTwo.x -= powerUps.speed;
if (playerTwo.currentDirection != "left") {
playerTwo.gotoAndPlay('left')
playerTwo.currentDirection = "left";
}
}
if (keys.moveRight) {
playerTwo.x += powerUps.speed;
if (playerTwo.currentDirection != "right") {
playerTwo.gotoAndPlay('right')
playerTwo.currentDirection = "right";
}
}
if (keys.moveUp) {
playerTwo.y -= powerUps.speed;
if (playerTwo.currentDirection != "up") {
playerTwo.gotoAndPlay('up')
playerTwo.currentDirection = "up";
}
}
if (keys.moveDown) {
playerTwo.y += powerUps.speed;
if (playerTwo.currentDirection != "down") {
playerTwo.gotoAndPlay('down')
playerTwo.currentDirection = "down";
}
}
}
That´s only an Tipp not an answer - but the place in comments is not enough.
I thinks that´s not an good way with your "if" construction, a sample for an easier way:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table key´s</title>
<style>
td{width:10px;height:10px;background:#ddd;}
tr:nth-child(5) td:nth-child(5){background:#f00;}
</style>
</head>
<body>
<div id="tableContainer">
</div>
<script>
var row=col=5,max=10;
tableContainer.innerHTML = '<table>'+('<tr>'+'<td>'.repeat(max)).repeat(max)+'</table>';
window.addEventListener("keyup", function(e){
var colDiff, rowDiff;
var keyMap = new Map([[37,[-1,0]],[38,[0,-1]],[39,[1,0]],[40,[0,1]]]);
if (keyMap.has(e.keyCode)){
document.querySelector(`tr:nth-child(${row}) td:nth-child(${col})`).style.background='#ddd';
[colDiff,rowDiff]=keyMap.get(e.keyCode);
row+=rowDiff;
col+=colDiff;
row = (row>max) ? max : (row < 1) ? 1 : row;
col = (col>max) ? max : (col < 1) ? 1 : col;
document.querySelector(`tr:nth-child(${row}) td:nth-child(${col})`).style.background='#f00';
}
})
</script>
</body>
</html>

js game freezes with no error

I am working on a javascript game that involves building, destroying, and survival.
It has been working fine but after adding trees the game would randomly freeze after breaking blocks.
The code is here:
for (var bl in blocks) {
if (mouse.x >= blocks[bl].x-camera.x && mouse.y >= camera.y+blocks[bl].y && mouse.x <= blocks[bl].x-camera.x+64 && mouse.y <= camera.y+blocks[bl].y+64) {
document.body.style.cursor = "pointer";
if (mouse.down) {
if (!blocks[bl].d && blocks[bl].d !== 0) {
blocks[bl].d = 32;
} else if (blocks[bl].d > 0) {
blocks[bl].d -= 0.5;
if (tools[player.tool].n === 'axe') {
blocks[bl].d -= 1;
}
} else {
var fb = false;
for (var i in inventory) {
if (inventory[i].n === blocks[bl].n) {
inventory[i].a ++;
fb = true;
}
}
if (!fb) {
inventory.push({n: blocks[bl].n, a: 1});
}
blocks.splice(bl, 1);
}
}
}
}
I don't see any way there could be an infinite loop and no errors show up when it happens.
EDIT
I changed the code to
var spliceblock = {bl: 0, s: false};
for (var bl in blocks) {
if (mouse.x >= blocks[bl].x-camera.x && mouse.y >= camera.y+blocks[bl].y && mouse.x <= blocks[bl].x-camera.x+64 && mouse.y <= camera.y+blocks[bl].y+64) {
document.body.style.cursor = "pointer";
if (mouse.down) {
if (!blocks[bl].d && blocks[bl].d !== 0) {
blocks[bl].d = 32;
} else if (blocks[bl].d > 0) {
blocks[bl].d -= 0.5;
if (tools[player.tool].n === 'axe') {
blocks[bl].d -= 1;
}
} else {
var fb = false;
for (var i in inventory) {
if (inventory[i].n === blocks[bl].n) {
inventory[i].a ++;
fb = true;
}
}
if (!fb) {
inventory.push({n: blocks[bl].n, a: 1});
}
spliceblock.s = true;
spliceblock.bl = bl;
//blocks.splice(bl, 1);
}
}
}
}
if (spliceblock.s) {
blocks.splice(spliceblock.bl, 1);
}
but it still freezes randomly when trying to break blocks.
Modifying an array (using splice) while you're iterating through it is bound to cause problems. If you remove the block bl from the array and then continue to run through it, the counter will probably be off.
Instead, store the index of the block you're removing, then remove it after you're done looping through the blocks.

How to move an element in javascript automatically with while loop?

I am making a Snake game so I'm trying to move my snake. It is moving with keys but it should move automatically on the screen. I tried doing that with while loops like in the code below but because of break; I have to press a key every time I want it to move. How can I make it move automatically? I tried removing break; an using an if statement but I didn't succeed.
Any other solutions or something else?
I'm new to programming so any advices would be helpful.
var main = function() {
var i = 0;
var j = 0;
$(document).keyup(function(event) {
var e = event.which;
while(i == 1) {
$('.snake').animate({left: '+=10px'}, 10);
break;
}
while(i == 2) {
$('.snake').animate({left: '-=10px'}, 10);
break;
}
while(i == 3) {
$('.snake').animate({top: '-=10px'}, 10);
break;
}
while(i == 4) {
$('.snake').animate({top: '+=10px'}, 10);
break;
}
//Which key is preesed
//D
if(e == 68) {
i = 1;
}
//A
else if(e == 65) {
i = 2;
}
//W
else if(e == 87) {
i = 3;
}
//S
else if(e == 83) {
i = 4;
}
//Any other key
else {
i = 0;
}
});
};
$(document).ready(main);
I think you just have to organize a little bit your code.
First. You must put your code inside a function. You really don't need a while. You can use a simple if.
function move(i) {
if(i == 1) {
$('.snake').animate({left: '+=10px'}, 10);
break;
}
if(i == 2) {
$('.snake').animate({left: '-=10px'}, 10);
break;
}
if(i == 3) {
$('.snake').animate({top: '-=10px'}, 10);
break;
}
if(i == 4) {
$('.snake').animate({top: '+=10px'}, 10);
break;
}
}
Now you have to change the event, using keydown instead of keyup
function main() {
var interval;
$(document).keydown(function(event) {
if(interval) clearInterval(interval); // Clear the previous interval
var e = event.which;
var i;
//Which key is pressed
//D
if(e == 68) {
i = 1;
}
//A
else if(e == 65) {
i = 2;
}
//W
else if(e == 87) {
i = 3;
}
//S
else if(e == 83) {
i = 4;
}
//Any other key
else {
i = 0;
}
interval = setInterval(function() {
move(i)
},1000); // repeat every 1 second
});
}
$(document).ready(main);

Categories

Resources