Please help, when I run my Window.onload()=dank(); function, I get the error message, unexpected token illegal.
<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 heroY=20;
//this is where the error is
Function not working correctly
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);
This is the main game function
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();
}
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;
}
}
setInterval(draw, 10);
</script>
</body>
</html>
Javascript strings cannot span multiple lines.
try this instead of "Window.onload()=dank();":
window.addEventListener('load',dank);
Shouldn't it be:
Window.onload=dank();
function dank(){
alert("How to play:");
}
I tried to execute the not working function but just came across an issue
On using Window.onload()=dank()
I am encountering
Window.onload is not a function
So I changed it to Window.onload=dank() and it is working. Also as pointed out in previous answer javascript cannot span multiple lines. But you can change the alert text to this
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.")
WORKING MODEL
Related
I am trying to make a 2D platforming game and I am missing an essential part of it, gravity.
I have tried everything from look at questions on this website to looking at online tutorials and you-tube videos.
I really need help with getting gravity into this game as I am out of ideas.
As I said I have already tried looking at multiple tutorials and videos, including this one:
http://www.somethinghitme.com/2013/01/09/creating-a-canvas-platformer-tutorial-part-one/
but this one uses shapes created in canvas rather than images.
I already know that you have to use a velocity function as well as variable for the gravity. Then you have to put this all inside the key handler function so that it can get executed.
//spaceman variables
var sx = canvasWidth / 2; // start the spaceman in the centre
var sy = canvasHeight / 2;
var sdx = 0; // set initial speed to 0
var sdy = 0;
var sspeed = 3; // create a variable for speed
var gravity = 0.2;
var svX = 0;
var svY = (Math.random() * -10) - 5;
//set variables to use for key presses
//these are Boolean variables
//they can only be true or false
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
function keyDownHandler(e) {
if (e.keyCode == 39) {
rightPressed = true;
} else if (e.keyCode == 37) {
spaceman2Ready = true;
spacemanReady = false;
leftPressed = true;
} else if (e.keyCode == 38) {
upPressed = true;
} else if (e.keyCode == 40) {
downPressed = true;
}
}
function keyUpHandler(e) {
if (e.keyCode == 39) {
rightPressed = false;
sdx--;
} else if (e.keyCode == 37) {
spaceman2Ready = false;
spacemanReady = true;
leftPressed = false;
sdx--;
} else if (e.keyCode == 38) {
upPressed = false;
sdx--;
} else if (e.keyCode == 40) {
downPressed = false;
sdx--;
}
}
// add something to "listen" for an event
//an event is keypress, mouse movement, mouse click etc.
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (rightPressed == true) {
sdx = sspeed;
} else if (leftPressed == true) {
sdx = -sspeed;
} else if (upPressed == true) {
sdy = -sspeed;
} else if (downPressed == true) {
sdy = sspeed
}
if (rightPressed == false && leftPressed == false && upPressed == false && downPressed == false) {
sdx = 0;
sdy = 0;
}
sx = sx + sdx;
sy = sy + sdy;
}
if (spacemanReady) {
ctx.drawImage(spacemanImage, sx, sy);
if (spaceman2Ready) {
ctx.drawImage(spaceman2Image, sx, sy);
}
// basically the setTimeout part, but this time its requesting the function that we made at the top
requestAnimationFrame(draw);
}
// this is to get the loop for the animation to start going
window.addEventListener("load",
function() {
draw();
});
< /script>
</body >
</html>/
You should be using gravity to update your position every frame (in the draw function). This would look like:
if(sy > 0){
sdy += gravity
}
I have created a codepen with your game with gravity. I hope this helps!
The code works in the following way:
- holding shoot/drop button generate bullet and the bomb that is drawn/shown in canvas,
- it executes all the time in the function draw that refreshes around 60times per second.
Instead I want to set sth as:
- setInterval(shoot, 1000);
- setInterval(drop, 2000);
so it should be like:
- when user presses the key, it creates the bullet/bomb with the interval of 1/2 seconds
- it should all happen without realising the key
Below I provide the sample code:
let left = false;
let up = false;
let right = false;
let down = false;
let shoot = false;
let drop = false;
document.onkeydown = function (e) {
if (e.keyCode == 37) left = true;
if (e.keyCode == 38) up = true;
if (e.keyCode == 39) right = true;
if (e.keyCode == 40) down = true;
if (e.keyCode == 17) shoot = true;
if (e.keyCode == 32) drop = true;
e.preventDefault();
}
document.onkeyup = function (e) {
if (e.keyCode == 37) left = false;
if (e.keyCode == 38) up = false;
if (e.keyCode == 39) right = false;
if (e.keyCode == 40) down = false;
if (e.keyCode == 17) shoot = false;
if (e.keyCode == 32) drop = false;
e.preventDefault();
}
function draw() {
requestAnimationFrame(draw);
if (shoot) {
bullet = new Bullet(player.x - 3, player.y - 3, 6, 10)
bullets.push(bullet);
}
for (i = 0; i < bullets.length; i++) {
bullets[i].show();
bullets[i].move();
}
if (drop) {
bomb = new Bomb(player.x - 8, player.y + 50, 16, 1)
bombs.push(bomb);
}
for (i = 0; i < bombs.length; i++) {
bombs[i].show();
bombs[i].move();
}
}
requestAnimationFrame(draw);
Full code on remote server:
https://stacho163.000webhostapp.com
Is that a way to do it in my code or i have to change the way the buttons work?
If there is a solution without jQuery, that would be great.
e: checked the first tip, but after creating the first single bullet/bomb it's working as it was before.
Thank you for your tips :)
You should set some sort of wait variable, that indicates that the key is currently pressed, and no processing needs to take place:
let dropping = false;
// indicates that the bomb is dropping right now. Do not drop a new bomb
//...
if (e.keyCode == 32) {
drop = true;
dropping = true;
setTimeout(function () { dropping = false; }, 1000);
// if 1 second has passed, reset the dropping variable, to allow another bomb to drop
}
//...
if (drop && !dropping) {
bomb = new Bomb(player.x - 8, player.y + 50, 16, 1)
bombs.push(bomb);
}
This way, your bomb will only drop once every 1 second. Rinse and repeat :)
I am creating a Canvas game of 'Snake'. Using your arrow keys, you can move the snake around.
What I'm working on is clearing an interval when a different arrow key is pressed. I am trying to make use of both setInterval and clearInterval. Here is one of the four such functions I have.
https://jsfiddle.net/2q1svfod/2/
function moveUp() {
if (direction != "up") {
incrementScore();
}
direction = "up";
if (direction == "up") {
var goUp = setInterval(function() {
ctx.lineTo(headX, headY - 10);
ctx.stroke();
headY -= 10;
}, 1000);
}
else {
clearInterval(goUp);
}
}
The objective is to avoid crashing into the walls, which will result in losing the game, and your score will be reset. I'd like to prevent players from repeatedly tapping on a key to get extra points, so I only increase their score once per direction.
As long as the direction stays the same, I want the interval to keep running. That's why I declared the goUp interval inside this conditional.
If the direction has changed, I clear that interval. However, two intervals are now going on at the same time instead of 1.
Does anyone know where I'm going wrong here?
This is one implementation (out of many) you might consider.
var currentInput = {
left: false,
up: false,
right: false,
down: false
};
function getKey(keyCode) {
if (keyCode === 37) {
return 'left';
} else if (keyCode === 38) {
return 'up';
} else if (keyCode === 39) {
return 'right';
} else if (keyCode === 40) {
return 'down';
}
}
function onKeyDown(event) {
var key = getKey(event.keyCode);
currentInput[key] = true;
}
function onKeyUp(event) {
var key = getKey(event.keyCode);
currentInput[key] = false;
}
document.addEventListener('keydown', onKeyDown, false)
document.addEventListener('keyup', onKeyUp, false)
function update() {
requestAnimationFrame(update);
if (currentInput.left) {
// move snake left
} else if (currentInput.right) {
// etc.
}
}
// Kick off the event loop
requestAnimationFrame(update);
I managed to find a solution, but I'm not too thrilled I had to resort to using global variables.
It looks something like this
function moveUp() {
if (direction != "up") {
incrementScore();
}
direction = "up";
clearInterval(goRight);
upArrow();
}
function upArrow() {
if (direction == "up") {
goUp = setInterval(function() {
ctx.lineTo(headX, headY - 10);
ctx.stroke();
headY -= 10;
}, 1000);
}
}
It works and I'm able to change directions. But I don't like using globals.
Here's the updated fiddle
https://jsfiddle.net/2q1svfod/6/
So I have a game, and Im trying to keep it from starting unless the user pressed the Enter key.
This is the code I have for that:
var code = (e.keyCode ? e.keyCode : e.which);
var enterpressed = 0;
do {
if(code == 13) { //Enter keycode
enterpressed = 13;
}
ctx.font = "25px Helvetica";
drawStartScreen();
update();
} while (enterpressed === 13);
This is the full program, on JSfiddle:
http://jsfiddle.net/3aoozxte/6/
Edit: I figured it out!
Here is the program working:
http://jsfiddle.net/84c2k5kg/6/
Here is the solution to your problem.
I added the enter key logic to your keydown eventlistener. So when you press enter it starts the game.
I deleted the loop in startGameScreen() to prevent the browser crashing repeating this infinite loop.
http://jsfiddle.net/3aoozxte/19/
function main() {
canvas = document.createElement("canvas");
canvas.width = COLS*20;
canvas.height = ROWS*20;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
ctx.font = "12px Helvetica";
frames = 0;
keystate = {};
started = false;
// keeps track of the keyboard input
document.addEventListener("keydown", function(evt) {
keystate[evt.keyCode] = true;
if(keystate[Key_ENTER] && !started) { // Start the game if it's not started and Enter is pressed.
started = true;
init();
loop();
}
});
document.addEventListener("keyup", function(evt) {
delete keystate[evt.keyCode];
});
//Attempting to create a welcome screen
startGameScreen();
}
function startGameScreen() {
ctx.font = "25px Helvetica";
drawStartScreen();
}
This might be the one you are looking for.
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.ctrlKey && evt.keyCode == 90) {
alert("Ctrl-Z was pressed");
}
else {
var kc = evt.keyCode
switch(kc){
case 13 : alert("Enter was pressed"); break
case 37 : alert("Left Key was pressed"); break
case 38 : alert("Up Key was pressed"); break
case 39 : alert("Right Key was pressed"); break
case 40 : alert("Down Key was pressed"); break
// default : alert(kc + " was pressed");//used to check for key value
}
}
};
Fiddle Key Events
Adding the function on your listener..
document.onkeydown = function(evt) {
if (evt.keyCode == 13) {
started = true;
init();
loop();
}
}
Updated and working Game
Complete reference Complete Handling Key Events
I prefer using jquery
$(document).keypress(function(e)
{
if (e.which == 13)
{
//Your code
}
});
I feel like a complete klutz, I had this working and then I accidentally forgot to save it! I'm an idiot. I've spent the last day trying to recreate what I had but I can't do it. Basically (from my last save) I had this:
function canvasMove(e) {
if(!e) var e = window.event;
var downcheck;
var upcheck;
var leftcheck;
var rightcheck;
if(e.keyCode == '38') {
if(up + down == 0) downcheck = false;
else downcheck = true;
e.preventDefault();
}
if(e.keyCode == '40') {
if(up + down > HEIGHT - 110) upcheck = false;
else upcheck = true;
e.preventDefault();
}
if(e.keyCode == '37') {
if(left + right == 0) rightcheck = false;
else rightcheck = true;
e.preventDefault();
}
if(e.keyCode == "39") {
if(left + right > WIDTH - 110) leftcheck = false;
else leftcheck = true;
e.preventDefault();
}
if(leftcheck == true) { left += 10; counting() };
if(rightcheck == true) { right -= 10; counting() };
if(upcheck == true) { up += 10; counting(true) };
if(downcheck == true) { down -= 10; counting(true) };
}
The problem of course being that Javascrpt doesn't support the ability to check if two keys are being pressed at the same time. What I want to accomplish is when the user pressed up and left they'll move diagonally. Ignore the "counting" function, it's just to keep track of how much the user has moved.
I managed to accomplish this with just else and if statements, no less! So I was wondering if you guys could give it a shot. The first if statement in each key if statement is so the user can't leave the canvas box. Then I have a function that moves the user by redrawing the canvas.
function redraw() {
clear(draw);
draw.fillStyle = 'rgba(0,0,0,0.5)';
draw.fillRect(left + right, up + down, '100', '100');
}
The "clear" function is just a simple function that clears the entire canvas. This is all controlled by an init function that looks like this:
function init() {
canvas = document.getElementById('game');
HEIGHT = canvas.height;
WIDTH = canvas.width;
draw = canvas.getContext('2d');
setInterval(redraw, 30);
document.onkeydown = canvasMove;
}
Your -check flags need to be global variables rather than function-scoped variables, otherwise they will never stay set between keydown events (handling only one key at a time). You also need a keyup event handler that will unset the correct flag when a key is released.