I am beginner in JavaScript and I'm trying to create a simple game. I'm looking for a way to stop the rectangle when it touches the screen border by stopping setInterval(), I can't get the value of the left screen border.
const element = document.querySelector('#rectangle');
let a = 1;
document.addEventListener('keydown', function (e) {
switch (e.keyCode) {
case 37:
let leftInterval = setInterval(moveLeft, 100);
break;
case 39:
let rightInterval = setInterval(moveRight, 100);
break;
}
});
window.addEventListener('load', () => {
rectangle.style.position = 'absolute';
rectangle.style.left = "44%";
});
let moveLeft = () => {
element.style.left = parseInt(element.style.left) - a + '%';
}
let moveRight = () => {
element.style.left = parseInt(element.style.left) + a + '%';
}
function clearinterval() {
if (element.style.left < 0)
clearinterval(leftInterval);
}
clearinterval();
body {
background-color: brown;
box-sizing: border-box;
width: 100%;
height: 100%;
}
#rectangle {
bottom: 2.5%;
background-color: burlywood;
width: 12%;
height: 14px;
}
<div id="rectangle"></div>
This will help you.
const element = document.querySelector('#rectangle');
let a = 1;
document.addEventListener('keydown', function (e) {
switch (e.keyCode) {
case 37:
let leftInterval = setInterval(moveLeft, 100);
break;
case 39:
let rightInterval = setInterval(moveRight, 100);
break;
}
});
window.addEventListener('load', () => {
rectangle.style.position = 'absolute';
rectangle.style.left = "44%";
});
let moveLeft = () => {
if (parseInt(window.getComputedStyle(element,null).getPropertyValue("left")) > 10) {
element.style.left = parseInt(element.style.left) - a + '%';
}
}
let moveRight = () => {
if (parseInt(window.getComputedStyle(element,null).getPropertyValue("right")) > 10) {
element.style.left = parseInt(element.style.left) + a + '%';
}
}
// function clearinterval() {
// // clearinterval(leftinterval);
// }
// clearinterval();
Related
I want the div to slide from left to right, and then back again from right left when it reaches the end of the browser using JavaScript.
var imgObj = null;
var animate;
function init() {
imgObj = document.getElementById('animate');
imgObj.style.position = 'fixed';
imgObj.style.left = '0px';
moveRight();
}
function moveRight() {
imgObj.style.left = parseInt(imgObj.style.left) + 1 + '%';
if (imgObj.style.left == '95%') {
clearTimeout(animate)
alert("i am here")
moveLeft();
}
animate = setTimeout(moveRight, 20);
}
function moveLeft() {
imgObj.style.left = parseInt(imgObj.style.left) - 1 + '%';
if (imgObj.style.right == '95%') {
clearTimeout(animate)
alert('i am here2')
moveRight();
}
animate = setTimeout(moveLeft, 20);
}
window.onload = init;
#animate {
width: 5%;
height: 10%;
background-color: red;
}
<div id="animate"></div>
This is an example of a similar animation, started by the button.You should always use variables to change values and not just hardcorde values to elements. In this case pos is the variable that gets changed (pos++ and pos--) and then added to the style-property.
In your Code i think you never stop increasing the % value. So it gets stuck in a scenario where it does +1 -1 +1 -1 forever.
function myMove() {
var elem = document.getElementById("myAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 100) {
clearInterval(id);
alert("done");
myMove2();
} else {
pos++;
elem.style.left = pos + '%';
}
}
}
function myMove2() {
var elem = document.getElementById("myAnimation");
var pos = 100;
var id = setInterval(frame, 10);
function frame() {
if (pos == 0) {
clearInterval(id);
alert("done2");
myMove();
} else {
pos--;
elem.style.left = pos + '%';
}
}
}
#myAnimation {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
<p>
<button onclick="myMove()">Click Me</button>
</p>
<div id ="myAnimation"></div>
I'm attempting to create a classic "Snake game" using only vanilla Javascript. I got an issue with the snake movements when arrow keys are pressed. It didn't work as supposed to.
The entire code is look like this.
HTML
<div class="canvas" id="canvas">
<div class="snake" id="snake"></div>
<div class="food-item" id="food-item"></div>
</div>
CSS
.canvas {
position: relative;
width: 500px;
height: 500px;
background-color: rgba(203, 200, 200, 0.51);
}
.snake {
width: 18px;
height: 18px;
transform: translate(215px, 246px);
background-color: rgba(180, 9, 180, 0.808);
border-radius: 25px;
}
JS
//the position of element before movement
var pos = 0;
let ele = document.getElementById("snake");
//Add an event for button press
window.addEventListener("keydown", (key) => {
var keycode = key.key;
return {
keycode: keycode,
start: start(keycode),
};
});
//movement of the element
function start(key) {
let keys = key;
function automove() {
try {
if (pos === 380) {
clearInterval(movement);
} else if (keys === "ArrowRight") {
pos++;
ele.style.transform = "translate(" + pos + "px)";
} else if (keys === "ArrowLeft") {
pos++;
ele.style.transform = "translate(" + -pos + "px)";
} else if (keys === "ArrowUp") {
pos++;
ele.style.transform = "translateY(" + pos + "px)";
} else if (keys === "ArrowDown") {
pos++;
ele.style.transform = "translateY(" + -pos + "px)";
} else {
console.log("invalid command: " + Error);
}
} catch (error) {
console.log("Error: " + error);
}
}
const movement = setInterval(automove, 1000);
return movement;
}
the behavior of the code is this
What I'm doing wrong here... is there any alternative way of doing this ?
It would be great if you can support with a vanillaJs answer.
For a snake game, you want the character to move even when no key is pressed.
So you need to store the direction somehow.
here's an updated version:
https://jsfiddle.net/wmvqgku4/1/
JS:
var posX = 200;
var posY = 160;
var ele = document.getElementById("snake");
const UP =0;
const RIGHT =1;
const DOWN =2;
const LEFT =3;
var dir = 1;
window.addEventListener("keydown", (key) => {
keyhandler(key.key)
});
window.onload = function () {
ele = document.getElementById("snake");
ele.style.top = posY + "px";
ele.style.left = posX + "px";
setInterval( automove, 300);
console.log("Started.");
}
function keyhandler(keys) {
try {
if (posX >= 380) {
clearInterval(movement);
}
if (keys === "ArrowRight") {
dir = RIGHT;
} else if (keys === "ArrowLeft") {
dir = LEFT;
} else if (keys === "ArrowUp") {
dir = UP;
} else if (keys === "ArrowDown") {
dir = DOWN;
} else {
console.log("invalid command: " + keys);
}
} catch (error) {
console.log("Error: " + error);
}
}
function automove() {
switch ( dir ) {
case UP: posY--; break;
case DOWN: posY++; break;
case LEFT: posX--; break;
case RIGHT: posX++; break;
}
console.log(dir);
ele.style.top = posY + "px";
ele.style.left = posX + "px";
}
CSS:
.canvas {
position: relative;
width: 500px;
height: 500px;
background-color: rgba(203, 200, 200, 0.51);
}
.snake {
width: 18px;
height: 18px;
position: absolute;
background-color: rgba(180, 9, 180, 0.808);
border-radius: 25px;
}
I made the snake position absolute, and als kept track of the x/y position, so you can add checks for the bounds.
I also changed it a bit, the keyhandler checks the keys and updates the direction variable.
the automove now only checks the direction, and updates the position.
Hope this helps.
let score = document.querySelector('.score');
let startScreen = document.querySelector('.startScreen');
let gameArea = document.querySelector('.gameArea');
let startGame = document.querySelector('#startGame');
let keys = {
ArrowUp: false,
ArrowLeft: false,
ArrowRight: false,
ArrowDown: false
}
let player = {
speed: 5
};
startGame.addEventListener('click', start)
console.log(gameArea);
document.addEventListener('keydown', keyDown);
document.addEventListener('keyup', keyUp);
function keyDown(e) {
keys[e.key] = true;
e.preventDefault();
//console.log(e.key);
//
console.log(keys);
}
function keyUp(e) {
e.preventDefault();
keys[e.key] = false;
console.log(e.key);
console.log(keys);
}
function gamePlay() {
// console.log('now play the game');
let keys = {
ArrowUp: false,
ArrowLeft: false,
ArrowRight: false,
ArrowDown: false
}
if (keys.ArrowUp) {
player.y -= 5;
}
if (keys.ArrowDown) {
player.y += 5;
}
if (keys.ArrowLeft) {
player.x -= 5;
}
if (keys.ArrowRight) {
player.x += 5;
}
car.style.top = player.y + "px";
car.style.left = player.x + "px";
window.requestAnimationFrame(gamePlay)
}
function start() {
let car = document.createElement('div');
car.setAttribute('class', 'car')
gameArea.appendChild(car);
gameArea.classList.remove('hide');
startScreen.classList.add('hide');
player.start = true;
player.y = car.offsetTop;
player.x = car.offsetLeft;
console.log(car.offsetTop);
car.style.top = player.y + "px";
car.style.left = player.x + "px";
console.log(car)
}
let car = document.querySelector('.car');
.car {
width: 50px;
height: 70px;
background: red;
position: absolute;
left: 50px;
top: 120px;
}
.hide {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Car Game</title>
</head>
<body>
<div class="carGame">
<div class="score">
</div>
<div class="startScreen">
<p>
Arrow keys to move <br> If you hit another car you will lose.
<button id="startGame">Start Game</button>
</p>
</div>
<div class="gameArea hide"></div>
</div>
</body>
</html>
I am creating a javascript car Game but I am trying to move my car by arrow keys but it is not moving.
Please 🙏 Tell me what is mistake in my code and I want that when I press arrow keys it moves left right up down please check the mistake in my code
The current code makes no attempt to move the .car element when a key is pressed. All it does is sets an object property to true:
keys[e.key] = true;
I would suggest creating another function, moveCar(), that can be called from the keyDown event listener. This function will hold the positioning logic that is currently found in gamePlay().
Also, when you crate the car element, assign it to a variable that is accessible to the whole application.
let score = document.querySelector(".score");
let startScreen = document.querySelector(".startScreen");
let gameArea = document.querySelector(".gameArea");
let startGame = document.querySelector("#startGame");
let car; /* This will reference the `car` element once created */
let keys = {
ArrowUp: false,
ArrowLeft: false,
ArrowRight: false,
ArrowDown: false
};
let player = {
speed: 5
};
startGame.addEventListener("click", start);
console.log(gameArea);
document.addEventListener("keydown", keyDown);
document.addEventListener("keyup", keyUp);
function keyDown(e) {
keys[e.key] = true;
e.preventDefault();
//console.log(e.key);
//
console.log(keys);
moveCar();
}
function keyUp(e) {
e.preventDefault();
keys[e.key] = false;
console.log(e.key);
console.log(keys);
}
function gamePlay() {
// console.log('now play the game');
let keys = {
ArrowUp: false,
ArrowLeft: false,
ArrowRight: false,
ArrowDown: false
};
window.requestAnimationFrame(gamePlay);
}
function start() {
car = document.createElement("div");
car.setAttribute("class", "car");
gameArea.appendChild(car);
gameArea.classList.remove("hide");
startScreen.classList.add("hide");
player.start = true;
player.y = car.offsetTop;
player.x = car.offsetLeft;
console.log(car.offsetTop);
car.style.top = player.y + "px";
car.style.left = player.x + "px";
console.log(car);
}
function moveCar() {
if (keys.ArrowUp) {
player.y -= 5;
}
if (keys.ArrowDown) {
player.y += 5;
}
if (keys.ArrowLeft) {
player.x -= 5;
}
if (keys.ArrowRight) {
player.x += 5;
}
car.style.top = player.y + "px";
car.style.left = player.x + "px";
}
.car {
width: 50px;
height: 70px;
background: red;
position: absolute;
left: 50px;
top: 120px;
}
.hide {
display: none;
}
<div class="carGame">
<div class="score">
</div>
<div class="startScreen">
<p>
Arrow keys to move <br> If you hit another car you will lose.
<button id="startGame">Start Game</button>
</p>
</div>
<div class="gameArea hide"></div>
</div>
why my checkCollision function is not working in foreach loop ? I want to check whether obs (obstacle) is hits/overlaps on collector (gray object). I am checking every 1 millisecond using setInterval checkCollision function. Basically I am trying to build a simple car game. please help me and thank you in advance
let body = document.body[0];
let container = document.querySelector(".container");
let allObstacles = [];
let colors = ["green", "green", "red"];
let collector = document.getElementById("collector");
class Obstacle {
constructor(yPos) {
this.yPos = -50;
}
randomnum() {
let randX = Math.floor(Math.random() * (container.clientWidth - 50));
return randX;
}
createObstacle() {
let obstacle = document.createElement("div");
obstacle.classList.add("obstacle");
let bgColor = colors[Math.floor(Math.random() * colors.length)];
obstacle.style.width = "50px";
obstacle.style.height = "50px";
obstacle.style.position = "absolute";
obstacle.style.left = this.randomnum() + "px";
obstacle.style.top = this.yPos + "px";
obstacle.style.backgroundColor = bgColor;
obstacle.dataset.behave = bgColor;
container.appendChild(obstacle);
return obstacle;
}
element = this.createObstacle();
updatePosition() {
this.yPos += 2;
this.element.style.top = this.yPos + "px";
}
kill() {
this.element.remove();
}
}
let dropObs = setInterval(function() {
allObstacles.forEach(function(obs) {
obs.updatePosition();
});
allObstacles.forEach(function(obs) {
// why checkCollision function is not working?
if (checkCollision(obs, collector)) {
console.log("hit");
}
if (obs.yPos > container.clientHeight) {
obs.kill();
}
});
}, 10);
let generateObs = setInterval(function() {
let obs = new Obstacle();
allObstacles.push(obs);
}, 2000);
function checkCollision(obj1, obj2) {
var obj1Y = obj1.offsetTop;
var obj2Y = obj2.offsetTop;
var obj1X = obj1.offsetLeft;
var obj2X = obj2.offsetLeft;
if (
obj2Y + 100 >= obj1Y &&
obj2Y <= obj1Y + 100 &&
obj2X + 100 >= obj1X &&
obj2X <= obj1X + 100
) {
return 1;
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
outline: 0;
}
html,
body {
width: 100%;
height: 100%;
}
.container {
position: relative;
width: 100%;
height: 100%;
}
#collector {
width: 50px;
height: 100px;
background: gray;
position: absolute;
top: calc(100vh - 100px);
left: 50%;
margin-left: -25px;
}
<div class="container">
<div id="collector"></div>
</div>
The first thing you should not use setInterval for this type of animation. Use requestAnimationFrame
https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
obj1X,obj1Y comming undefined.
So, I have an event listener keydown on arrow right, when you push the square moving on xPX but my parent element this w and h
set a 100px for example, and I would like to stop moving and I can't, I try with element.offsetWidth > 0 so them you can move.
Please look this fiddle : FIDDLE
Few errors in your code. I've commented fixes. Here is how i made it for the right arrow - you can apply same logic to the rest of the moves...
Code:
const carre = document.querySelector('.carre');
const main = document.querySelector('.main');
const w = main.offsetWidth - carre.offsetWidth; // this was wrong in your code
carre.style.left="0px"; // set start position
document.addEventListener('keyup', (event) => {
const positionLeft = parseInt(carre.style.left); //i've used style.left, rather, it gives expected numbers (10,20,30....)
if(event.keyCode == '39') {
if (positionLeft < w) { // this was fixed too
carre.style.left = (positionLeft) + 10 + 'px';
} else {
carre.style.left = '0'
}
}
})
DEmo:
const carre = document.querySelector('.carre');
const main = document.querySelector('.main');
const w = main.offsetWidth - carre.offsetWidth; // this was wrong in your code
carre.style.left="0px"; // set start position
document.addEventListener('keyup', (event) => {
const positionLeft = parseInt(carre.style.left); //i've used style.left, rather, it gives expected numbers (10,20,30....)
if(event.keyCode == '39') {
if (positionLeft < w) { // this was fixed too
carre.style.left = (positionLeft) + 10 + 'px';
} else {
carre.style.left = '0'
}
}
})
* {
box-sizing:border-box;
}
.carre {
position:absolute;
left: 0;
width: 50px;
height: 50px;
background-color: red;
}
.main {
position: relative;
width: 100px;
height: 100px;
border: 1px solid #000;
}
<main class="main">
<div class="carre"></div>
</main>
I rebuild your code:
document.addEventListener('keydown', (event) => {
const w = main.getBoundingClientRect().right - carre.getBoundingClientRect().right;
const positionLeft = carre.getBoundingClientRect().left;
if(event.keyCode == '39') {
if (w >= 0) {
carre.style.left = (positionLeft) + 10 + 'px';
} else {
carre.style.left = '0'
}
}
if (event.keyCode == '37') {
if (w >= 0) {
carre.style.left = (positionLeft) - 10 + 'px';
}else {
carre.style.left = '0'
}
}
})