How to move charater to other sectors - javascript

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>

Related

Difficulty Adding a "Play Again!" Button to this snake game

I've been trying to figure out how I can add a play again button to refresh the page after a player has lost. This is a classic snake game. I followed a tutorial on it and but they never said anything about a Play Again button. Any help would be appreciated. Nothing too complicated though please, I'm still learning.
const ctx = canvas.getContext("2d");
class SnakePart {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
let speed = 7;
let tileCount = 20;
let tileSize = canvas.width / tileCount - 2;
let headX = 10;
let headY = 10;
const snakeParts = [];
let tailLength = 2;
let appleX = 5;
let appleY = 5;
let inputsXVelocity = 0;
let inputsYVelocity = 0;
let xVelocity = 0;
let yVelocity = 0;
let score = 0;
const gulpSound = new Audio("gulp.mp3");
//game loop
function drawGame() {
xVelocity = inputsXVelocity;
yVelocity = inputsYVelocity;
changeSnakePosition();
let result = isGameOver();
if (result) {
return;
}
clearScreen();
checkAppleCollision();
drawApple();
drawSnake();
drawScore();
if (score > 5) {
speed = 9;
}
if (score > 10) {
speed = 11;
}
setTimeout(drawGame, 1000 / speed);
}
function isGameOver() {
let gameOver = false;
if (yVelocity === 0 && xVelocity === 0) {
return false;
}
//walls
if (headX < 0) {
gameOver = true;
} else if (headX === tileCount) {
gameOver = true;
} else if (headY < 0) {
gameOver = true;
} else if (headY === tileCount) {
gameOver = true;
}
for (let i = 0; i < snakeParts.length; i++) {
let part = snakeParts[i];
if (part.x === headX && part.y === headY) {
gameOver = true;
break;
}
}
if (gameOver) {
ctx.fillStyle = "white";
ctx.font = "50px Verdana";
if (gameOver) {
ctx.fillStyle = "white";
ctx.font = "50px Verdana";
var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
gradient.addColorStop("0", " magenta");
gradient.addColorStop("0.5", "blue");
gradient.addColorStop("1.0", "red");
// Fill with gradient
ctx.fillStyle = gradient;
ctx.fillText("Game Over!", canvas.width / 6.5, canvas.height / 2);
}
ctx.fillText("Game Over!", canvas.width / 6.5, canvas.height / 2);
}
return gameOver;
}
function drawScore() {
ctx.fillStyle = "white";
ctx.font = "10px Verdana";
ctx.fillText("Score " + score, canvas.width - 50, 10);
}
function clearScreen() {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function drawSnake() {
ctx.fillStyle = "green";
for (let i = 0; i < snakeParts.length; i++) {
let part = snakeParts[i];
ctx.fillRect(part.x * tileCount, part.y * tileCount, tileSize, tileSize);
}
snakeParts.push(new SnakePart(headX, headY)); //put an item at the end of the list next to the head
while (snakeParts.length > tailLength) {
snakeParts.shift(); // remove the furthet item from the snake parts if have more than our tail size.
}
ctx.fillStyle = "orange";
ctx.fillRect(headX * tileCount, headY * tileCount, tileSize, tileSize);
}
function changeSnakePosition() {
headX = headX + xVelocity;
headY = headY + yVelocity;
}
function drawApple() {
ctx.fillStyle = "red";
ctx.fillRect(appleX * tileCount, appleY * tileCount, tileSize, tileSize);
}
function checkAppleCollision() {
if (appleX === headX && appleY == headY) {
appleX = Math.floor(Math.random() * tileCount);
appleY = Math.floor(Math.random() * tileCount);
tailLength++;
score++;
gulpSound.play();
}
}
document.body.addEventListener("keydown", keyDown);
function keyDown(event) {
//up
if (event.keyCode == 38 || event.keyCode == 87) {
//87 is w
if (inputsYVelocity == 1) return;
inputsYVelocity = -1;
inputsXVelocity = 0;
}
//down
if (event.keyCode == 40 || event.keyCode == 83) {
// 83 is s
if (inputsYVelocity == -1) return;
inputsYVelocity = 1;
inputsXVelocity = 0;
}
//left
if (event.keyCode == 37 || event.keyCode == 65) {
// 65 is a
if (inputsXVelocity == 1) return;
inputsYVelocity = 0;
inputsXVelocity = -1;
}
//right
if (event.keyCode == 39 || event.keyCode == 68) {
//68 is d
if (inputsXVelocity == -1) return;
inputsYVelocity = 0;
inputsXVelocity = 1;
}
}
drawGame();```
The easiest way to refresh the page would be just:
window.location.reload(false)
Source:
https://www.freecodecamp.org/news/location-reload-method-how-to-reload-a-page-in-javascript/
I would suggest that simply reloading the page is not a great way to implement a play again feature but I appreciate the creativity of it.

How can i make the bullet not move with the character when looking either right or left?

I am having a problem where when I fire either left or right, once i move the character the bullets direction will change while its still fired. I am using the protagonist picture as the condition to either shoot right or left but i would like the bullet to keep firing in the fired direction even if i change the movement of the character
I am a beginner in Javascript and I'm using canvas to create a game for a college project.
if (moveBullet) {
let s = heroPic.src.substring(heroPic.src.lastIndexOf("/") + 1);
//alert(s);
if (s == "Protagenist_Right_Jet.png" || s == "Protagenist_Stand_Jet.png") {
bulletX += 20;
}
if (s == "Protagenist_Left_Jet.png") {
bulletX -= 20;
}
if (bulletX >= canvas.width) {
moveBullet = false;
bulletX = canvas.width + 50
bulletY = canvas.height + 50;
}
if (bulletX <= 0) {
moveBullet = false;
bulletX = canvas.width + 50
bulletY = canvas.height + 50;
}
}
Full Code
<!DOCTYPE html>
<body>
<div id="canvasesdiv" style="text-align: center;">
<canvas id="canvas1" width="800" height="500" tabIndex="0" style="background: url('Level 1.png');position: relative; display: block;">
</div>
<script>
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
//get the animation frame depending on the browser engine
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
//Hero Attributes
var jetPackAudio = new Audio();
jetPackAudio.src = "Jetpack Sound.mp3";
var heroPic = new Image();
var heroX ;
var heroY ;
//Decides where the hero is looking
var heroRight = false;
var life = 3;
var heroWidth = 50 ;
var heroHeight = 50 ;
var gravity = 5;
heroX = 20;
heroY = 440;
heroPic.src = "Protagenist_Stand_Jet.png";
function drawHero(x,y)
{
ctx.drawImage(heroPic,x,y,heroWidth,heroHeight);
}
hitBottom = function() {
var rockbottom = canvas.height - heroHeight;
if (heroY > rockbottom) {
heroY = rockbottom;
}
}
// Key Attribute
var key = new Image();
key.src = "Key1.png"
var keyX ;
var keyY ;
var keyCounter = 0;
var keyWidth = 30 ;
var keyHeight = 30 ;
function drawKey()
{
ctx.drawImage(key,keyX,keyY,keyWidth,keyHeight);
}
var killCounter = 0 ;
var levelKillCounter;
// Monster 1 Attributes
var monster1 = new Image();
monster1.src = "Monster1_Left.png"
var m1MoveLeft = true;
var m1X ;
var m1Y ;
var m1Width = 50 ;
var m1Height = 50 ;
function drawMonster1()
{
ctx.drawImage(monster1,m1X,m1Y,m1Width,m1Height);
}
// Monster 2 Attributes
var monster2 = new Image();
monster2.src = "Monster 2_Right.png"
var m2MoveRight = true;
var m2X ;
var m2Y ;
var m2Width = 50 ;
var m2Height = 50 ;
function drawMonster2()
{
ctx.drawImage(monster2,m2X,m2Y,m2Width,m2Height);
}
// Monster 3 Attributes
var monster3 = new Image();
monster3.src = "Monster3_Right.png"
var m3MoveRight = true;
var m3X ;
var m3Y ;
var m3Width = 50 ;
var m3Height = 50 ;
function drawMonster3()
{
ctx.drawImage(monster3,m3X,m3Y,m3Width,m3Height);
}
// Hit Bottom
hitBottom = function() {
var rockbottom = canvas.height - heroHeight;
if (heroY > rockbottom) {
heroY = rockbottom;
}
}
//Bullet Attribute
var bulletX;
var bulletY;
const ammo = [];
var moveBullet = false;
var bulletImage = new Image();
bulletImage.src = 'Bullet.png';
function drawBullet(x,y)
{
ctx.drawImage(bulletImage,bulletX,bulletY);
}
//this function is used to detect a hit monster 1
function getDistanceHit1() {
var xRect = (m1X - bulletX);
var yRect = (m1Y - bulletY);
return Math.sqrt(Math.pow((xRect), 2) + Math.pow((yRect), 2));
}
//this function is used to detect a hit monster 2
function getDistanceHit2() {
var xRect = (m2X - bulletX);
var yRect = (m2Y - bulletY);
return Math.sqrt(Math.pow((xRect), 2) + Math.pow((yRect), 2));
}
//this function is used to detect a hit monster 3
function getDistanceHit3() {
var xRect = (m3X - bulletX);
var yRect = (m3Y - bulletY);
return Math.sqrt(Math.pow((xRect), 2) + Math.pow((yRect), 2));
}
//this function is used to detect if the player got the key
function getDistanceKey() {
var xRect = (keyX - heroX);
var yRect = (keyY - heroY);
return Math.sqrt(Math.pow((xRect), 2) + Math.pow((yRect), 2));
}
//configure the audio files
var fireAudio = new Audio();
fireAudio.src = "fire.mp3";
var hitAudio = new Audio();
hitAudio.src = "neck_snap.wav"
//Hero Movement
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
window.addEventListener("keydown", heroControl);
//Keyboard Cotrolls
function heroControl(event) { //event handler function
if (event.keyCode == 32) { //SPACE BAR PRESSED - fire gun
moveBullet = true;
fireAudio.play();
bulletX = heroX + 10;
bulletY = heroY + (heroHeight / 2);
console.log("BulletX = " + bulletX);
}
// 38 is up arrow, 87 is the W key
if (event.keyCode == 38 || event.keyCode == 87) { //Jump
upPressed = true;
console.log("HeroY = " + heroY);
}
// 39 is right arrow, 68 is thw D key
else if (event.keyCode == 39 || event.keyCode == 68) { //move Right
rightPressed = true;
console.log("Herox = " + heroX);
}
else if(event.keyCode == 37 || event.keyCode == 65) { // Move Left
leftPressed = true;
console.log("Herox = " + heroX);
}
else if(event.keyCode == 40 || event.keyCode == 83) { // Move Left
downPressed = true;
console.log("Heroy = " + heroY);
}
}
//Touch Controls
canvas.addEventListener("touchstart", handleTouchStart, false);
function handleTouchStart(touchEvent) { //event handler for touch events
var rect = canvas.getBoundingClientRect(); //to get canvas offsets
let touchX = touchEvent.changedTouches[0].clientX - rect.left;
let touchY = touchEvent.changedTouches[0].clientY - rect.top;
if (touchX <= canvas.width && touchX > canvas.width - 200) {
rightPressed = true;
}
if (touchX >= 0 && touchX < canvas.width - 600) {
leftPressed = true;
}
if (touchY >= 0 && touchY < canvas.height - 200) {
upPressed = true;
}
if (touchY <= canvas.height && touchY > canvas.height - 200) {
downPressed = true;
}
}
function moveHero() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if(rightPressed) {
if(heroX < canvas.width - 53){
heroPic.src = "Protagenist_Right_Jet.png"
heroRight = true;
heroX = heroX + 10;
heroRight = true;
rightPressed = false;
}
else
{
rightPressed = false;
heroRight = false;
}
}
if(leftPressed) {
if(heroX > 0){
heroX = heroX - 10;
heroLeft = true;
heroPic.src = "Protagenist_Left_Jet.png";
bulletImage.src = "left_bullet.png";
leftPressed = false;
}
else
{
leftPressed = false;
heroLeft = false;
}
}
if(upPressed) {
if(heroY > 0){
heroY = heroY - 20;
heroStand = true;;
jetPackAudio.play();
heroPic.src = "Protagenist_Stand_Jet.png";
upPressed = false;
}
else
{
upPressed = false;
heroStand = false;;
}
}
if(downPressed) {
if(heroY < canvas.height){
heroPic.src = "Protagenist_Stand_Jet.png"
heroStand = true;
heroY = heroY + 10;
downPressed = false;
}
else
{
downPressed = false;
heroStand = false;
}
}
displayScoreArea();
drawHero(heroX,heroY);
drawMonster1();
drawMonster2();
drawMonster3();
drawKey();
drawBullet(bulletX,bulletY);
requestAnimationFrame(moveHero);
}
//Level Setter
var level = 2;
function setLvl()
{
if(level == 1)
{
canvas.style = "background: url('Level 1.png')";
levelKillCounter = 3;
}
else if(level == 2)
{
canvas.style = "background: url('Level 2.png')";
monster1.src = "Monster3_Right.png"
monster2.src = "Monster3_Right.png"
}
else if(level == 3)
{
canvas.style = "background: url('Level 3.png')";
}
}
var gameAudio = new Audio();
gameAudio.src = "Dungeon Theme.mp3"
function animation()
{
setTimeout(() => {
//animation code goes into this anonymous function handler
requestAnimationFrame(animation);
//clear the whole canvas area
ctx.clearRect(0, 0, canvas.width, canvas.height);
moveHero();
drawMonster1();
drawMonster2();
drawMonster3();
drawKey();
drawBullet(bulletX,bulletY);
monsterAnimate();
setLvl();
heroY = heroY + gravity;
if(moveBullet)
{
let s = heroPic.src.substring(heroPic.src.lastIndexOf("/") + 1);
//alert(s);
if(s == "Protagenist_Right_Jet.png" || s == "Protagenist_Stand_Jet.png")
{
bulletX +=20;
}
if(s == "Protagenist_Left_Jet.png")
{
bulletX -=20;
}
if(bulletX >= canvas.width)
{
moveBullet = false;
bulletX = canvas.width + 50
bulletY = canvas.height +50;
}
if(bulletX <= 0)
{
moveBullet = false;
bulletX = canvas.width + 50
bulletY = canvas.height +50;
}
console.log(getDistanceHit1());
if (getDistanceHit1() <= 30 ||
getDistanceHit2() <= 30 ||
getDistanceHit3() <= 30 )
{
//Delete Monster
if(getDistanceHit1() <= 30)
{
m1X = 1000;
m1Y = 1000;
}
if(getDistanceHit2() <= 30)
{
m2X = 1000;
m2Y = 1000;
}
if(getDistanceHit3() <= 30)
{
m3X = 1000;
m3Y = 1000;
}
//increase the hit count
killCounter++;
//we have a hit
moveBullet = false;
//play the hitAudio
hitAudio.play();
//Reset Bullet
bulletX = canvas.width + 50
bulletY = canvas.height +50;
}
}
if(killCounter == 3)
{
keyX = canvas.width / 2;
keyY = 150;
}
if(getDistanceKey() <= 10)
{
keyCounter = 1;
keyX = 1000;
keyY = 1000;
}
//level progression flow - check of level objectives are met
if (level == 1 && keyCounter == 1 && heroX >= 700 & heroY >= 50) {
alert("Level 1 completed. Starting Level 2...");
level = 2;
killCounter = 0; //reset
keyCounter = 0;//reset
m1X = 700;
m1Y = 370;
m2X = 100;
m2Y = 320;
m3X = 100;
m3Y = 170;
}
else if (level == 2 && keyCounter == 1 && heroX == 700 & heroY == 50) {
alert("Level 2 completed. Starting Level 3...");
level = 3;
killCounter = 0; //reset
keyCounter = 0;//reset
}
else if (level == 3 && currentLevelHits == 4) {
//last level
var playAgain = confirm("Game completed. Play again?");
if (playAgain)
window.location.reload(true); //force reload
else
stopAnimation = true;
}
//gameAudio.play();
displayScoreArea();
hitBottom();
},100)
}
m1X = 700;
m1Y = 370;
m2X = 100;
m2Y = 320;
m3X = 100;
m3Y = 170;
function monsterAnimate()
{
//Movement for level 1
if(level == 1)
{
if(m1MoveLeft)
{
m1X -= 10
}
else if(!m1MoveLeft)
{
m1X += 10
}
if(m2MoveRight)
{
m2X += 10
}
else if(!m2MoveRight)
{
m2X -= 10
}
if(m3MoveRight)
{
m3X +=10
}
else if(!m3MoveRight)
{
m3X -= 10
}
if(m1X == 420)
{
m1MoveLeft = false;
monster1.src ="Monster 1_Right.png"
}
else if(m1X == 700)
{
m1MoveLeft = true;
monster1.src ="Monster1_Left.png"
}
if(m2X == 310)
{
m2MoveRight = false;
monster2.src ="Monster2_left.png"
}
else if(m2X == 100)
{
m2MoveRight = true;
monster2.src ="Monster 2_Right.png"
}
if(m3X == 310)
{
m3MoveRight = false;
monster3.src ="Monster 3_left.png"
}
else if(m3X == 100)
{
m3MoveRight = true;
monster3.src ="Monster3_Right.png"
}
}
//Movement for level 2
if(level == 2)
{
if(m1MoveLeft)
{
m1X -= 20
}
else if(!m1MoveLeft)
{
m1X += 20
}
if(m2MoveRight)
{
m2X += 20
}
else if(!m2MoveRight)
{
m2X -= 20
}
if(m3MoveRight)
{
m3X +=20
}
else if(!m3MoveRight)
{
m3X -= 20
}
if(m1X == 420)
{
m1MoveLeft = false;
monster1.src ="Monster 1_Right.png"
}
else if(m1X == 700)
{
m1MoveLeft = true;
monster1.src ="Monster1_Left.png"
}
if(m2X == 600)
{
m2MoveRight = false;
monster2.src ="Monster2_left.png"
}
else if(m2X == 100)
{
m2MoveRight = true;
monster2.src ="Monster 2_Right.png"
}
if(m3X == 500)
{
m3MoveRight = false;
monster3.src ="Monster 3_left.png"
}
else if(m3X == 100)
{
m3MoveRight = true;
monster3.src ="Monster3_Right.png"
}
}
}
// Create gradient
var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
gradient.addColorStop("0", "black");
gradient.addColorStop("0.5", "red");
gradient.addColorStop("1.0", "white");
//Draw Score Area
function displayScoreArea() {
ctx.font = "40px Arial";
ctx.strokeStyle = gradient;
ctx.fillStyle = gradient;
ctx.strokeText(killCounter, 380, 60);
ctx.strokeText(life, 65, 45);
ctx.strokeText(keyCounter, 65, 90);
}
animation();
function moveup()
{
upPressed = true;
}
function movedown()
{
downPressed = true;
}
function moveright()
{
rightPressed = true;
}
function moveleft()
{
leftPressed = true;
}
function shootGun()
{
moveBullet = true;
fireAudio.play();
bulletX = heroX + 10;
bulletY = heroY + (heroHeight / 2);
console.log("BulletX = " + bulletX);
}
</script>
<div style="text-align:center;width:900px;">
<button style="width: 100px; height: 60px;" onclick="moveup()">UP</button><br><br>
<button style="width: 100px; height: 60px;" onclick="moveleft()">LEFT</button>
<button style="width: 100px; height: 60px; margin-left: 20px;" onclick="moveright()">RIGHT</button><br><br>
<button style="width: 100px; height: 60px;" onclick="movedown()">DOWN</button>
<button style="width: 100px; height: 60px;" onclick="shootGun()">SHOOT</button>
</div>
</body>
</html>
Using objects would be one (of many) steps in the right direction. Even without them, you could:
In your bullet variable creation
...
//Bullet Attribute
let bulletX;
let bulletY;
let bulletVelocity;
...
In your hero control function, where the firing action currently takes place, initialize your bullet properties once
...
//Keyboard Cotrolls
function heroControl(event) { //event handler function
if (event.keyCode == 32) { //SPACE BAR PRESSED - fire gun
moveBullet = true;
fireAudio.play();
bulletX = heroX + 10;
bulletY = heroY + (heroHeight / 2);
// Initialize bullet velocity
let s = heroPic.src.substring(heroPic.src.lastIndexOf("/") + 1);
//alert(s);
if (s == "Protagenist_Right_Jet.png" || s == "Protagenist_Stand_Jet.png") {
bulletVelocity = 20;
} else {
bulletVelocity = -20;
}
...
In your animation function, where this currently takes place, update your bullet position according to its velocity
...
if (moveBullet) {
bulletX += bulletVelocity;
if (bulletX >= canvas.width) {
...
There are lots of things I would refactor in your current setup, but this should get you moving on your current problem.
And a quick example of a very simple object:
// create with key: value pairs
let bullet = {
x: 0,
y: 0,
velocity: 0,
};
// Access or set properties using dot notation
bullet.x = heroX + 10;
bullet.y = heroY + (heroHeight / 2);

My Javascript ball moving code isn't working

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>

javascript jumping character not working

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

Drawing an arc in java script but it doesn't appear

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.

Categories