I'm having a few issues with my code. Can't get my cube to jump. Take a look at my code and let me know if you can help please.
My left, right and duck abilities all currently work at desired level, but I cannot get my cube to jump. I've been trying for three days and can't find anything online. My javascript is embedded within a tag in a html page.
var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
var coinRad = 8;
var coinX = 40;
var coinY = 80;
var x = 20;
var y = 510;
var w = 30;
var h = 50;
var rightPressed = false;
var leftPressed = false;
var ducked = false;
var jumping = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.keyCode == 39) {
rightPressed = true;
} else if (e.keyCode == 37) {
leftPressed = true;
} else if (e.keyCode == 40) {
ducked = true;
} else if (e.keycode == 32) {
jumping = true;
}
}
function keyUpHandler(e) {
if (e.keyCode == 39) {
rightPressed = false;
} else if (e.keyCode == 37) {
leftPressed = false;
} else if (e.keyCode == 40) {
ducked = false;
} else if (e.keycode == 32) {
jumping = false;
}
}
function drawCube() {
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.fillStyle = "Green";
ctx.fill();
ctx.closePath();
}
function run() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (leftPressed) {
if (x > 0) {
x -= 2.5;
}
} else if (rightPressed) {
if (x < canvas.width - w) {
x += 2.5;
}
}
if (jumping) {
y -= 10;
h -= 10;
}
if (ducked) {
y = 535;
h = 25;
} else {
y = 510;
h = 50;
}
drawCube();
}
setInterval(run, 10);
<canvas id="gameCanvas"></canvas>
Additionally, your keyCode check is improperly capitalized for the jumping condition.
else if (e.keyCode == 40) {
ducked = false;
} else if (e.keycode == 32) { //should be keyCode
jumping = false;
}
because when the run method end, you do this.
if (jumping) {
y -= 10;
h -= 10;
}
if (ducked) {
y = 535;
h = 25;
} else {
y = 510;
h = 50;
}
even if you change the values from Y and H, their values always change to 510 and 50 respectively, because the else in ducked condition.
Remove this else or find another logic to do the same
Related
I have this working fiddle http://jsfiddle.net/Sk8erPeter/b5sxk/1/
What i want is to make a grid lets say 3x3
Lets consider i m in scector B2.
The question is how could i move to any other sector knowing where i m?
A1 A2 A3
B1 B2 B3
C1 C2 C3
Goal is to be able to walk from one sector to other! Any help?
Code now:
<style>
canvas {
display:block;
margin:auto;
border:1px dashed black;
}
</style>
<canvas id="canvas" width="500" height="400"></canvas>
<script>
(function (d, w) {
var context;
var rightKey = false;
var leftKey = false;
var upKey = false;
var downKey = false;
var block_x;
var block_y;
var block_h = 30;
var block_w = 30;
function init() {
var canvas = d.getElementById('canvas');
var canvasTextRectangle = canvas.getBoundingClientRect();
context = canvas.getContext('2d');
WIDTH = canvasTextRectangle.width;
HEIGHT = canvasTextRectangle.height;
block_x = WIDTH / 2 - 15;
block_y = HEIGHT / 2 - 15;
setInterval(draw, 25);
}
function clearCanvas() {
context.clearRect(0, 0, WIDTH, HEIGHT);
}
function draw() {
clearCanvas();
if (rightKey) block_x += 5;
else if (leftKey) block_x -= 5;
if (upKey) block_y -= 5;
else if (downKey) block_y += 5;
if (block_x <= 0) block_x = 0;
if ((block_x + block_w) >= WIDTH) block_x = WIDTH - block_w;
if (block_y <= 0) block_y = 0;
if ((block_y + block_h) >= HEIGHT) block_y = HEIGHT - block_h;
context.fillRect(block_x, block_y, block_w, block_h);
}
function onKeyDown(evt) {
if (evt.keyCode == 39) rightKey = true;
else if (evt.keyCode == 37) leftKey = true;
if (evt.keyCode == 38) upKey = true;
else if (evt.keyCode == 40) downKey = true;
evt.preventDefault();
evt.stopPropagation();
}
function onKeyUp(evt) {
if (evt.keyCode == 39) rightKey = false;
else if (evt.keyCode == 37) leftKey = false;
if (evt.keyCode == 38) upKey = false;
else if (evt.keyCode == 40) downKey = false;
evt.preventDefault();
evt.stopPropagation();
}
w.addEventListener("load", init, false);
w.addEventListener("keydown", onKeyDown, false);
w.addEventListener("keyup", onKeyUp, false);
})(document, window);
</script>
If I understand the question correctly, you want the block to jump between sections at the border.
Here's what I would do:
Create an array of sections and specify the number of columns and rows (in your case 9 sections in a 3x3 grid)
Create an index that marks the section the block is currently in
In your edge detection, check if there is an adjacent section
If there is an adjacent section, update the section index and move the block to the opposite end
If there isn't (e.g. you're on row 0 and moving up), ensure the block sticks to the edge (current implementation you already have)
Here's a working example:
(function (d, w) {
var context;
var rightKey = false;
var leftKey = false;
var upKey = false;
var downKey = false;
var block_x;
var block_y;
var block_h = 20;
var block_w = 20;
const sect_rows = 3;
const sect_cols = 3;
const sections = [
"A1", "A2", "A3",
"B1", "B2", "B3",
"C1", "C2", "C3"];
let sectionIndex = 4;
function init() {
var canvas = d.getElementById('canvas');
var canvasTextRectangle = canvas.getBoundingClientRect();
context = canvas.getContext('2d');
WIDTH = canvasTextRectangle.width;
HEIGHT = canvasTextRectangle.height;
block_x = WIDTH / 2 - 15;
block_y = HEIGHT / 2 - 15;
setInterval(draw, 25);
}
function clearCanvas() {
context.clearRect(0, 0, WIDTH, HEIGHT);
}
function draw() {
clearCanvas();
// Move player
if (rightKey) block_x += 5;
else if (leftKey) block_x -= 5;
if (upKey) block_y -= 5;
else if (downKey) block_y += 5;
// Edge detection
if (block_x <= 0) {
const hasSectionToLeft = sectionIndex % sect_rows !== 0;
if (hasSectionToLeft) {
sectionIndex -= 1;
block_x = WIDTH - block_w - 1;
} else {
block_x = 0;
}
} else if ((block_x + block_w) >= WIDTH) {
const hasSectionToRight = sectionIndex % sect_rows !== (sect_rows - 1);
if (hasSectionToRight) {
sectionIndex += 1;
block_x = 1;
} else {
block_x = WIDTH - block_w;
}
}
if (block_y <= 0) {
const hasSectionAbove = sectionIndex >= sect_cols;
if (hasSectionAbove) {
sectionIndex -= sect_cols;
block_y = HEIGHT - block_h - 1;
} else {
block_y = 0;
}
} else if ((block_y + block_h) >= HEIGHT) {
const hasSectionBelow = sectionIndex < sections.length - sect_rows;
if (hasSectionBelow) {
sectionIndex += sect_cols;
block_y = 1;
} else {
block_y = HEIGHT - block_h;
}
}
// Draw section
context.font = '48px sans-serif';
context.fillText(sections[sectionIndex], 10, 50);
// Draw player
context.fillRect(block_x, block_y, block_w, block_h);
}
function onKeyDown(evt) {
if (evt.keyCode == 39) rightKey = true;
else if (evt.keyCode == 37) leftKey = true;
if (evt.keyCode == 38) upKey = true;
else if (evt.keyCode == 40) downKey = true;
evt.preventDefault();
evt.stopPropagation();
}
function onKeyUp(evt) {
if (evt.keyCode == 39) rightKey = false;
else if (evt.keyCode == 37) leftKey = false;
if (evt.keyCode == 38) upKey = false;
else if (evt.keyCode == 40) downKey = false;
evt.preventDefault();
evt.stopPropagation();
}
w.addEventListener("load", init, false);
w.addEventListener("keydown", onKeyDown, false);
w.addEventListener("keyup", onKeyUp, false);
})(document, window);
// ********************************
canvas { border: 1px solid red; }
<canvas id="canvas" width="200" height="200"></canvas>
const cellSize = 30; // grid resolution
(function (d, w) {
var context;
var rightKey = false;
var leftKey = false;
var upKey = false;
var downKey = false;
var block_h = 30;
var block_w = 30;
// Remember what this x and y now is grid x y, not in pixels!
var block_x;
var block_y;
function init() {
var canvas = d.getElementById('canvas');
var canvasTextRectangle = canvas.getBoundingClientRect();
context = canvas.getContext('2d');
WIDTH = canvasTextRectangle.width;
HEIGHT = canvasTextRectangle.height;
// Find center cell..
block_x = (WIDTH / 2 - block_w / 2) / cellSize >>> 0;
block_y = (HEIGHT / 2 - block_h / 2) / cellSize >>> 0;
setInterval(draw, 75);
}
function clearCanvas() {
context.clearRect(0, 0, WIDTH, HEIGHT);
}
function drawGrid(){
for(let i = 0; i < canvas.width; i+=cellSize){
context.fillRect(i, 0, 1, canvas.height);
}
for(let i = 0; i < canvas.height; i+=cellSize){
context.fillRect(0, i, canvas.width, 1);
}
}
function draw() {
clearCanvas();
drawGrid();
// Since block x and y is grid position, not pixels
// we have to move it for one cell per step
if (rightKey) {
block_x += 1;
}else if (leftKey) {
block_x -= 1;
}
if (upKey) {
block_y -= 1;
}
else if (downKey) {
block_y += 1;
}
if (block_x <= 0) block_x = 0;
if (block_y <= 0) block_y = 0;
// Here you see, how to find last _full_ cell on right and bottom sides of grid
if ((block_x + 1) * cellSize >= WIDTH) block_x = (WIDTH - block_w) / cellSize >>> 0;
if ((block_y + 1)* cellSize >= HEIGHT) block_y = (HEIGHT - block_h) / cellSize >>> 0;
// calculating pixel position is easy:
context.fillRect(block_x * cellSize, block_y * cellSize, block_w, block_h);
}
function onKeyDown(evt) {
if (evt.keyCode == 39) rightKey = true;
else if (evt.keyCode == 37) leftKey = true;
if (evt.keyCode == 38) upKey = true;
else if (evt.keyCode == 40) downKey = true;
evt.preventDefault();
evt.stopPropagation();
}
function onKeyUp(evt) {
if (evt.keyCode == 39) rightKey = false;
else if (evt.keyCode == 37) leftKey = false;
if (evt.keyCode == 38) upKey = false;
else if (evt.keyCode == 40) downKey = false;
evt.preventDefault();
evt.stopPropagation();
}
w.addEventListener("load", init, false);
w.addEventListener("keydown", onKeyDown, false);
w.addEventListener("keyup", onKeyUp, false);
})(document, window);
canvas {
display:block;
margin:auto;
border:1px dashed black;
}
<canvas id="canvas" width="500" height="400"></canvas>
I am writing a game in javascript for the first time most of my code is not efficient. I am stuck on how to code a jumping method for my cube(the character for my game). The jump works but the player can double jump. The double jump occurs on the way down if the user presses the jump key again. I have tried setting a variable which will be modified when the player is on the ground and if it is true then your only allowed to jump but it hasn't worked. Here is the code:
//setting screen up
const canvas = document.getElementById('canvas');
const c = canvas.getContext('2d');
canvas.width = innerWidth;
canvas.height = innerHeight;
//ground
gHeight = canvas.height/1.3
function ground(){
c.fillStyle = 'white';
c.fillRect(0,gHeight,canvas.width,canvas.height-gHeight);
}
//player
class Player{
constructor(x,y,w,h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.color = 'rgb(92,168,255)';
this.l = false;
this.r = false;
this.speed = 10
this.hp = 100;
this.jump = false;
this.jumpC = 0;
}
draw(){
c.fillStyle = this.color;
c.fillRect(this.x,this.y,this.w,this.h);
}
update(){
this.draw();
//gravity
if(this.y < gHeight - this.h){
this.y += 5;
}
//movement
if(this.l == true){
this.x -= this.speed;
}
if(this.r == true){
this.x += this.speed;
}
//jump
if(this.jump == true){
this.y -= 10;
this.jumpC += 5;
}
if (this.jumpC >= 100){
this.jump = false;
this.jumpC = 0;
}
}
}
var player = new Player(100, 100,50,50);
//main loop
var animationId;
function animate(){
c.fillStyle = 'rgba(0,0,0,0.7)';
c.fillRect(0,0, canvas.width, canvas.height);
animationId = requestAnimationFrame(animate);
//drawing the ground
ground();
//drawing the player
player.update();
//ending game
if(player.hp == 0){
cancelAnimationFrame(animationId);
}
}
//keypress
addEventListener('keydown', (event)=>{
if(event.keyCode == 37) {
player.l = true;
}
if(event.keyCode == 39) {
player.r = true;
}
if(event.keyCode == 38 && player.jump == false){
player.jump = true;
}
});
//keyup
addEventListener('keyup', (event)=>{
if(event.keyCode == 37 ) {
player.l = false;
}
if(event.keyCode == 39) {
player.r = false;
}
});
animate();
tell me if more info is needed
After the jump make it impossible to jump until the player reaches the ground.
if(event.keyCode == 38 && player.jump == false){ player.jump = true; }
I would add another comparison in this if like this:
if(event.keyCode == 38 && player.jump == false && player.isOnGround()){ player.jump = true; }
To check if the user landed
I created a ball and some Javascript code that is supposed to make it move. But my code isn't working and I don't know why. Could someone please look over my code and help me out.
Code
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var xPos = canvas.width/2;
var yPos = canvas.height-30;
var ballRadius = 10;
var leftPressed = false;
var rightPressed = false;
var upPressed = false;
var downPressed = false;
function drawBall() {
ctx.beginPath();
ctx.arc(xPos, yPos, ballRadius, 0, Math.PI*2, false);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
}
setInterval(draw, 10);
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 37) {
leftPressed = true;
}
else if(e.keyCode == 39) {
rightPressed = true;
}
else if(e.keyCode == 38) {
upPressed == true;
}
else if(e.keyCode == 40) {
downPressed = true;
}
}
function keyUpHandler(e) {
if(e.keyCode == 37) {
leftPressed = false;
}
else if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 38) {
upPressed == false;
}
else if(e.keyCode == 40) {
downPressed = false;
}
}
if(leftPressed = true) {
xPos -= 7;
} else if(rightPressed = true) {
xPos += 7;
} else if(upPressed = true) {
yPos -= 7;
} else if(downPressed = true) {
yPos += 7;
}
* { padding: 0; margin: 0; }
canvas { background: #eee; display: block; margin: 0 auto; }
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Breakout</title>
<style>
* { padding: 0; margin: 0; }
canvas { background: #eee; display: block; margin: 0 auto; }
</style>
</head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
<script src="gameJS.js"></script>
</body>
</html>
You're only updating the boolean values during keypress. You're not updating the position dynamically. Your position update code runs first during load and that's it.
To move during keypress, you need to update the position during each keypress and you need to draw the ball.
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var xPos = canvas.width/2;
var yPos = canvas.height-30;
var ballRadius = 10;
var leftPressed = false;
var rightPressed = false;
var upPressed = false;
var downPressed = false;
function drawBall() {
ctx.beginPath();
ctx.arc(xPos, yPos, ballRadius, 0, Math.PI*2, false);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
}
setInterval(draw, 10);
document.addEventListener("keydown", keyDownHandler, false);
//document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 37) {
xPos -= 7;
//draw the ball with new position
}
else if(e.keyCode == 39) {
xPos += 7;
//draw the ball with new position
}
else if(e.keyCode == 38) {
yPos -= 7;
//draw the ball with new position
}
else if(e.keyCode == 40) {
yPos += 7;
//draw the ball with new position
}
}
* { padding: 0; margin: 0; }
canvas { background: #eee; display: block; margin: 0 auto; }
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Breakout</title>
<style>
* { padding: 0; margin: 0; }
canvas { background: #eee; display: block; margin: 0 auto; }
</style>
</head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
<script src="gameJS.js"></script>
</body>
</html>
You are using assignment operators (single equal signs) in your check for keypresses, rather than comparator operators (double equal signs). Essentially, you're saying that they should equal true, rather than checking if they are true:
if (leftPressed = true) {}
else if (rightPressed = true) {}
else if (upPressed = true) {}
else if (downPressed = true) {}
These should be written as:
if (leftPressed == true) {}
else if (rightPressed == true) {}
else if (upPressed == true) {}
else if (downPressed == true) {}
Having said that, you don't need to make use of these four variables at all, and can instead simply modify the positions directly on checking against the keyCode values:
if (e.keyCode == 37) {
xPos -= 7;
}
Hope this helps! :)
There are a few errors in your code.
In your up/down key handlers you compare the value of upPressed instead of setting it.
e.g.
upPressed == true;
should be
upPressed = true;
In your if conditions at the end, you set the value instead of comparing.
e.g.
if(leftPressed = true)
should be
if(leftPressed)
I've moved the ball position code into the moveBall function and called that when the key handler is called so that the position is updated on key press.
This is the fixed version.
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var xPos = canvas.width / 2;
var yPos = canvas.height - 30;
var ballRadius = 10;
var leftPressed = false;
var rightPressed = false;
var upPressed = false;
var downPressed = false;
function drawBall() {
ctx.beginPath();
ctx.arc(xPos, yPos, ballRadius, 0, Math.PI * 2, false);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
}
setInterval(draw, 10);
document.addEventListener("keydown", keyDownHandler, false);
function keyDownHandler(e) {
leftPressed = false;
rightPressed = false;
upPressed = false;
downPressed = false;
if (e.keyCode == 37) {
leftPressed = true;
} else if (e.keyCode == 39) {
rightPressed = true;
} else if (e.keyCode == 38) {
upPressed = true;
} else if (e.keyCode == 40) {
downPressed = true;
}
moveBall();
}
function moveBall() {
if (leftPressed) {
xPos -= 7;
} else if (rightPressed) {
xPos += 7;
} else if (upPressed) {
yPos -= 7;
} else if (downPressed) {
yPos += 7;
}
}
* {
padding: 0;
margin: 0;
}
canvas {
background: #eee;
display: block;
margin: 0 auto;
}
<canvas id="myCanvas" width="480" height="320"></canvas>
Since keyDownHandler is called whenever a keydown event occurs, you'll want to move your position variables updating code to within that function, and you can remove the keyDownHandler as it doesn't do anything in this example:
function keyDownHandler(e) {
//left
if(e.keyCode === 37){
xPos -= 7
}
//right
else if (e.keyCode === 39) {
xPos += 7
}
//up
else if (e.keyCode === 38) {
yPos -= 7
}
//down
else if (e.keyCode === 40) {
yPos += 7
}
}
In addition, you can make your code slightly more readable with a switch statement rather than cascading else if
function keyDownHandler(e) {
switch(e.keyCode){
case 37: //left
xPos -= 7
break;
case 39: //right
xPos += 7
break;
case 38: //up
yPos -= 7
break;
case 40: //down
yPos += 7
break;
}
}
Note: as Obsidian Age correctly pointed out, you are using assignment operators and not comparison operators in your update code, so you might want to double check that in the future. In my example I used the triple equal === operator because it checks both type and value, which is recommended in JavaScript. See W3Schools reference for JavaScript Operators
Just update your javascript as below will do the trick.
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var xPos = canvas.width/2;
var yPos = canvas.height-30;
var ballRadius = 20;
var leftPressed = false;
var rightPressed = false;
var upPressed = false;
var downPressed = false;
function drawBall() {
ctx.beginPath();
ctx.arc(xPos, yPos, ballRadius, 0, Math.PI*2, false);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if(leftPressed == true) {
xPos -= 7;
}
else if(rightPressed == true) {
xPos += 7;
}
else if(upPressed == true) {
yPos -= 7;
}
else if(downPressed == true) {
yPos += 7;
}
drawBall();
}
function keyDownHandler(e) {
var keyCode = e.keyCode;
if(keyCode == 37) {
leftPressed = true;
}
else if(keyCode == 39) {
rightPressed = true;
}
else if(keyCode == 38) {
upPressed = true;
}
else if(keyCode == 40) {
downPressed = true;
}
}
function keyUpHandler(e) {
var keyCode = e.keyCode;
if(keyCode == 37) {
leftPressed = false;
}
else if(keyCode == 39) {
rightPressed = false;
}
else if(keyCode == 38) {
upPressed = false;
}
else if(keyCode == 40) {
downPressed = false;
}
}
Use assignment operator = instead of comparison operator == for upPressed variable within keyUpHandler and keyDownHandler methods.
Don't set leftPressed, rightPressed, upPressed and downPressed values using by = operator within if...else conditions. Use comparison operator or logical values directly instead.
Update xPos and yPos values each time before drawBall method calling.
The working code below.
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var xPos = canvas.width / 2;
var yPos = canvas.height - 30;
var ballRadius = 10;
var leftPressed = false;
var rightPressed = false;
var upPressed = false;
var downPressed = false;
function drawBall() {
ctx.beginPath();
ctx.arc(xPos, yPos, ballRadius, 0, Math.PI * 2, false);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
SetPos();
drawBall();
}
setInterval(draw, 10);
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.keyCode == 37) {
leftPressed = true;
} else if (e.keyCode == 39) {
rightPressed = true;
} else if (e.keyCode == 38) {
upPressed = true;
} else if (e.keyCode == 40) {
downPressed = true;
}
}
function keyUpHandler(e) {
if (e.keyCode == 37) {
leftPressed = false;
} else if (e.keyCode == 39) {
rightPressed = false;
} else if (e.keyCode == 38) {
upPressed = false;
} else if (e.keyCode == 40) {
downPressed = false;
}
}
function SetPos() {
if (leftPressed) {
xPos -= 7;
} else if (rightPressed) {
xPos += 7;
} else if (upPressed) {
yPos -= 7;
} else if (downPressed) {
yPos += 7;
}
}
* {
padding: 0;
margin: 0;
}
canvas {
background: #eee;
display: block;
margin: 0 auto;
}
<canvas id="myCanvas" width="480" height="320"></canvas>
My keyPress movement seems to be broken, if I press arr.up/down twice then it gets broken and I can't move the element back. And the element doesn't even stop when I stop holding the arr.up/down, why?
rocket = new Image();
x = 50;
y = 185;
score = 0;
velY = 0;
speed = 2;
y += velY;
ctx.drawImage(rocket, x, y);
if(e.keyCode == 38) {
if(velY < speed) {
velY --;
}
}
if(e.keyCode == 40) {
if(velY < speed) {
velY ++;
}
}
Preview: http://game.stranger.tk/
I would have edited your code however your game via your link isn't working :(. I hope this code example I have provided helps you out.
jsFiddle : https://jsfiddle.net/w1z2c1cq/
javascript
var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
var rocket = function()
{
this.Sprite = new Image();
this.Sprite.src = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcS9zafp1ezdR2lSAxTdjZYe_nPhe6VeKKmAuK-GzWQCSs395WkzNA";
this.XPos = 100;
this.YPos = 100;
}
var player = new rocket();
setInterval(function()
{
ctx.fillRect(0,0,400,400);
ctx.drawImage(player.Sprite, player.XPos, player.YPos);
}, 3);
window.addEventListener("keydown", function(e){
// Left key
if(e.keyCode === 37) {
player.XPos -= 5;
}
// Right key
if(e.keyCode === 39) {
player.XPos += 5;
}
// Up key
if(e.keyCode === 38) {
player.YPos -= 5;
}
// Down key
if(e.keyCode === 40) {
player.YPos += 5;
}
});
Also in your code you are checking this same if statement for up and down if(velY < speed)
try
// Up
if(e.keyCode == 38) {
if(velY < speed) {
velY --;
}
}
// Down
if(e.keyCode == 40) {
if(velY > -speed) {
velY ++;
}
}
I'm working on a simple html/js project to get a box moving in a canvas that can shoot a ball. I got the box moving but I cant get the ball to appear. The program makes it to the drawBall() and moveBall()(Tested using alerts) functions but they don't do anything. I've been working on this the past hour and so and I just can't get it to work. Here's my javascript code that moves the box and should draw a ball whenever the spacebar is released.
function init() {
//canvas = document.getElementById('canvas');
context = $('#canvas')[0].getContext('2d');
WIDTH = $('#canvas').width();
HEIGHT = $('#canvas').height();
block_x = WIDTH / 2;
block_y = HEIGHT / 2;
setInterval('draw()', 25);
}
function clearCanvas() {
context.clearRect(0,0,WIDTH,HEIGHT);
}
function draw() {
clearCanvas();
if(shotBall)
{
drawBall();
moveBall();
}
if (rightKey) block_x += 5;
else if (leftKey) block_x -= 5;
if (upKey) block_y -= 5;
else if (downKey) block_y += 5;
if (block_x <= 0) block_x = 0;
if ((block_x + block_w) >= WIDTH) block_x = WIDTH - block_w;
if (block_y <= 0) block_y = 0;
if ((block_y + block_h) >= HEIGHT) block_y = HEIGHT - block_h;
context.fillRect(block_x, block_y, block_w, block_h);
}
function drawBall() {
context.beginPath();
context.arc(ball_x, ball_y, ball_radius, 0, Math.PI * 2, false);
}
function moveBall() {
ball_y += 1;
ball_x -= 1;
}
function onKeyDown(evt) {
if (evt.keyCode == 68) rightKey = true;
else if (evt.keyCode == 65) leftKey = true;
if (evt.keyCode == 87) upKey = true;
else if (evt.keyCode == 83) downKey = true;
}
function onKeyUp(evt) {
if (evt.keyCode == 68) rightKey = false;
else if (evt.keyCode == 65) leftKey = false;
if (evt.keyCode == 87) upKey = false;
else if (evt.keyCode == 83) downKey = false;
if(evt.keyCode == 32) createBall();
}
function createBall()
{
ball_x = block_x + (block_w / 2);
ball_y = block_y + (block_y / 2);
radius = 20;
shotBall = true;
}
$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);
When I tried your code
the problem that I can see is that you haven't initialized the block_w, and block_h and the ball_radius variables, because these values are seems to be undefined as I see in firebug tool.
So you have to make sure that you have defined and initialized every variable that you use.
Also You have to make sure that you are calling every function that you have defined.
When I put values manually in the context.arc(23, 34, 45, 0, Math.PI*2, false); function
then it works fine for me.
So make sure you have defined and initialized every variable.