For a project I am currently working on making a game in HTML with JavaScript. In the final product the game was functioning perfect. But as I integrated the game in a website the game stopped functioning as it should.
I have made a memory game which you should click for turning to see the picture behind. Since I have integrated the game in a website the pictures are not turning anymore.
I have added my HTML, CSS, and JavaScript code.
I am using Flask as back-end server, and instead of an Apache server. So the Flask server is also handling as a Web Sever.
$(document).ready(function() {
//variablen
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("#canvas").height();
var cw = 15;
var d = "right";
var food;
var score;
var color = "green";
var speed = 100;
//snake
var snake_array;
//init
function init() {
d = "right";
create_snake();
create_food();
score = "0";
if (typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, speed);
}
init();
//De snake wordt geboren
function create_snake() {
var length = 5;
snake_array = [];
for (var i = length - 1; i >= 0; i--) {
snake_array.push({
x: i,
y: 0
});
}
}
//Voedsel balletjes plaatsen
// plaatst voedsel ergens binnen het canvas?
function create_food() {
food = {
x: Math.round(Math.random() * (w - cw) / cw),
y: Math.round(Math.random() * (h - cw) / cw),
};
}
//tekenen snake
function paint() {
//canvas
ctx.fillStyle = "#d3f3ff";
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = "white";
ctx.strokeRect(0, 0, w, h);
// positie van slang variablen
var nx = snake_array[0].x;
var ny = snake_array[0].y;
//besturing
if (d == 'right') nx++;
else if (d == 'left') nx--;
else if (d == 'up') ny--;
else if (d == 'down') ny++;
//botsen
if (nx == -1 || nx == w / cw || ny == -1 || ny == h / cw || Check_Collision(nx, ny, snake_array)) {
//init();
//toevoegen eindscore
$('#eindscore').html(score);
//overlay tonen
$('#overlay').fadeIn(speed = 300)
return;
}
if (nx == food.x && ny == food.y) {
var tail = {
x: nx,
y: ny
};
score++;
//new voedsel moet verschijnen
create_food();
} else {
tail = snake_array.pop();
tail.x = nx;
tail.y = ny;
}
snake_array.unshift(tail);
for (var i = 0; i < snake_array.length; i++) {
var c = snake_array[i];
paint_cell(c.x, c.y);
}
//teken groeien slang
paint_cell(food.x, food.y);
//score controle
checkscore(score);
//score tonen
$('#score').html('Je score: ' + score)
}
function paint_cell(x, y) {
ctx.fillStyle = color;
ctx.fillRect(x * cw, y * cw, cw, cw);
ctx.strokeStyle = "white";
ctx.strokeRect(x * cw, y * cw, cw, cw);
}
function Check_Collision(x, y, SnakeArray) {
for (var I = 0; I < snake_array.Length; I++) {
if (array[I.x == x && snake_array[I].y == y])
return true;
}
return false;
}
function checkscore(score) {
if (localStorage.getItem('eindscore') === null) {
//zonder score
localStorage.setItem('eindscore', score);
} else {
//score al aanwezig
if (score > localStorage.getItem('eindscore')) {
localStorage.setItem('eindscore', score);
}
}
$('#eind_score').html('Score: ' + localStorage.eindscore);
}
//slang besturen
$(document).keydown(function(e) {
var key = e.which;
if (key == "37" && d != "right") d = "left";
else if (key == "38" && d != "down") d = "up";
else if (key == "39" && d != "left") d = "right";
else if (key == "40" && d != "up") d = "down";
})
});
function resetscore() {
localStorage.eind_score = 0;
//
eindscorediv = document.getElementById('eind_score');
eindscorediv.innerHTML = 'Eind Score: 0'
}
html,
body {
margin: 0;
padding: 0;
}
#canvas-game {
margin: 0 auto;
text-align: left;
width: 612px;
margin-top: 20px;
border: Solid 1px #ebe5e5;
height: 385px;
position: relative;
}
#game-statistic {
margin: 0 auto;
text-align: left;
width: 612px;
margin-top: 20px;
}
#statistic-left,
#statistic-right {
font-style: italic;
font-size: 12px;
float: left;
}
#statistic-right {
float: right;
}
.bold-text {
font-weight: bold;
}
.clear {
clear: both;
}
.congrats-message {
color: white;
font-family: "Comic Sans MS";
}
.box-picture {
float: left;
width: 100px;
height: 75px;
border: solid 1px #ebe5e5;
display: none;
}
.box-picture>img {
width: 100px;
height: 75px;
}
.box-cover-wrapper {
position: absolute;
left: 0;
top: 0;
z-index: 100;
}
.box-cover {
width: 100px;
height: 75px;
background: url(../static/MemoryGame/game-images/image-cover.jpg) no-repeat;
border: solid 1px #ebe5e5;
float: left;
cursor: pointer;
}
#game-message {
margin: 0 auto;
font-size: 20px;
background: orangered;
padding: 15px;
border: solid 1px #ccc;
border-radius: 5px;
width: 612px;
display: none;
}
#btnRestart {
padding: 15px;
font-weight: bold;
text-align: center;
background: #66C835;
text-decoration: uppercase;
margin-top: 20px;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
}
/**** Als het scherm kleinder is dan 640px ****/
#media (max-width: 640px) {
#canvas-game {
width: 385px;
height: 348px;
}
.box-picture,
.box-picture>img,
.box-cover {
width: 75px;
height: 56px;
}
.box-cover {
background: url(../static/MemoryGame/game-images/image-cover-75.jpg) no-repeat;
}
#game-statistic {
margin-top: 20px;
}
#game-message,
#game-statistic {
width: 385px;
}
}
/**** Als het scherm kleinder is dan 640px 320px ****/
#media (max-width: 320px) {
#canvas-game {
width: 156px;
height: 390px;
}
.box-picture,
.box-picture>img,
.box-cover {
width: 50px;
height: 38px;
}
.box-cover {
background: url(../static/MemoryGame/game-images/image-cover-50.jpg) no-repeat;
}
#game-statistic {
margin-top: 20px;
}
#game-message,
#game-statistic {
width: 156px;
}
#statistic-left,
#statistic-right {
float: none;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8">
<title>Memory_Game</title>
<link rel="stylesheet" href="../static/TulipAir.css">
<link href="../static/MemoryGame.css" type="text/css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="../static/MemoryGame.js"></script>
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
</head>
<body>
<!-- Titel Website -->
<h1 id="TextCenter">Welkom bij Tulip Air</h1>
<!-- Navigatie bar -->
<ul>
<li>Home</li>
<li>Media</li>
<li>Chat</li>
<li>Reisinformatie</li>
<li>Vliegtuig Informatie</li>
<li><a class="active" href="/Games">Games</a></li>
<li>Webshop</li>
<li id="FloatRight">Admin</li>
</ul>
<div class="games">
<img src="../static/snake.png">
<img src="../static/MemoryGame.jpg">
</div>
<div>
<div id="canvas-game">
<div id="game-content"></div>
</div>
<div id="game-statistic">
<div id="statistic-left">No of Clicks: <span id="no-of-clicks" class="bold-text">0</span></div>
<div id="statistic-right">Correct Guess: <span id="correct-guess" class="bold-text">0</span></div>
<div class="clear"></div>
</div>
<div id="game-message">
<div class="congrats-message">Wooosh, you succesfully landed! :)</div>
<button id="btnRestart" type="button">Speel opnieuw</button>
</div>
</div>
</body>
<footer>
<p id="TextCenter">© Tulip Air</p>
</footer>
</html>
First off all I am really thankful for your quick answers. This is mine first Stack Overflow post, and I found the solution within half an hour. :)
When I whas integrating the code in mine website I deleted a piece of code
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" type="text/css" rel="stylesheet"/>
The code from above helps the picture to move with a 3d transition. After I was deleting unnecessary code I saw that something was missing. I have putted the code back, and everything does work again :)
Related
this is my first question here. I am fairly new to html, css, and javascript.
What I wanted to achieve was similar to this mockup i've created:
my website mockup
I've tried to replace the rectangle on the left side with javascript code to achieve a similar effect. The javascript code was taken from this codepen:
https://codepen.io/vaaghu/pen/abmYGYz
I've nudged the canvas a bit to the right, but if i extend the canvas width and height, the canvas does extend, but the circle animations don't. How do I extend this animation?
var canvas = document.querySelector("canvas")
canvas.width = 800;
canvas.height = 1600;
var c = canvas.getContext("2d");
var mouse = {x:innerWidth/2,y:innerHeight/2}
window.addEventListener("mousemove",(event)=>{
mouse.x = event.x;
mouse.y = event.y;
})
window.addEventListener("resize",()=>{
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
int();
})
function Circle(x, y,dx,dy,radius,color) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.radius = radius;
this.color = color
var maxRadius = 30;
this.draw = function() {
c.beginPath();
c.arc(this.x,this.y,this.radius,0,Math.PI * 2,false);
c.fillStyle = color
c.fill();
}
this.update = function(){
if(this.x+this.radius > innerWidth || this.x-this.radius < 0) {
this.dx = -this.dx;
}
if(this.y+this.radius > innerHeight || this.y -this.radius < 0 ) {
this.dy = -this.dy;
}
if( mouse.x - this.x > -50 && mouse.x - this.x < 50 && mouse.y - this.y >-50 && mouse.y - this.y < 50) {
if (this.radius < maxRadius) {
this.radius += 1
}
} else {
if (this.radius > radius) {
this.radius -= 1
}
}
this.x += this.dx;
this.y += this.dy;
this.draw();
}
}
var colorArray = ["#F5871A","#81968F","#DFAA2F","#D76034","#F5411D"];
var circleArray = []
function int() {
circleArray = []
for (let i = 0; i < 700; i++) {
var x = Math.random() * window.innerWidth;
var y = Math.random() * (window.innerHeight ) ;
var radius = Math.random() * 5 + 2;
var dx = Math.random() - 0.5;
var dy = Math.random() - 0.5;
var color = colorArray[Math.floor(Math.random()*4)]
circleArray.push(new Circle(x,y,dx,dy,radius,color))
}
}
int()
function animate() {
requestAnimationFrame(animate);
c.clearRect(0,0,innerWidth,innerHeight)
for (let i = 0; i < circleArray.length; i++) {
circleArray[i].update()
}
}
animate();
.mediaViewInfo {
--web-view-name: Homepage;
--web-view-id: Homepage;
--web-scale-on-resize: true;
--web-show-navigation-controls: true;
--web-enable-deep-linking: true;
--web-page-font: arial, Manrope;
}
:root {
--web-view-ids: Homepage;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
border: none;
}
#Homepage {
position: absolute;
width: 100%;
height:450%;
font-family: arial, Manrope;
background-color: rgba(255,255,255,1);
overflow: hidden;
--web-view-name: Homepage;
--web-view-id: Homepage;
--web-scale-on-resize: true;
--web-show-navigation-controls: true;
--web-enable-deep-linking: true;
--web-page-font: arial;
}
canvas {
background: #FFFF05;
background-image: linear-gradient(to bottom, #81968F99, #FFE636CC, #FF000066);
margin: 50% 0% 0% 8%;
padding: 0vh 0vh 0vh 0vh;
z-index:-1;
width:auto;
}
#Wave_Vid {
position: absolute;
left: -19px;
top: -1920px;
width: 100vh;
height: 100vh;
overflow: hidden;
}
.Wave_container {
overflow: visible;
}
#MIDDLEcontainer {
position:absolute;
top: 24%;
left:59%;
}
#MIDDLE {
overflow: visible;
}
#Good_ideas_can_take_time {
line-height: 0.8;
width: 100%;
text-align: left;
padding-right: 10%;
font-family: Manrope, arial;
font-style: normal;
font-weight: bold;
font-size: 15vh;
color: rgba(129,150,143,1);
margin-bottom: 30px;
}
#And_execution_takes_even_more {
width: 100%;
line-height: 1em;
text-align: left;
padding-right: 30vh;
font-family: Manrope, arial;
font-style: normal;
font-weight: normal;
font-size: 5vh;
color: rgba(129,150,143,1);
margin-bottom: 20px;
}
#Line_ {
fill: transparent;
stroke: rgba(129,150,143,1);
stroke-width: 4px;
stroke-linejoin: miter;
stroke-linecap: butt;
stroke-miterlimit: 4;
shape-rendering: auto;
}
.Line_ {
width: 509px;
height: 10px;
transform: matrix(1,0,0,1,0,0);
margin-bottom: 40px;
}
#Midcontainer {
position:absolute;
}
#Mid {
float:bottom;
position:absolute;
}
.MySkills {
position: relative;
overflow:visible;
height: 1em;
text-align: left;
font-family: Manrope, arial;
font-style: normal;
font-weight: lighter;
font-size: 12vh;
color: rgba(129,150,143,1);
letter-spacing: -0.85px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>wbdg portfolio</title>
<link rel="stylesheet" type="text/css" id="applicationStylesheet" href="../faux styles.css"/>
</head>
<body>
<div>
<canvas></canvas>
<script id="jssomething" type="text/javascript" src="../faux scripts.js"></script>
<script src="https://kit.fontawesome.com/4f3ce16e3e.js" crossorigin="anonymous"></script>
<div id="MIDDLEcontainer">
<div id="MIDDLE">
<div id="Good_ideas_can_take_time">
<p>Good ideas can take time.</p>
</div>
<div id="And_execution_takes_even_more">
<span>And execution takes even more.</span>
</div>
<svg class="Line_" viewBox="0 0 674 4">
<path id="Line_" d="M 0 0 L 674 0">
</path>
</svg>
<div id="Midcontainer">
<div id="Mid">
<div class="MySkills"> Photos </div>
<div class="MySkills"> Illustrations </div>
<div class="MySkills"> Videos </div>
<div class="MySkills"> Animations </div>
<div class="MySkills"> Branding </div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
If I understand correctly, change these lines in int() function:
var x = Math.random() * window.innerWidth;
var y = Math.random() * (window.innerHeight ) ;
to this:
var x = Math.random() * canvas.width;
var y = Math.random() * canvas.height;
I am trying to build a game similar to the snake game, except it is with shark and a fish. I have written a program that works exactly like the game I wanted to make, but when I tried using an image instead of background color for shark and fish, the just became invisible. I am quoting the code I have written for this. Please suggest how to change background colors of the thing representing shark and fish to their images. the pictures are in the same folder as the code files.
EDIT: i hosted the images online and they are still not visible....
please pardon if there are any mistakes in my code as i am not very great at programming...
//constants n variables
let inputdir = {x: 0, y: 0};
const eatsound = new Audio('eat.wav');
const gosound = new Audio('gameover.wav');
const movesound = new Audio('move.wav');
const musicsound = new Audio('music.mp3');
let speed = 5;
let score = 0;
let lastPaintTime = 0;
let sharkarr = [
{x: 13, y: 15}
]
fish = {x: 6, y: 7};
//game functions
function main(ctime) {
window.requestAnimationFrame(main);
//console.log(ctime)
if((ctime - lastPaintTime)/1000 < 1/speed){
return;
}
lastPaintTime = ctime;
gameEngine();
}
function isCollide(sharkarr) {
if(sharkarr[0].x >= 18*2 || sharkarr[0].x <= -18 || sharkarr[0].y >= 18*2 || sharkarr[0].y <= -18){
return true;
}
}
function gameEngine(){
// updating fish, shark
if(isCollide(sharkarr)){
gosound.play();
musicsound.pause();
inputdir = {x: 0, y: 0};
setTimeout(() => {
alert("GAME OVER!");
}, 2000);
sharkarr = [{x: 13, y: 15}];
musicsound.play();
score = 0;
scoreBox.innerHTML = "Score: " + score;
}
//fish eaten = score+ + fish moved
if(sharkarr[0].y === fish.y && sharkarr[0].x === fish.x){
eatsound.play();
score += 1;
scoreBox.innerHTML = "Score: " + score
let a = 1;
let b = 18;
fish = {x: Math.round(a + (b - a)*Math.random()), y: Math.round(a + (b - a)*Math.random())}
}
//moving shark
for (let i = sharkarr.length - 2; i>=0 ; i--){
//const element = array[i];
sharkarr[i+1] = {...sharkarr[i]};
}
sharkarr[0].x += inputdir.x;
sharkarr[0].y += inputdir.y;
// display shark
board.innerHTML = "";
sharkarr.forEach((e, index)=>{
sharkelement = document.createElement('div');
sharkelement.style.gridRowStart = e.y;
sharkelement.style.gridColumnStart = e.x;
if(index === 0){
sharkelement.classList.add('shark')
}
else{
sharkelement.classList.add('shark');
}
board.appendChild(sharkelement);
})
// display food
fishelement = document.createElement('div');
fishelement.style.gridRowStart = fish.y;
fishelement.style.gridColumnStart = fish.x;
fishelement.classList.add('fish');
board.appendChild(fishelement);
}
//main logic
window.requestAnimationFrame(main);
window.addEventListener('keydown', e =>{
inputdir = {x: 0, y: 1} //starts the game
movesound.play();
musicsound.play();
switch (e.key) {
case "ArrowUp":
//console.log("ArrowUp");
inputdir.x = 0;
inputdir.y = -1;
break;
case "ArrowDown":
//console.log("ArrowDown");
inputdir.x = 0;
inputdir.y = 1;
break;
case "ArrowLeft":
//console.log("ArrowLeft");
inputdir.x = -1;
inputdir.y = 0;
break;
case "ArrowRight":
//console.log("ArrowRight");
inputdir.x = 1;
inputdir.y = 0;
break;
default:
break;
}
})
*{
padding: 0;
margin: 0;
}
body{
background-color: blue;
}
.body{
background-repeat: no-repeat;
background-size: 100vw 100vh;
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
#bg{
width: 100vw;
height: 100vh;
object-fit: cover;
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: -1;
}
#title{
color: white;
border: 2px solid white;
width: 98%;
font-family: Verdana, Geneva, Tahoma, sans-serif;
position: absolute;
top: 1%;
text-align: center;
background-color: green;
font-size: medium;
}
#scoreBox{
color: white;
border: 2px solid white;
width: 98%;
font-family: Verdana, Geneva, Tahoma, sans-serif;
position: absolute;
bottom: 1%;
text-align: center;
background-color: green;
font-size: medium;
}
#board{
width: 98%;
height: 85%;
display: grid;
grid-template-rows: repeat(18, 1fr);
grid-template-columns: repeat(18, 1fr);
border: 10px solid red;
}
.shark{
background-color: #fff;
background-image: url('https://postimg.cc/dDBdCsP4');
background-repeat: no-repeat;
}
.fish{
background-color: yellow;
background-image: url('https://postimg.cc/SYNnd9FV');
background-repeat: no-repeat;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Eat The Fish</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="body">
<video id="bg" autoplay loop muted>
<source src="bg.mp4">
</video>
<div id="title">EAT THE FISH!!!</div>
<div id="scoreBox">Score: 0</div>
<div id="board"></div>
</div>
</body>
<script src="index.js"></script>
</html>
background-clip is for controlling whether a background image extends beyond its element's boundaries. It is not for embedding video clips in the background, and does not accept a url().
https://developer.mozilla.org/en-US/docs/Web/CSS/background-clip
Your background-image rules should work (provided the path to the images is correct) but they are commented out.
I changed this line:
background-clip: url(bg.mp4);
to
background-image: url(https://picsum.photos/300/200);
background-clip: border-box;
Read more about background-clip
I also added some placeholder images to show that your issue is almost certainly a result of an invalid path to your images.
//constants n variables
let inputdir = {x: 0, y: 0};
const eatsound = new Audio('eat.wav');
const gosound = new Audio('gameover.wav');
const movesound = new Audio('move.wav');
const musicsound = new Audio('music.mp3');
let speed = 5;
let score = 0;
let lastPaintTime = 0;
let sharkarr = [
{x: 13, y: 15}
]
fish = {x: 6, y: 7};
//game functions
function main(ctime) {
window.requestAnimationFrame(main);
//console.log(ctime)
if((ctime - lastPaintTime)/1000 < 1/speed){
return;
}
lastPaintTime = ctime;
gameEngine();
}
function isCollide(sharkarr) {
if(sharkarr[0].x >= 18*2 || sharkarr[0].x <= -18 || sharkarr[0].y >= 18*2 || sharkarr[0].y <= -18){
return true;
}
}
function gameEngine(){
// updating fish, shark
if(isCollide(sharkarr)){
gosound.play();
musicsound.pause();
inputdir = {x: 0, y: 0};
setTimeout(() => {
alert("GAME OVER!");
}, 2000);
sharkarr = [{x: 13, y: 15}];
musicsound.play();
score = 0;
scoreBox.innerHTML = "Score: " + score;
}
//fish eaten = score+ + fish moved
if(sharkarr[0].y === fish.y && sharkarr[0].x === fish.x){
eatsound.play();
score += 1;
scoreBox.innerHTML = "Score: " + score
let a = 1;
let b = 18;
fish = {x: Math.round(a + (b - a)*Math.random()), y: Math.round(a + (b - a)*Math.random())}
}
//moving shark
for (let i = sharkarr.length - 2; i>=0 ; i--){
//const element = array[i];
sharkarr[i+1] = {...sharkarr[i]};
}
sharkarr[0].x += inputdir.x;
sharkarr[0].y += inputdir.y;
// display shark
board.innerHTML = "";
sharkarr.forEach((e, index)=>{
sharkelement = document.createElement('div');
sharkelement.style.gridRowStart = e.y;
sharkelement.style.gridColumnStart = e.x;
if(index === 0){
sharkelement.classList.add('shark')
}
else{
sharkelement.classList.add('shark');
}
board.appendChild(sharkelement);
})
// display food
fishelement = document.createElement('div');
fishelement.style.gridRowStart = fish.y;
fishelement.style.gridColumnStart = fish.x;
fishelement.classList.add('fish');
board.appendChild(fishelement);
}
//main logic
window.requestAnimationFrame(main);
window.addEventListener('keydown', e =>{
inputdir = {x: 0, y: 1} //starts the game
movesound.play();
musicsound.play();
switch (e.key) {
case "ArrowUp":
//console.log("ArrowUp");
inputdir.x = 0;
inputdir.y = -1;
break;
case "ArrowDown":
//console.log("ArrowDown");
inputdir.x = 0;
inputdir.y = 1;
break;
case "ArrowLeft":
//console.log("ArrowLeft");
inputdir.x = -1;
inputdir.y = 0;
break;
case "ArrowRight":
//console.log("ArrowRight");
inputdir.x = 1;
inputdir.y = 0;
break;
default:
break;
}
})
*{
padding: 0;
margin: 0;
}
body{
background-color: blue;
}
.body{
background-image: url(https://picsum.photos/300/200);
background-clip: border-box;
background-repeat: no-repeat;
background-size: 100vw 100vh;
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
#bg{
width: 100vw;
height: 100vh;
object-fit: cover;
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: -1;
}
#title{
color: white;
border: 2px solid white;
width: 98%;
font-family: Verdana, Geneva, Tahoma, sans-serif;
position: absolute;
top: 1%;
text-align: center;
background-color: green;
font-size: medium;
}
#scoreBox{
color: white;
border: 2px solid white;
width: 98%;
font-family: Verdana, Geneva, Tahoma, sans-serif;
position: absolute;
bottom: 1%;
text-align: center;
background-color: green;
font-size: medium;
}
#board{
width: 98%;
height: 85%;
display: grid;
grid-template-rows: repeat(18, 1fr);
grid-template-columns: repeat(18, 1fr);
border: 10px solid red;
}
.shark{
background-color: #fff;
background-image: url('https://picsum.photos/30/20');
background-repeat: no-repeat;
}
.fish{
background-color:yellow;
background-image: url('https://picsum.photos/30/20');
background-repeat: no-repeat;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Eat The Fish</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="body">
<video id="bg" autoplay loop muted>
<source src="bg.mp4">
</video>
<div id="title">EAT THE FISH!!!</div>
<div id="scoreBox">Score: 0</div>
<div id="board"></div>
</div>
</body>
<script src="index.js"></script>
</html>
I am building a video game where fireballs drop from the top screen. The spaceship, moved by controllers, must avoid those fireballs in order win. My issue is that I do not know how to detect when the spaceship collides into fireballs. However, I found this link: Detect if animated object touched another object in DOM. I analysed this code and it seems it only works for his issue particularly. Do you guys know how to do this?
Code for image spaceship and fireball:
<img src="Photo/fireball.png" id="fireball">
<img src="Photo/Spaceship1.png" id="icon-p">
Code for spaceship:
let rect = icon
let pos = {top: 1000, left: 570}
const keys = {}
window.addEventListener("keydown", function(e) {keys[e.keyCode] = true})
window.addEventListener("keyup", function(e) {keys[e.keyCode] = false})
const loop = function() {
if (keys[37] || keys[81]) {pos.left -= 10}
if (keys[39] || keys[68]) {pos.left += 10}
if (keys[38] || keys[90]) {pos.top -= 10}
if (keys[40] || keys[83]) {pos.top += 10}
var owidth = display.offsetWidth
var oheight = display.offsetHeight
var iwidth = rect.offsetWidth
var iheight = rect.offsetHeight
if (pos.left < 0) pos.left = -10
if (pos.top < 0) pos.top = -10
if (pos.left + iwidth >= owidth) pos.left = owidth-iwidth
if (pos.top + iheight >= oheight) pos.top= oheight-iheight
rect.setAttribute("data", owidth + ":" + oheight)
rect.style.left = pos.left + "px"; rect.style.top = pos.top + "px"}
let sens = setInterval(loop, 1000 / 60)
Code for fireball:
function fFireball(offset) {
return Math.floor(Math.random() * (window.innerWidth - offset))}
let fireballElement = document.querySelector("#fireball");
let fireball = {x: fFireball(fireballElement.offsetWidth), y: 0}
const fireLoop = function() {
fireball.y += 2
fireballElement.style.top = fireball.y + 'px'
if (fireball.y > window.innerHeight) {
fireball.x = fFireball(fireballElement.offsetWidth)
fireballElement.style.left = fireball.x + 'px'; fireball.y = 0}}
fireballElement.style.left = fireball.x + 'px'
let fireInterval = setInterval(fireLoop, 1000 / 100)
Thanks!
here I've integrated collision detection for your game. The most notable thing is in this function:
function checkCollision() {
var elem = document.getElementById("icon");
var elem2 = document.getElementById("fireball");
if ( detectOverlap(elem, elem2) && elem2.getAttribute('hit')=='false' ){
hits++; // detect hit and increase
elem2.setAttribute('hit', true); // set attribute to not have flooding
console.log( hits ); // console it just to see it
}
setTimeout( checkCollision, 20);
}
In lower window you can test demo that I've built for you without images but some random boxes as images :)
Good luck with game man, cool
//////////
"use strict"
//Stay on focus
function stayOnFocus() {
setTimeout(function() {
alert("Do not exit window or game progression will be lost!")
}, 1000)
}
let hits = 0
//"A" keypress plays Music
document.addEventListener('keydown', function(e) {
if (e.keyCode !== 173) {
//document.getElementById('audio').play()
}
})
//Input Validation
let icon = document.getElementById("icon")
let fireballElement = document.querySelector("#fireball")
var input = document.getElementById("input")
input.addEventListener("keydown", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("begin-timer").click()
}
})
//CountDown (3...2...1)
var count = 3
function countDown() {
function preventCountFast() {
document.getElementById("count").innerHTML = count
if (count > 0) {
count--
} else {
clearInterval(ncount);
document.getElementById("count").style.display = "none"
}
}
var ncount = setInterval(preventCountFast, 1000)
}
//Name displayed + space(switch between images) + parameter icon displayed
function Username(field) {
field = input.value
if (field == "") {
alert("Complete blanks");
return false
}
document.getElementById("askName").style.display = "none"
setTimeout(function() {
document.getElementById("name").innerHTML = "Player: " + field
icon.style.display = 'block';
fireballElement.style.display = "block"
const images = ["https://placehold.it/30x30", "https://placehold.it/90x90",
"https://placehold.it/120x40", "https://placehold.it/100x100"
]
document.body.onkeyup = function(e) {
if (e.keyCode === 32) {
hits++;
icon.src = images[hits % 5]
}
}
checkCollision();
}, 4000)
}
//Spaceship moves into space + prevent going out borders
let display = document.getElementById("body");
let rect = icon
let pos = {
top: 1000,
left: 570
}
const keys = {}
window.addEventListener("keydown", function(e) {
keys[e.keyCode] = true
})
window.addEventListener("keyup", function(e) {
keys[e.keyCode] = false
})
const loop = function() {
if (keys[37] || keys[81]) {
pos.left -= 10
}
if (keys[39] || keys[68]) {
pos.left += 10
}
if (keys[38] || keys[90]) {
pos.top -= 10
}
if (keys[40] || keys[83]) {
pos.top += 10
}
var owidth = display.offsetWidth
var oheight = display.offsetHeight
var iwidth = rect.offsetWidth
var iheight = rect.offsetHeight
if (pos.left < 0) pos.left = -10
if (pos.top < 0) pos.top = -10
if (pos.left + iwidth >= owidth) pos.left = owidth - iwidth
if (pos.top + iheight >= oheight) pos.top = oheight - iheight
rect.setAttribute("data", owidth + ":" + oheight)
rect.style.left = pos.left + "px";
rect.style.top = pos.top + "px"
}
let sens = setInterval(loop, 1000 / 60)
//Parameter Sensibility
let param = document.getElementById("parameters")
let b2 = document.getElementById("body2")
document.getElementById("general").addEventListener("click", function() {
param.style.display = "block";
b2.style.display = "none"
})
function validateSens() {
b2.style.display = "block";
param.style.display = "none";
clearInterval(sens)
let sensibilty = parseFloat(document.getElementById("sensibilty").value)
switch (sensibilty) {
case 1:
sens = setInterval(loop, 1000 / 40);
break;
case 2:
sens = setInterval(loop, 1000 / 60);
break;
case 3:
sens = setInterval(loop, 1000 / 80);
break;
default:
alert("Sorry, a bug occured")
}
}
//Fireball script
function fFireball(offset) {
return Math.floor(Math.random() * (window.innerWidth - offset))
}
let fireball = {
x: fFireball(fireballElement.offsetWidth),
y: 0
}
const fireLoop = function() {
fireball.y += 2;
fireballElement.style.top = fireball.y + 'px'
if (fireball.y > window.innerHeight) {
fireball.x = fFireball(fireballElement.offsetWidth)
fireballElement.style.left = fireball.x + 'px';
fireball.y = 0;
fireballElement.setAttribute('hit', false );
}
}
fireballElement.style.left = fireball.x + 'px'
let fireInterval = setInterval(fireLoop, 1000 / 100)
function checkCollision() {
var elem = document.getElementById("icon");
var elem2 = document.getElementById("fireball");
if (detectOverlap(elem, elem2) && elem2.getAttribute('hit')=='false' ){
hits++; // detect hit
elem2.setAttribute('hit', true);
aler("hi")
}
setTimeout( checkCollision, 20);
}
// detect fn
var detectOverlap = (function() {
function getPositions(elem) {
var pos = elem.getBoundingClientRect();
return [
[pos.left, pos.right],
[pos.top, pos.bottom]
];
}
function comparePositions(p1, p2) {
var r1, r2;
r1 = p1[0] < p2[0] ? p1 : p2;
r2 = p1[0] < p2[0] ? p2 : p1;
return r1[1] > r2[0] || r1[0] === r2[0];
}
return function(a, b) {
var pos1 = getPositions(a),
pos2 = getPositions(b);
return comparePositions(pos1[0], pos2[0]) && comparePositions(pos1[1], pos2[1]);
};
})();
body {
user-select: none;
margin: 0px;
height: 100vh;
padding: 0;
width: 100%;
background-image: url(Photo/bg.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
animation: intro-fade 3s;
background-size: cover;
overflow: hidden;
}
#askName {
display: block;
z-index: 1;
margin-left: auto;
margin-top: 12%;
margin-right: auto;
width: 400px;
text-align: center;
background-color: #737373;
opacity: 0.8;
border-radius: 15px;
padding: 40px 50px 40px 50px;
}
#askName:hover {
opacity: 0.9
}
#askName>label {
text-align: center;
font-size: 150%;
font-weight: lighter;
text-align: center;
}
#askName>input {
display: block;
font-size: 100%;
margin: 30px auto 20px auto;
border: none;
border-radius: 10px;
padding: 10px 20px 10px 20px;
}
#askName>button {
background-color: #e6e6e6;
cursor: pointer;
padding: 10px 20px 10px 20px;
border: none;
border-radius: 10px;
}
#count {
margin-top: 13%;
animation: count-down 16s;
font-weight: lighter;
font-family: cursive;
text-align: center;
color: black;
font-size: 200px;
}
h6 {
margin-right: 20px;
padding-top: 5px;
font-weight: normal;
font-family: sans-serif;
margin-top: 0px;
color: white;
text-align: center;
font-size: 190%;
cursor: default;
}
h6:hover {
font-size: 210%
}
#icon {
position: absolute;
top: 0;
left: 0;
cursor: none;
width: 9%;
}
#general {
position: absolute;
cursor: pointer;
min-width: 4%;
top: 10px;
width: 4%;
right: 10px;
}
#general:hover {
transform: rotate(-100deg)
}
#parameters {
text-align: center;
display: none;
animation: intro-fade 3s;
height: auto;
border: none;
background-color: #d9d9d9;
color: black;
position: absolute;
padding: 0px 60px 20px 60px;
left: 50%;
width: auto;
min-width: 200px;
top: 50%;
transform: translate(-50%, -50%);
border-radius: 13px;
}
h3 {
color: black;
font-weight: normal;
font-size: 150%;
}
#sensibilty {
display: block;
margin-right: auto;
margin-left: auto;
}
#validateSens {
margin-top: 20px;
border: none;
padding: 10px;
border-radius: 5px;
cursor: pointer;
}
#keyframes intro-fade {
from {
opacity: 0
}
to {
opacity: 1
}
}
#keyframes count-down {
from {
transform: scale(0)
}
to {
transform: scale(1)
}
}
<body id="body" onload="stayOnFocus()">
<img src="https://placehold.it/350x350" id="general">
<section id="parameters">
<h3> Choose your sensibility </h3>
<input type="range" id="sensibilty" min="1" max="3" value="2">
<button id="validateSens" onclick="validateSens()"> Submit </button>
</section>
<main id="body2">
<form id="askName" title="Write your name"> <label> Enter your username: </label>
<input id="input" type="text" maxlength="10" autofocus>
<button type="button" onclick="countDown(); return Username()" id="begin-timer"> Submit </button>
</form>
<h6 id="name"></h6>
<h2 id="count"></h2>
<img src="https://placehold.it/50x52" id="fireball" style="display:none; width:3%; position:absolute; cursor:none">
<img src="https://placehold.it/80x40" id="icon" style="display:none">
</main>
I'm trying to learn to move a second object with the WASD keys and I cannot find much specific information that details how it is done. I'm also having trouble resizing it. I'm currently exploring this game to learn all I can.
https://jsfiddle.net/t2mjc5k1/ <=== code posted below.
I've tried a few prewritten javascript snippets that I saw online. I am using one that I found here on StackOverflow. I have also been using this website (https://keycode.info/) to better understand how event keycodes work.
// Arrow key codes
var UP = 38,
DOWN = 40,
RIGHT = 39,
LEFT = 37;
//wasd keycodes
/*var W = 87,
A = 65,
S = 83,
D = 68;*/
// rocket object
var rocket = {
img: document.querySelector("#rocket"),
x: 490,
y: 390,
width: 100
};
var UFO = {
img: document.querySelector("#ufo"),
x: 300,
y: 200,
width: 200 // Need to read up on x,y positioning.S
};
//sound array
var sounds = ["#Photon", "#Shrapnel"];
var currentSound = null;
const velocity = 8;
let torpedo = document.querySelector("#torpedo"),
startBtn = document.querySelector("#start"),
fireBtn = document.querySelector("#fire"),
ufo = document.querySelector("#ufo");
// Initialize objects on the screen
render ( );
/*
function startGameHandler( ) {
"use strict"
// Hide the intro screen, show the game screen
introScreen.style.display = "none";
gameScreen.style.display = "block";
rocket.img.style.display = "block";
ufo.style.display = "block";
}
*/
const startGameHandler = ( ) => {
"use strict";
// Hide the intro screen, show the game screen
introScreen.style.display = "none";
gameScreen.style.display = "block";
rocket.img.style.display = "block";
ufo.style.display = "block";
};
function fireTorpedoHandler( ) {
"use strict"
// Fire the photon torpedo!
// CSS animation occurs whenever torpedo
// 'left' property changes value
torpedo.style.visibility = "visible";
torpedo.style.left = (rocket.x - 200)+ "px";
}
const keydownHandler = event => {
"use strict"
if (event.keyCode == UP) {
rocket.y -= velocity;
}
if (event.keyCode == LEFT) {
rocket.x -= velocity;
}
if (event.keyCode === DOWN) {
rocket.y += velocity;
}
if (event.keyCode == RIGHT) {
rocket.x += velocity;
}
render( );
}
//moving the UFO
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
function onKeyDown(event) {
var keyCode = event.keyCode;
switch (keyCode) {
case 68: //d
keyD = true;
break;
case 83: //s
keyS = true;
break;
case 65: //a
keyA = true;
break;
case 87: //w
keyW = true;
break;
}
}
function onKeyUp(event) {
var keyCode = event.keyCode;
switch (keyCode) {
case 68: //d
keyD = false;
break;
case 83: //s
keyS = false;
break;
case 65: //a
keyA = false;
break;
case 87: //w
keyW = false;
break;
}
}
//neccessary variables
var clickX = 10;
var clickY = 10;
var keyW = false;
var keyA = false;
var keyS = false;
var keyD = false;
//main animation function
function ufoBooster() {
window.requestAnimationFrame(ufoBooster);
var canvas = document.getElementById("ufo");
if (keyD == true) {
clickX += 1;
}
if (keyS == true) {
clickY += 1;
}
if (keyA == true) {
clickX--;
}
if (keyW == true) {
clickY--;
}
}
window.requestAnimationFrame(ufoBooster);
// Moved here to get the arrow function to work.
startBtn.addEventListener("click",startGameHandler,false);
fireBtn.addEventListener("click",fireTorpedoHandler,false)
window.addEventListener("keydown",keydownHandler,false);
//ufo event listeners
window.addEventListener("keydown", onKeyDown, false);
window.addEventListener("keyup", onKeyUp, false);
function render( ) {
"use strict"
// position objects on the screen
rocket.img.style.left = rocket.x + "px";
rocket.img.style.top = rocket.y + "px";
torpedo.style.left = (rocket.x +10) + "px";
torpedo.style.top = (rocket.y+8) + "px";
torpedo.style.visibility = "hidden";
}
* { margin: 0;
padding: 0;
}
#font-face {
font-family: 'spaceAge';
src: url('../fonts/space_age-webfont.eot');
src: url('../fonts/space_age-webfont.eot?#iefix') format('embedded-opentype'),
url('../fonts/space_age-webfont.woff') format('woff'),
url('../fonts/space_age-webfont.ttf') format('truetype'),
url('../fonts/space_age-webfont.svg#space_ageregular') format('svg');
font-weight: normal;
font-style: normal;
}
#introScreen {
margin: 50px auto;
padding: 50px 30px;
width: 540px;
height: 350px;
position: relative;
background-color: #0d152a;
font-family: Arial, Helvetica, sans-serif;
color: white;
}
#title {
font-size: 32px;
line-height: 1.1em;
font-family: spaceAge;
}
#introScreen img {
float: left;
margin-right: 20px;
}
#introScreen h3 {
clear: both;
font-family: spaceAge;
margin-top: 40px;
}
#introScreen div {
margin-top: 40px;
text-align: center;
}
button {
font-family: spaceAge;
font-size: 150%;
padding: 4px 8px;
cursor: pointer;
color: white;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
background: -webkit-linear-gradient(top, #a3a3a3, #000);
background: -moz-linear-gradient(top, #a3a3a3, #000);
background: linear-gradient(top, #a3a3a3, #000);
-webkit-box-shadow: 0px 5px 8px 3px rgba(255,255,255,0.3);
-moz-box-shadow: 0px 5px 8px 3px rgba(255,255,255,0.3);
box-shadow: 0px 5px 8px 3px rgba(255,255,255,0.3);
}
button:hover {
background: -webkit-linear-gradient(top, #acc7a3, #506651);
background: -moz-linear-gradient(top, #acc7a3, #506651);
background: linear-gradient(top, #acc7a3, #506651);
}
#gameScreen {
margin: 50px auto;
width: 600px;
height: 450px;
background-image: url("../images/bkg.jpg");
display:none;
position: relative;
}
#rocket {
position: absolute;
display: none;
}
#torpedo {
position: absolute;
/* transition */
-webkit-transition: left 0.5s ease-out 0s;
-moz-transition: left 0.5s ease-out 0s;
transition: left 0.5s ease-out 0s;
}
#ufo {
position: absolute;
display: none;
}
#gameUI {
width: 560px;
height: 50px;
padding: 10px 20px;
background-color: rgba(0,0,0,0.5);
color: white;
font-family: spaceAge;
line-height: 1em;
}
#gameInfo {
width: 450px;
height: 120px;
font-size: 120%;
float: left;
}
#gameControls {
width: 50px;
height: 55px;
padding-top: 5px;
float:left;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Space Arcade</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<section id="introScreen">
<img src="images/introImage.jpg" alt="intro image">
<span id="title">Big<br>Space<br>Sprite<br>Mover</span>
<h3>How to play:</h3>
<p>Use the arrow keys to move the rocket ship up, down, left, or right. Hit the <strong>Fire!</strong> button to fire a photon torpedo.</p>
<div>
<button id="start">Engage!</button>
</div>
</section>
<section id="gameScreen">
<div id="gameUI">
<div id="gameInfo">
<p>Dilithium fuel: 100%</p>
<p>Phasers: 25</p>
<p>Photon torpedoes: 10</p>
</div>
<div id="gameControls">
<button type= button id="fire" >Fire!</button>
</div>
</div>
<!-- absolutely positioned elements -->
<img id="ufo" src="images/ufo.png" alt="UFO">
<img id="torpedo" src="images/torpedo.png" alt="torpedo">
<img id="rocket" src="images/rocket.png" alt="Rocket Ship sprite">
</section>
<!--<input type="button" value="PLAY" onclick="play()">
<audio id="audio" src="photon.mp3" ></audio>-->
<audio id="Photon">
<source src="Photon.mp3" type="audio/mp3">
<source src="Photon.ogg" type="audio/ogg">
</audio>
<audio id="Shrapnel">
<source src="Shrapnel.mp3" type="audio/mp3">
<source s`enter code here`rc="Shrapnel.ogg" type="audio/ogg">
</audio>
<script src="js/program.js"></script>
</body>
</html>
I would like to learn to move the ufo image with the WASD keys. The rocket image is currently bound to the arrow keys.
Hello fellow game developer (so it seems), why are you not using canvas or other libraries like PixiJS?
Anyway, how I like to do it, is to actually create separate objects for the controls and the checks for whether the key is down:
Objects/Variables
//Controls
var controls = {
"ufo":
{
"left":[65, 74], //A/J
"right":[68, 76], //D/L
"up":[87, 73], //W/I
"down":[83, 75] //S/K
}
"rocket":{
"left":[37], //LEFT
"right":[39], //RIGHT
"up":[38], //UP
"down":[40] //DOWN
},
"pause":[80], //P
"mute":[77] //M
};
//Is Key down?
//For eg, if the W (87) key is down, isKeyDown[87] will be true, otherwise, false.
var isKeyDown = {};
//To Set:
for(var i in controls)
if(controls.hasOwnProperty(i))
if(i=="rocket" || i=="ufo"){ //special cases where we have nested objects
for(var j in controls[i]){
for(var k=0;j<controls[i][j].length;k++)
isKeyDown[controls[i][j][k]] = false;
}
}
else for(var j=0;j<controls[i].length;j++)
isKeyDown[controls[i][j]] = false;
This is very good for scalability: You can include button presses for other things like pause and mute. You can also have multiple keypresses to do the same thing (eg. I added WASD and IJKL for you so BOTH can now move the UFO).
Event Listeners
window.addEventListener("keydown", function (e) {
for(i in isKeyDown)
if(isKeyDown.hasOwnProperty(i) && e.keyCode == i)
isKeyDown[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function (e) {
if(isKeyDown[e.keyCode] != undefined)
isKeyDown[e.keyCode] = false;
else return;
//Actual movements can be handled elsewhere in your tick/main animation function (see below)
//Pausing and muting (just in case you want them):
for(var j=0;j<controls["pause"].length;j++)
if(e.keyCode==controls["pause"][j]){
//PAUSE GAME
break;
}
for(var j=0;j<controls["mute"].length;j++)
if(e.keyCode==controls["mute"][j]){
//MUTE GAME
break;
}
}, false);
Inside your tick/Animation Function
//FOR MOVEMENTS. To go in your main tick/animation function
var movements = {
"ufo":{
"up":false,
"down":false,
"right":false,
"left":false
},
"rocket":{
"up":false,
"down":false,
"right":false,
"left":false
}
};
//Rocket
for(var i in controls["rocket"])
if(controls.hasOwnProperty(i))
for(var j=0;j<controls["rocket"][i].length;j++){
if(isKeyDown[controls["rocket"][i][j]])
movements["rocket"][i] = true;
}
//UFO
for(var i in controls["ufo"])
if(controls.hasOwnProperty(i))
for(var j=0;j<controls["ufo"][i].length;j++){
if(isKeyDown[controls["ufo"][i][j]])
movements["ufo"][i] = true;
}
For the Actual movements
//Actual movements, also to go into your tick function or equivalent handler:
//Rocket
if (event.keyCode == movements["rocket"]["up"]) {
rocket.y -= velocity;
}
if (event.keyCode == movements["rocket"]["left"]) {
rocket.x -= velocity;
}
if (event.keyCode === movements["rocket"]["down"]) {
rocket.y += velocity;
}
if (event.keyCode == movements["rocket"]["right"]) {
rocket.x += velocity;
}
//UFO
if (event.keyCode == movements["ufo"]["up"]) {
UFO.y -= velocity;
}
if (event.keyCode == movements["ufo"]["left"]) {
UFO.x -= velocity;
}
if (event.keyCode === movements["ufo"]["down"]) {
UFO.y += velocity;
}
if (event.keyCode == movements["ufo"]["right"]) {
UFO.x += velocity;
}
While the previous user has already "answered" your question, I believe that as you scale up your game to become larger with more functions, this method will be more useful.
You can simply duplicate the code that you have for the rocket and use it for the UFO. To bind the movement key to WASD instead, just extend the if statements in your keydownHandler function to include the WASD keys
// Arrow key codes
var UP = 38,
DOWN = 40,
RIGHT = 39,
LEFT = 37;
//wasd keycodes
var W = 87,
A = 65,
S = 83,
D = 68;
// rocket object
var rocket = {
img: document.querySelector("#rocket"),
x: 490,
y: 390,
width: 100
};
var UFO = {
img: document.querySelector("#ufo"),
x: 300,
y: 200,
width: 200 // Need to read up on x,y positioning.S
};
//sound array
var sounds = ["#Photon", "#Shrapnel"];
var currentSound = null;
const velocity = 8;
let torpedo = document.querySelector("#torpedo"),
startBtn = document.querySelector("#start"),
fireBtn = document.querySelector("#fire"),
ufo = document.querySelector("#ufo");
// Initialize objects on the screen
render ( );
/*
function startGameHandler( ) {
"use strict"
// Hide the intro screen, show the game screen
introScreen.style.display = "none";
gameScreen.style.display = "block";
rocket.img.style.display = "block";
ufo.style.display = "block";
}
*/
const startGameHandler = ( ) => {
"use strict";
// Hide the intro screen, show the game screen
introScreen.style.display = "none";
gameScreen.style.display = "block";
rocket.img.style.display = "block";
ufo.style.display = "block";
};
function fireTorpedoHandler( ) {
"use strict"
// Fire the photon torpedo!
// CSS animation occurs whenever torpedo
// 'left' property changes value
torpedo.style.visibility = "visible";
torpedo.style.left = (rocket.x - 200)+ "px";
}
const keydownHandler = event => {
"use strict"
if (event.keyCode == UP) {
rocket.y -= velocity;
}
if (event.keyCode == LEFT) {
rocket.x -= velocity;
}
if (event.keyCode === DOWN) {
rocket.y += velocity;
}
if (event.keyCode == RIGHT) {
rocket.x += velocity;
}
if (event.keyCode == W) {
UFO.y -= velocity;
}
if (event.keyCode == A) {
UFO.x -= velocity;
}
if (event.keyCode === S) {
UFO.y += velocity;
}
if (event.keyCode == D) {
UFO.x += velocity;
}
render( );
}
//moving the UFO
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
//neccessary variables
var clickX = 10;
var clickY = 10;
var keyW = false;
var keyA = false;
var keyS = false;
var keyD = false;
//main animation function
function ufoBooster() {
window.requestAnimationFrame(ufoBooster);
var canvas = document.getElementById("ufo");
if (keyD == true) {
clickX += 1;
}
if (keyS == true) {
clickY += 1;
}
if (keyA == true) {
clickX--;
}
if (keyW == true) {
clickY--;
}
}
window.requestAnimationFrame(ufoBooster);
// Moved here to get the arrow function to work.
startBtn.addEventListener("click",startGameHandler,false);
fireBtn.addEventListener("click",fireTorpedoHandler,false)
window.addEventListener("keydown",keydownHandler,false);
function render( ) {
"use strict"
// position objects on the screen
rocket.img.style.left = rocket.x + "px";
rocket.img.style.top = rocket.y + "px";
UFO.img.style.left = UFO.x + "px";
UFO.img.style.top = UFO.y + "px";
torpedo.style.left = (rocket.x +10) + "px";
torpedo.style.top = (rocket.y+8) + "px";
torpedo.style.visibility = "hidden";
}
* { margin: 0;
padding: 0;
}
#font-face {
font-family: 'spaceAge';
src: url('../fonts/space_age-webfont.eot');
src: url('../fonts/space_age-webfont.eot?#iefix') format('embedded-opentype'),
url('../fonts/space_age-webfont.woff') format('woff'),
url('../fonts/space_age-webfont.ttf') format('truetype'),
url('../fonts/space_age-webfont.svg#space_ageregular') format('svg');
font-weight: normal;
font-style: normal;
}
#introScreen {
margin: 50px auto;
padding: 50px 30px;
width: 540px;
height: 350px;
position: relative;
background-color: #0d152a;
font-family: Arial, Helvetica, sans-serif;
color: white;
}
#title {
font-size: 32px;
line-height: 1.1em;
font-family: spaceAge;
}
#introScreen img {
float: left;
margin-right: 20px;
}
#introScreen h3 {
clear: both;
font-family: spaceAge;
margin-top: 40px;
}
#introScreen div {
margin-top: 40px;
text-align: center;
}
button {
font-family: spaceAge;
font-size: 150%;
padding: 4px 8px;
cursor: pointer;
color: white;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
background: -webkit-linear-gradient(top, #a3a3a3, #000);
background: -moz-linear-gradient(top, #a3a3a3, #000);
background: linear-gradient(top, #a3a3a3, #000);
-webkit-box-shadow: 0px 5px 8px 3px rgba(255,255,255,0.3);
-moz-box-shadow: 0px 5px 8px 3px rgba(255,255,255,0.3);
box-shadow: 0px 5px 8px 3px rgba(255,255,255,0.3);
}
button:hover {
background: -webkit-linear-gradient(top, #acc7a3, #506651);
background: -moz-linear-gradient(top, #acc7a3, #506651);
background: linear-gradient(top, #acc7a3, #506651);
}
#gameScreen {
margin: 50px auto;
width: 600px;
height: 450px;
background-image: url("../images/bkg.jpg");
display:none;
position: relative;
}
#rocket {
position: absolute;
display: none;
}
#torpedo {
position: absolute;
/* transition */
-webkit-transition: left 0.5s ease-out 0s;
-moz-transition: left 0.5s ease-out 0s;
transition: left 0.5s ease-out 0s;
}
#ufo {
position: absolute;
display: none;
}
#gameUI {
width: 560px;
height: 50px;
padding: 10px 20px;
background-color: rgba(0,0,0,0.5);
color: white;
font-family: spaceAge;
line-height: 1em;
}
#gameInfo {
width: 450px;
height: 120px;
font-size: 120%;
float: left;
}
#gameControls {
width: 50px;
height: 55px;
padding-top: 5px;
float:left;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Space Arcade</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<section id="introScreen">
<img src="images/introImage.jpg" alt="intro image">
<span id="title">Big<br>Space<br>Sprite<br>Mover</span>
<h3>How to play:</h3>
<p>Use the arrow keys to move the rocket ship up, down, left, or right. Hit the <strong>Fire!</strong> button to fire a photon torpedo.</p>
<div>
<button id="start">Engage!</button>
</div>
</section>
<section id="gameScreen">
<div id="gameUI">
<div id="gameInfo">
<p>Dilithium fuel: 100%</p>
<p>Phasers: 25</p>
<p>Photon torpedoes: 10</p>
</div>
<div id="gameControls">
<button type= button id="fire" >Fire!</button>
</div>
</div>
<!-- absolutely positioned elements -->
<img id="ufo" src="images/ufo.png" alt="UFO">
<img id="torpedo" src="images/torpedo.png" alt="torpedo">
<img id="rocket" src="images/rocket.png" alt="Rocket Ship sprite">
</section>
<!--<input type="button" value="PLAY" onclick="play()">
<audio id="audio" src="photon.mp3" ></audio>-->
<audio id="Photon">
<source src="Photon.mp3" type="audio/mp3">
<source src="Photon.ogg" type="audio/ogg">
</audio>
<audio id="Shrapnel">
<source src="Shrapnel.mp3" type="audio/mp3">
<source s`enter code here`rc="Shrapnel.ogg" type="audio/ogg">
</audio>
<script src="js/program.js"></script>
</body>
</html>
I'm trying to create a game using Jquery however I have an issue when trying to make the webpage responsive. The issue is that I'm unable to make my game-board "spelplan" responsive, I know the reason this happens is because parts of my script is connected to the "width" of the game-board so when I remove the "width" and replace it with <div id="spelplan" class="col-6 col-m-6"> these parts get completely messed up. So what I need help with is how I make my game-board "spelplan" responsive, I would really appreciate any help I can get with this.
function updateClock() {
var currentTime = new Date();
var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
var currentSeconds = currentTime.getSeconds();
currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;
var timeOfDay = (currentHours < 12) ? "AM" : "PM";
currentHours = (currentHours > 12) ? currentHours - 12 : currentHours;
currentHours = (currentHours == 0) ? 12 : currentHours;
var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background-color: black;
}
header {
position: absolute;
top: 50px;
color: white;
text-align: center;
}
#clock {
font-size: 25px;
position: absolute;
color: white;
}
#rand_pos {
position: absolute;
top: 20%;
left: 30%;
z-index: 10;
}
.player {
background-color: red;
height: 50px;
width: 50px;
position: absolute;
top: 100px;
left: 100px;
z-index: 100;
}
p {
position: relative;
left: 10px;
color: white;
}
#spelplan {
position: relative;
left: 35%;
top: 200px;
height: 600px;
width: 600px;
background-color: blue;
border-style: double;
border-radius: 40px;
}
.rand {
background-color: green;
height: 15px;
width: 15px;
position: absolute;
left: 30%;
top: 150px;
z-index: 3;
}
.new_pos {
background: #ccc;
border: 1px solid #000;
padding: 5px;
box-shadow: 0 0 20px #555;
-webkit-transition: all .2s ease-in;
transition: all .2s ease-in;
}
.new_pos:hover {
background: #bbb;
box-shadow: 0 0 20px #222;
}
.new_pos:active {
box-shadow: 0 0 20px #000;
background: #aaa;
}
*:focus {
outline: none;
}
.new_pos {
position: fixed;
left: 0;
bottom: 0;
cursor: pointer;
}
#footer {
position: absolute;
top: 80vh;
color: white;
text-align: center;
}
/* For mobile phones: */
[class*="col-"] {
width: 100%;
}
#media only screen and (min-width: 600px) {
/* For tablets: */
.col-m-1 {
width: 8.33%;
}
.col-m-2 {
width: 16.66%;
}
.col-m-3 {
width: 25%;
}
.col-m-4 {
width: 33.33%;
}
.col-m-5 {
width: 41.66%;
}
.col-m-6 {
width: 50%;
}
.col-m-7 {
width: 58.33%;
}
.col-m-8 {
width: 66.66%;
}
.col-m-9 {
width: 75%;
}
.col-m-10 {
width: 83.33%;
}
.col-m-11 {
width: 91.66%;
}
.col-m-12 {
width: 100%;
}
img {
width: 80%;
height: auto;
}
}
#media only screen and (min-width: 768px) {
/* For desktop: */
.col-1 {
width: 8.33%;
}
.col-2 {
width: 16.66%;
}
.col-3 {
width: 25%;
}
.col-4 {
width: 33.33%;
}
.col-5 {
width: 41.66%;
}
.col-6 {
width: 50%;
}
.col-7 {
width: 58.33%;
}
.col-8 {
width: 66.66%;
}
.col-9 {
width: 75%;
}
.col-10 {
width: 83.33%;
}
.col-11 {
width: 91.66%;
}
.col-12 {
width: 100%;
}
img {
width: 100%;
height: auto;
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style20.css">
<script type='text/javascript' src='eventjavascript6.js'></script>
<title>Jquery spel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var sprites = [];
var enemies = [];
var game = $("#spelplan");
var score = 0;
var el_score = $("#score")
function SCORE(pts) {
score += pts
el_score.text(score);
}
function RND(min, max) {
return parseInt(Math.random() * (max - min) + min);
}
var sprite = function(id, x, y, w, h, _class, view, collisionDetect, options) {
this.view = view;
this.id = id
this.x = x + "px";
this.y = y + "px";
this.width = w;
this.height = h;
this.options = options;
this.el = $("<div id='" + this.id + "' class='" + _class + "'></div>").css('left', this.x).css('top', this.y);
view.append(this.el);
this.x = function() {
return this.el.position().left;
}
this.y = function() {
return this.el.position().top;
}
this.up = function() {
if (this.y() > 0) {
this.el.animate({
top: '-=25px'
}, 0);
if (collisionDetect) collisionDetect(this);
}
};
this.down = function() {
if (this.y() < this.view.height() - this.height) {
this.el.animate({
top: '+=25px'
}, 0);
if (collisionDetect) collisionDetect(this);
}
};
this.left = function() {
if (this.x() > 0) {
this.el.animate({
left: '-=25px'
}, 0);
if (collisionDetect) collisionDetect(this);
}
};
this.right = function() {
if (this.x() + this.width < this.view.width()) {
this.el.animate({
left: '+=25px'
}, 0);
if (collisionDetect) collisionDetect(this);
}
this.destroy = function() {
this.el.remove();
for (var i = 0; i < sprites.length; i++) {
if (data[i].id == this.id) {
sprites.splice(i, 1);
break;
}
}
}
};
this.getPos = function() {
var pos, width, height;
pos = this.el.position();
width = this.el.width();
height = this.el.height();
return [
[pos.left, pos.left + width],
[pos.top, pos.top + height]
];
};
this.comparePos = function(p1, p2) {
var r1, r2;
r1 = p1[0] < p2[0] ? p1 : p2;
r2 = p1[0] < p2[0] ? p2 : p1;
return r1[1] > r2[0] || r1[0] === r2[0];
};
this.collidesWith = function(sprite) {
if (sprite.destroyed === true) return;
var pos1 = this.getPos(),
pos2 = sprite.getPos();
return this.comparePos(pos1[0], pos2[0]) && this.comparePos(pos1[1], pos2[1]);
};
if (this.options && this.options.init) this.options.init(this);
sprites.push(this);
};
function spawnrand() {
if (sprites.length > 100) return
var points = [50, 100, 200, 300, 400, 500];
var spelplanWidth = game.width();
var spelplanHeight = game.height();
var randPosY = Math.floor((Math.random() * spelplanHeight));
var randPosX = Math.floor((Math.random() * spelplanWidth));
var enemy = new sprite("enemy" + sprites.length + 1, randPosY, randPosX, 15, 15, "rand", game, null, {
PTS: points[RND(0, 5)],
init: function(sprite) {
sprite.selfDestruct = setTimeout(function() {
sprite.el.fadeOut(1000, function() {});
}, 5000);
}
});
enemies.push(enemy);
}
SCORE(0);
var player = new sprite("box1", 200, 200, 50, 50, "player", game,
function(sprite) {
sprites.forEach(function(sprite) {
if (sprite.id !== "box1" && player.collidesWith(sprite)) {
sprite.destroyed = true;
clearTimeout(sprite.selfDestruct);
sprite.el.fadeOut(100, function() {});
SCORE(sprite.options.PTS);
}
})
});
setInterval(spawnrand, 250);
$(document).keydown(function(e) {
if (e.keyCode == 37) {
player.left();
} else if (e.keyCode == 39) {
player.right();
} else if (e.keyCode == 38) {
player.up();
} else if (e.keyCode == 40) {
player.down();
}
});
});
</script>
</head>
<body onload="updateClock(); setInterval('updateClock()', 1000 )">
<span id="clock"> </span>
<header class="col-12 col-m-12">
<h1>Samla så mycket poäng du hinner genom att ta de gröna bollarna innan de försvinner</h1>
</header>
<div id="spelplan" class="col-6 col-m-6">
<div>
<p>Score:<span id="score"></span></p>
</div>
</div>
<section id="footer" class="col-12 col-m-12">
<h1>Använd piltangenterna för att styra den röda kuben </h1>
</section>
</body>
</html>
So again what I need help with is making the game-board "spelplan" responsive, any help is appreciated!