How do I make css offset smoother with Javascript? - javascript

I have a Player controller using the position attributes and javascript but it is kinda snappy. What do I do?
I tried making an infinite loop then adding a time out to slow it down to the client's computers frames but it just outputted the same result, snappy. Also, I wrote this in Atom and I compiled it on the Google Chrome Web Browser.
Javascript
var player = document.getElementById('Player');
var ctx = player.getContext("2d");
var playerXPos = 0;
var playerYPos = 0;
var playerSpeed = 5;
ctx.fillStyle = "Red";
ctx.fillRect(0,0,50,50);
function animate(key) {
if (key.keyCode == 39) { //Right Arrow
playerXPos += playerSpeed;
player.style.left = playerXPos + "px";
}
if (key.keyCode == 37) { //Left Arrow
playerXPos -= playerSpeed;
player.style.left = playerXPos + "px";
}
if (key.keyCode == 38) { //Up Arrow
playerYPos -= playerSpeed;
player.style.top = playerYPos + "px";
}
if (key.keyCode == 40) { //Down Arrow
playerYPos += playerSpeed;
player.style.top = playerYPos + "px";
}
else {
return false;
}
}
document.onkeydown = animate;
HTML part (lol html is not a programming language but whatever)
<!DOCTYPE html>
<html>
<head>
<title>Player Test</title>
<style>
#Player {
position: relative;
}
</style>
<body>
<canvas id="Player"></canvas>
<script src="App/playerController.js" type="text/javascript"></script>
</body>
</html>
I want it to be smooth. I think I should use linear algebra but I am not that advance in javascript. I am actually a beginner.

You can use the CSS transition property to get a smoother effect. You need to set the initial top and left positions of your element in your CSS since these are the properties that you are changing with your JS. I've set the animation to last 0.5s, but this can be adjusted to be faster or slower as you'd prefer:
var player = document.getElementById('Player');
var ctx = player.getContext("2d");
var playerXPos = 0;
var playerYPos = 0;
var playerSpeed = 5;
ctx.fillStyle = "Red";
ctx.fillRect(0, 0, 50, 50);
function animate(key) {
if (key.keyCode == 39) { //Right Arrow
playerXPos += playerSpeed;
player.style.left = playerXPos + "px";
}
if (key.keyCode == 37) { //Left Arrow
playerXPos -= playerSpeed;
player.style.left = playerXPos + "px";
}
if (key.keyCode == 38) { //Up Arrow
playerYPos -= playerSpeed;
player.style.top = playerYPos + "px";
}
if (key.keyCode == 40) { //Down Arrow
playerYPos += playerSpeed;
player.style.top = playerYPos + "px";
} else {
return false;
}
}
document.onkeydown = animate;
#Player {
position: relative;
left: 0;
top: 0;
-webkit-transition: all 0.5s;
/* For Safari 3.1 to 6.0 */
transition: all 0.5s;
}
<canvas id="Player"></canvas>

You could try this:
var player = document.getElementById('Player');
var ctx = player.getContext("2d");
var playerXPos = 0;
var playerYPos = 0;
var playerXSpeed = 0;
var playerYSpeed = 0;
ctx.fillStyle = "Red";
ctx.fillRect(0,0,50,50);
setInterval(function(){
playerXPos += playerXSpeed;
player.style.left = playerXPos + "px";
playerYPos += playerYSpeed;
player.style.top = playerYPos + "px";
},5)
function animate(event) {
let x = event.which || event.keyCode
switch (x) {
case 39://Right Arrow
playerXSpeed = 1
break
case 37://Left Arrow
playerXSpeed = -1
break
case 38://Up Arrow
playerYSpeed = -1;
break
case 40://Down Arrow
playerYSpeed = 1;
break
}
}
document.onkeydown = animate;
document.onkeyup = function(){
let x = event.which || event.keyCode
switch (x) {
case 39://Right Arrow
case 37://Left Arrow
playerXSpeed = 0
break
case 38://Up Arrow
case 40://Down Arrow
playerYSpeed = 0;
break
}
}

Related

How do I make an image move on keys up down left right?

I have watched at least 30 tutorials on how to make an image move up, down, left or right on the keys pressed, but not a single one was helpful to me.
I want to put in an image, and if you press the left or right key and it would move in that direction.
What is the shortest way to do this?
I know it's something with subtracting or adding the X axis, but how do I add the X and Y on a page so it can move?
is it something with keycode?
NOTE: Take care of -ve in left and top.
const image = document.querySelector(".image-continer");
document.addEventListener("keydown", (e) => {
const key = e.keyCode;
const cs = getComputedStyle(image);
const change = 10;
const regex = /[\d\.]*/;
const left = cs.left;
const top = cs.top;
const leftNumber = left.match(regex);
const topNumber = top.match(regex);
// LEFT key pressed
if (key === 37) {
image.style.left = `${parseFloat(leftNumber[0]) - change}px`;
}
// TOP key pressed
if (key === 38) {
image.style.top = `${parseFloat(topNumber[0]) - change}px`;
}
// RIGHT key pressed
if (key === 39) {
image.style.left = `${parseFloat(leftNumber[0]) + change}px`;
}
// DOWN key pressed
if (key === 40) {
image.style.top = `${parseFloat(topNumber[0]) + change}px`;
}
});
html,
body {
height: 100%;
margin: 0;
}
.image-continer {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<div class="image-continer">🙂</div>
This method allows move image diagonally.
let img = document.getElementById("myimage"),
w = img.offsetWidth/2,
h = img.offsetHeight/2,
x = img.offsetLeft,
y = img.offsetTop,
step = 10, //number of pixels to move
keys = [];
document.addEventListener("keydown", function(e)
{
let l=null, u=null;
if (keys.indexOf(e.key) == -1)
keys[keys.length] = e.key;
for(let i = 0; i < keys.length; i++)
{
let key = keys[i];
if (key == "ArrowLeft")
{
l += -step;
}
if (key == "ArrowRight")
{
l += step;
}
if (key == "ArrowUp")
{
u += -step;
}
if (key == "ArrowDown")
{
u += step;
}
}
if (l === null && u === null)
return;
e.preventDefault();
e.stopPropagation();
if (l !== null)
x += l;
if (u !== null)
y += u;
if (x < w)
x = w;
if (y < h)
y = h;
if (x > img.parentNode.offsetWidth - w)
x = img.parentNode.offsetWidth - w;
if (y > img.parentNode.offsetHeight - h)
y = img.parentNode.offsetHeight - h;
img.style.left = x + "px";
img.style.top = y + "px";
}, false);
document.addEventListener("keyup", function(e)
{
keys.splice(keys.indexOf(e.key), 1);
}, false);
body,
html
{
height: 100%;
}
img
{
top: 50%;
left: 50%;
position: absolute;
transform: translate(-50%,-50%);
transition: left 0.3s ease, top 0.3s ease;
box-shadow: 0 0 10px 2px lightblue;
}
<img id="myimage" src="https://lh3.googleusercontent.com/s1j_z7YCGft2EBNfnpXel8v02F8QkQKvp-_UjkR8SFaE5ciwPX9IugLMYvo_cCBzzuThRD7dVwwLO3H7XnvbD0JNnyVDmw_mPd8T5NH7yzQSSirZcA=w100">
Example with JQuery:
$(document).on('keydown', function(event) { // if a key is pressed...
if (event.which === 39) { // then if the key the right arrow key...
$('.image').animate({ // then animate it with JQuery...
left: `+=${$('.image').width() * 3}`
}, 'slow'); // and do it slowly
} else if (event.which === 37) { // otherwise if the key is the left arrow key...
$('.image').animate({ // then animate it with JQuery...
left: `-=${$('.image').width() * 3}`
}, 'slow'); // and do it slowly
} else if (event.which === 38) { // otherwise if it is the up arrow key...
$('.image').animate({ // then animate it with JQuery...
top: `-=${$('.image').width() * 3}`
}, 'slow'); // and do it slowly
} else if (event.which === 40) { // otherwise if it is the down arrow key...
$('.image').animate({ // then animate it with JQuery
top: `+=${$('.image').width() * 3}`
}, 'slow'); // and do it slowly
}
event.preventDefault();
});
I got the solution:
var x = 0;
var y = 0;
var keys = {};
image.style.left = (x) + "px";
image.style.top = (y) + "px";
document.addEventListener("keyup", (e) => {
keys[e.keyCode] = false;
});
document.addEventListener("keydown", (e) => {
keys[e.keyCode] = true;
if(keys[37] {
x += 5;
image.style.left = (x) + "px";
}
if(keys[39] {
x -= 5;
image.style.left = (x) + "px";
}
});

How can I change the position of an element when it is touched by another element in javascript?

I'm new to JavaScript and I'm trying to create a game just like this in javascript: http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/. Except I'm not allowed to use the canvas element so the code I use doesn't seem to work. The problem I'm having is getting my mouse/food element to move to a random new position when the snake/slither element collides with the mouse/food element. I'm also generally not sure if my update() function is working and if it isn't I don't know why.
I've tried a lot of different ways to get the code to execute correctly; placing the update function in different places like window onload,in each arrow function, etc. I tried sourcing many other codes but all I can find is people who use the canvas element to create their game.
var snake = null;
var slither = document.querySelector("#snake > .snake");
var mouse = document.querySelector("#food > .mouse");
var body = document.getElementById("grass");
x = body.width / 2;
y = body.height / 2;
function init() {
snake = document.getElementById("snake");
snake.style.position = 'relative';
snake.style.left = '0px';
snake.style.top = '0px';
}
function getKeyAndMove(e) {
var key_code = e.which || e.keyCode;
switch (key_code) {
case 37: //left arrow key
moveLeft();
break;
case 38: //Up arrow key
moveUp();
break;
case 39: //right arrow key
moveRight();
break;
case 40: //down arrow key
moveDown();
break;
}
}
function moveLeft() {
snake.style.left = parseInt(snake.style.left) - 7 + 'px';
update();
}
function moveUp() {
snake.style.top = parseInt(snake.style.top) - 7 + 'px';
update();
}
function moveRight() {
snake.style.left = parseInt(snake.style.left) + 7 + 'px';
update();
}
function moveDown() {
snake.style.top = parseInt(snake.style.top) + 7 + 'px';
update();
}
window.onload = init;
var update = () => {
if (
mouse.x === slither.x || mouse.y === slither.y || mouse.y === slither.y && mouse.x === slither.x
) {
mouse.x = Math.floor((Math.random() * 30) + 1);
mouse.y = Math.floor((Math.random() * 30) + 1);
}
};
<body id="grass" onkeydown='getKeyAndMove(event)'>
<div id="snake">
<img class="snake" src="img/snek.png" alt="snake">
</div>
<div id="food">
<img class="mouse" src="img/mouse.png" alt="mouse">
</div>
<script type="text/javascript" src="myscript.js"></script>
</body>
I need answers only in JavaScript please because I haven't learned JQuery and all that yet.
I think there could be a problem with my x and y values but I don't know how to set the position of the mouse to move to relative to the window like they do in the canvas element examples. I'm just confused, please help.
Your collision detection needs works because you are currently only checking whether the left and top sides intersect, but there are many more combinations.
Look at this answer and this for more
I also changed the selector to move the div that holds the mouse the same way that you had defined for your snake. I also set it to be position = 'relative'; so that it can move around. I added 'px' to the end of your random coord string
var snake = null;
var food = null;
var slither = document.querySelector("#snake > .snake");
var mouse = document.querySelector("#food > .mouse");
var body = document.getElementById("grass");
x = body.width / 2;
y = body.height / 2;
function init() {
snake = document.getElementById("snake");
snake.style.position = 'relative';
snake.style.left = '0px';
snake.style.top = '0px';
food = document.getElementById("food");
food.style.position = 'relative';
}
function getKeyAndMove(e) {
var key_code = e.which || e.keyCode;
switch (key_code) {
case 37: //left arrow key
moveLeft();
break;
case 38: //Up arrow key
moveUp();
break;
case 39: //right arrow key
moveRight();
break;
case 40: //down arrow key
moveDown();
break;
}
}
function moveLeft() {
snake.style.left = parseInt(snake.style.left) - 7 + 'px';
update();
}
function moveUp() {
snake.style.top = parseInt(snake.style.top) - 7 + 'px';
update();
}
function moveRight() {
snake.style.left = parseInt(snake.style.left) + 7 + 'px';
update();
}
function moveDown() {
snake.style.top = parseInt(snake.style.top) + 7 + 'px';
update();
}
window.onload = init;
var update = () => {
if (
mouse.x === slither.x || mouse.y === slither.y || mouse.y === slither.y && mouse.x === slither.x
) {
food.style.left = Math.floor((Math.random() * 30) + 1) + "px";
food.style.right = Math.floor((Math.random() * 30) + 1) + "px";
}
};
<body id="grass" onkeydown='getKeyAndMove(event)'>
<div id="snake">
<img class="snake" src="img/snek.png" alt="snake">
</div>
<div id="food">
<img class="mouse" src="img/mouse.png" alt="mouse">
</div>
<script type="text/javascript" src="myscript.js"></script>
</body>
This code is untested but may get you started...
function collisionCheck(elem1, elem2) {
var elem1Bounds = elem1.getBoundingClientRect();
var elem2Bounds = elem2.getBoundingClientRect();
var elem1Center = {
x: elem1Bounds.left + (elem1Bounds.width / 2),
y: elem1Bounds.top + (elem1Bounds.height / 2)
}
var elem2Center = {
x: elem2Bounds.left + (elem2Bounds.width / 2),
y: elem2Bounds.top + (elem2Bounds.height / 2)
}
// initialize if element 1 is within the viewport
if (
elem1Bounds.top >= 0 &&
elem1Bounds.left >= 0 &&
elem1Bounds.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
elem1Bounds.right <= (window.innerWidth || document.documentElement.clientWidth)
) {
// see https://stackoverflow.com/a/17628488/2116041
var distance = Math.sqrt(
Math.pow(elem1Bounds.x - elem2Bounds.x, 2) +
Math.pow(elem1Bounds.y - elem2Bounds.y, 2)
);
if (distance > elem1Bounds.width && distance > elem1Bounds.height) {
// no collision
return false;
} else {
// collision detected!
return true;
}
}
};
here's the answer I ended up with. I'm still tweaking some css stuff n all but this code does what I want it to :).
Also the positioning of the elements were the reason it wasn't staying in the window. I still have the rest of the code, this is just the important bits. Thanks for the help!
function init() {
snake = document.getElementById("snake");
snake.style.position = 'relative';
snake.style.left = '0px';
snake.style.top = '0px';
food = document.getElementById("food");
food.style.position = 'absolute';
}
function collisionCheck(slither, mouse) {
var snakeBounds = slither.getBoundingClientRect();
var mouseBounds = mouse.getBoundingClientRect();
if (!((snakeBounds.top + snakeBounds.height) < mouseBounds.top ||
snakeBounds.top > (mouseBounds.height + mouseBounds.top) ||
(snakeBounds.left + snakeBounds.width) < mouseBounds.left ||
snakeBounds.left > (mouseBounds.width + mouseBounds.left))) {
food.style.left = Math.floor(Math.random() * 800) + 'px';
food.style.top = Math.floor(Math.random() * 500) + 'px';
}
}

Move a div within another div with arrow keys

I am new in JavaScript, so I have some difficulties with it. I would like to move a small div within another bigger div with arrow keys - left, up, right and down. I have the code below but it does not work properly.
HTML and CSS
<div id="rectangle">
<div id="square"></div>
</div>
#rectangle {
width: 320px;
height: 200px;
border: 1px solid;
margin: auto;
position: relative;
}
#square {
width: 40px;
height: 40px;
background-color: deepskyblue;
position: absolute;
left: 0;
top:0;
}
Javascript
var rectangle = document.getElementById("rectangle");
var square = document.getElementById("square");
var currentPositionX = 0;
var currentPositionY = 0;
function moveSquare(event) {
if (event.keyCode == 37) {
currentPositionX -= 40;
square.style.left = currentPositionX + 'px';
if (currentPositionX <= 0) {
currentPositionX += 40;
}
}
if (event.keyCode == 38) {
currentPositionY -= 40;
square.style.top = currentPositionY + 'px';
if (currentPositionY <= 0) {
currentPositionY += 40;
}
}
if (event.keyCode == 39) {
currentPositionX += 40;
square.style.left = currentPositionX + 'px';
if (currentPositionX >= 280) {
currentPositionX -= 40;
}
}
if (event.keyCode == 40) {
currentPositionY += 40;
square.style.top = currentPositionY + 'px';
if (currentPositionY >= 160) {
currentPositionY -= 40;
}
}
}
document.onkeydown = moveSquare;
I have tested the code and found that when you are near the borders it's not working properly (Perhaps this was the original question?). On this i tested another simpler solution: I just changed your moveSquare function to only do work when you are inside your bounds (I mean, you shouldn't be always incrementing/decrementing position and then check if you are out of bounds to correct it).
function moveSquare(event) {
if (event.keyCode == 37) {
if (currentPositionX > 0) {
currentPositionX -= 40;
square.style.left = currentPositionX + 'px';
}
}
if (event.keyCode == 38) {
if (currentPositionY > 0) {
currentPositionY -= 40;
square.style.top = currentPositionY + 'px';
}
}
if (event.keyCode == 39) {
if (currentPositionX < 280) {
currentPositionX += 40;
square.style.left = currentPositionX + 'px';
}
}
if (event.keyCode == 40) {
if (currentPositionY < 160) {
currentPositionY += 40;
square.style.top = currentPositionY + 'px';
}
}
}
Here is the jsfiddle: https://jsfiddle.net/epL4a9Lq/
Please, next time be more specific on your error (i would comment this before answering but i have no reputation yet for that).
Hope this helps!

Wall detection on canvas JS

I made this script which moves a smaller div inside it's parent container, but I need it so that it doesn't go past the boundaries of the parent (represented by the 1px black line border). Could someone help me?
var guy = document.getElementById("guy");
var container = document.getElementById("container");
var guyLeft = 0;
var y = 0;
function anim(e) {
if (e.keyCode == 39) {
guyLeft += 2;
guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 37) {
guyLeft -= 2;
guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 40) {
y += 2;
guy.style.top = y + "px";
}
else if (e.keyCode == 38) {
y -= 2;
guy.style.top = y + "px";
}
}
document.onkeydown = anim;
#container {
height:300px;
width:300px;
outline: 2px solid black;
position:relative;
}
#guy {
position:absolute;
height:20px;
width:20px;
outline: 1px solid black;
background-color:red; left: 0;
}
<div id="container">
<div id="guy"></div>
</div>
You could use an IF statement to detect when the character is at the edge.
With your example your JavaScript would become:
var guy = document.getElementById("guy");
var container = document.getElementById("container");
var guyLeft = 0;
var y = 0;
function anim(e) {
if (e.keyCode == 39 && guyLeft <= 278) {
guyLeft += 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 37 && guyLeft >= 2) {
guyLeft -= 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 40 && y <= 278) {
y += 2; guy.style.top = y + "px";
}
else if (e.keyCode == 38 && y >= 2) {
y -= 2; guy.style.top = y + "px";
}
} document.onkeydown = anim;
Here's a working example:
var guy = document.getElementById("guy");
var container = document.getElementById("container");
var guyLeft = 0;
var y = 0;
function anim(e) {
if (e.keyCode == 39 && guyLeft <= 278) {
guyLeft += 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 37 && guyLeft >= 2) {
guyLeft -= 2; guy.style.left = guyLeft + "px";
}
else if (e.keyCode == 40 && y <= 278) {
y += 2; guy.style.top = y + "px";
}
else if (e.keyCode == 38 && y >= 2) {
y -= 2; guy.style.top = y + "px";
}
} document.onkeydown = anim;
#container {
height:300px;
width:300px;
outline: 2px solid black;
position:relative; }
#guy {
position:absolute;
height:20px;
width:20px;
outline: 1px solid black;
background-color:red; left: 0;
}
<div id="container"> <div id="guy"></div></div>

object moving on own in canvas

Sorry the code is so long. When the hero image is at most 32 pixels away from the mine or monster image, it should be transported back to the spawn point, which is 5 pixels on the x-axis, and 5 on the y axis. The hero image is being transported correctly, the alert is just not working. Thanks in advance for any ideas or suggestions.
<html>
<style>
</style>
<body background="background.jpg">
<canvas id="canvas" width="1300" height="630"></canvas>
<script>
var canvas=document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var H=canvas.height;
var W=canvas.width;
var x=10;
var y=15;
var rightPressed=false;
var leftPressed=false;
var upPressed=false;
var downPressed=false;
var heroX=20;
var monsterX=200;
var monsterY=200;
var heroY=20;
var dx= .68;
var dy= .76;
var score=0;
var monstersCaught=0;
var ballPX = 32 + (Math.random() * (canvas.width - 64));
var ballPY = 32 + (Math.random() * (canvas.height - 64));
var h=178;
var i=333;
var mineX=778;
var mineY=178;
Window.onload=dank();
function dank(){
alert("How to play: move your hero using the arrow keys, and collect colored balls for powerups and points!Get the highest score you can without touching a monster, which makes you start over!Collect the colored balls for more and better special powerups.");
}
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function draw(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
var heroImage=new Image();
heroImage.onload=function(){
ctx.drawImage(heroImage , heroX, heroY);
}
heroImage.src="hero.jpg";
dope();
checkMonster();
drawMines();
checkDeath();
}
function keyDownHandler(e) {
if(e.keyCode == 39) {
rightPressed = true;
}
else if(e.keyCode == 37) {
leftPressed = true;
}
else if(e.keyCode == 40) {
downPressed = true;
}
else if(e.keyCode == 38) {
upPressed = true;
}
}
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 37) {
leftPressed = false;
}
else if(e.keyCode == 40) {
downPressed = false;
}
else if(e.keyCode == 38) {
upPressed = false;
}
}
function dope(){
if(rightPressed) {
heroX += 7;
}
else if(leftPressed) {
heroX -= 7;
}
else if(upPressed){
heroY -= 7;
}
else if(downPressed){
heroY +=7;
}
}
function checkMonster(){
var monsterImage=new Image();
monsterImage.onload=function(){
ctx.drawImage(monsterImage, monsterX, monsterY)
}
monsterImage.src="monster.jpg";
monsterX += dx;
monsterY += dy;
if(monsterX>canvas.width || monsterX<0){
monsterX = -dx;
}
else if(monsterY>canvas.height || monsterY<0){
monsterY = -dy;
}
if (
heroX <= (monsterX + 32)
&& monsterX <= (heroX + 32)
&& heroY <= (monsterY + 32)
&& monsterY <= (heroY + 32)
) {
the alert that isn't working
alert("DEATH");
heroY=5;
heroX=5;
monsterX=100;
monsterY=100;
upPressed=false;
downPressed=false;
leftPressed=false;
rightPressed=false;
}
}
function drawMines(){
var rsz_mineImage=new Image();
rsz_mineImage.onload=function(){
ctx.drawImage(rsz_mineImage , mineX, mineY);
}
rsz_mineImage.src="rsz_mineimg.jpg";
if (
heroX <= (mineX + 32)
&& mineX <= (heroX + 32)
&& heroY <= (mineY + 32)
&& mineY <= (heroY + 32)
){
rightPressed=false;
leftPressed=false;
upPressed=false;
downPressed=false;
heroX=5;
heroY=5;
one of the alerts not working
alert("DEATH");
}
}
setInterval(draw, 10);
</script>
</body>
</html>
It's working for me. You had images loading in the animation loop which created a flickering effect. It's best to load your assets onto a canvas and when the images load place them on their canvas. This way you don't have to check if the image is loaded and can have a background color as a stand-in. Also running the animation in an interval loop isn't as efficient as using requestAnimationFrame. Also use preventDefault on the key input to prevent scrolling.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var H = canvas.height;
var W = canvas.width;
var x = 10;
var y = 15;
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
var heroX = 20;
var monsterX = 200;
var monsterY = 200;
var heroY = 20;
var dx = .68;
var dy = .76;
var score = 0;
var monstersCaught = 0;
var ballPX = 32 + (Math.random() * (canvas.width - 64));
var ballPY = 32 + (Math.random() * (canvas.height - 64));
var h = 178;
var i = 333;
var mineX = 778;
var mineY = 178;
Window.onload = dank();
function dank() {
alert("How to play: move your hero using the arrow keys, and collect colored balls for powerups and points!Get the highest score you can without touching a monster, which makes you start over!Collect the colored balls for more and better special powerups.");
}
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function loadImage(w,h,color,url) {
var can = document.createElement('canvas');
can.width = w;
can.height = h;
var ctx = can.getContext('2d');
ctx.fillStyle=color;
ctx.fillRect(0,0,w,h);
var img = document.createElement('image');
img.onLoad = function() {
ctx.clearRect(0,0,w,h);
ctx.drawImage(img, 0, 0);
};
img.src=url;
return can;
}
// load assets
var heroImage = loadImage(32,32,'#FF9900',"hero.jpg");
var monsterImage = loadImage(32,32,'purple',"monster.jpg");
var rsz_mineImage = loadImage(32,32,'#FF3300',"rsz_mineimg.jpg");
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(heroImage, heroX, heroY);
dope();
checkMonster();
drawMines();
//checkDeath();
requestAnimationFrame(draw);
}
function keyDownHandler(e) {
if (e.keyCode == 39) {
rightPressed = true;
} else if (e.keyCode == 37) {
leftPressed = true;
} else if (e.keyCode == 40) {
downPressed = true;
} else if (e.keyCode == 38) {
upPressed = true;
}
e.preventDefault();
}
function keyUpHandler(e) {
if (e.keyCode == 39) {
rightPressed = false;
} else if (e.keyCode == 37) {
leftPressed = false;
} else if (e.keyCode == 40) {
downPressed = false;
} else if (e.keyCode == 38) {
upPressed = false;
}
e.preventDefault();
}
function dope() {
if (rightPressed) {
heroX += 7;
} else if (leftPressed) {
heroX -= 7;
} else if (upPressed) {
heroY -= 7;
} else if (downPressed) {
heroY += 7;
}
}
function checkMonster() {
ctx.drawImage(monsterImage, monsterX, monsterY)
monsterX += dx;
monsterY += dy;
if (monsterX > canvas.width || monsterX < 0) {
monsterX = -dx;
} else if (monsterY > canvas.height || monsterY < 0) {
monsterY = -dy;
}
if (
heroX <= (monsterX + 32) && monsterX <= (heroX + 32) && heroY <= (monsterY + 32) && monsterY <= (heroY + 32)
) {
alert("DEATH");
heroY = 5;
heroX = 5;
monsterX = 100;
monsterY = 100;
upPressed = false;
downPressed = false;
leftPressed = false;
rightPressed = false;
}
}
function drawMines() {
ctx.drawImage(rsz_mineImage, mineX, mineY);
if (
heroX <= (mineX + 32) && mineX <= (heroX + 32) && heroY <= (mineY + 32) && mineY <= (heroY + 32)
) {
rightPressed = false;
leftPressed = false;
upPressed = false;
downPressed = false;
heroX = 5;
heroY = 5;
alert("DEATH");
}
}
draw();
#canvas {
width:100%;
background-color:#eff0de;
}
body {
background-color:#AADDFF;
}
<canvas id="canvas" width="1300" height="630"></canvas>

Categories

Resources