This is index.html file.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dragon Progression</title>
<script type="text/javascript" src="library/easeljs-0.6.0.min.js"></script>
<script type="text/javascript" src="libs/ndgmr.Collision.js"></script>
<script type="text/javascript" src="js/startScreen.js"></script>
<script type="text/javascript" src="js/gameScreen.js"></script>
</head>
<body onLoad="renderStartScreen()">
<canvas id="canvas1" width="1024" height="698">
Browser does not support canvas. Please upgrade browser.
</canvas>
</body> </html>
This is StartScreen.js
var introBackground;
var startScreenBtn;
var startScreenBtnImg;
var stage;
var stageHeight;
var stageWidth;
//this function render start screen
function renderStartScreen()
{
stage = new createjs.Stage("canvas1");
stage.enableMouseOver();
stageWidth = document.getElementById("canvas1").width;
stageHeight = document.getElementById("canvas1").height;
introBackground = new createjs.Bitmap("assets/images/bg.jpg");
introBackground.x = introBackground.y = 0;
stage.addChild(introBackground);
startScreenBtn = new createjs.Container();
startScreenBtn.x = 500;
startScreenBtn.y = 300;
startScreenBtnImg = new createjs.Bitmap("assets/images/start_button_normal.png");
stage.addChild(startScreenBtn);
startScreenBtn.addChild(startScreenBtnImg);
var btnBg = new createjs.Shape();
btnBg.graphics.beginFill("#FFFFFF");
btnBg.graphics.drawRect(0, 0, 143, 35);
btnBg.alpha = 0.01;
startScreenBtn.addChild(btnBg);
startScreenBtn.addEventListener("mouseover", onstartScreenBtnOver);
startScreenBtn.addEventListener("mouseout", onstartScreenBtnOut);
startScreenBtn.addEventListener("click", onstartScreenBtnClick);
createjs.Ticker.setFPS(45);
createjs.Ticker.addEventListener("tick", startScreenTickHandler);
}
//event handler function get called on start button roll over
function onstartScreenBtnOver()
{
startScreenBtnImg.image.src = "assets/images/start_button_over.png";
}
//event handler function get called on start button roll out
function onstartScreenBtnOut()
{
startScreenBtnImg.image.src = "assets/images/start_button_normal.png";
}
//event handler function get called on start button click
function onstartScreenBtnClick(event)
{
cleanupStartScreen();
}
//event handler function get called on specified interval
function startScreenTickHandler()
{
stage.update();
}
//clean start screen and loads main game
function cleanupStartScreen()
{
stage.removeAllChildren();
stage.update();
stage.removeAllEventListeners();
createjs.Ticker.removeEventListener("tick", startScreenTickHandler);
loadMainGame();
}
This is gamescreen.js file.
var background;
var snakeArray = [];
//var snakeBody;
var snake;
var snakeWidth=25;
var food;
var keyCode;
var CHECK_HIT_ALPHA = 1;
var currDirection;
var tempX;
var tempY;
var prevX;
var prevY;
function loadMainGame()
{
background = new createjs.Bitmap("assets/images/loading_background.jpg");
background.x=0;
background.y=0;
//snake = new createjs.Container();
//snakeTail = new createjs.Shape();
//snakeTail.graphics.beginFill("#E2DC1E").drawPolyStar(40,65,15,3,0,360);
createSnakeHead();
createFood();
snakeArray.currDirection = "";
stage.addChild(background,snake,food);
createjs.Ticker.addEventListener("tick", snakeMovement);
//createjs.Ticker.addEventListener("tick", snakeBodyMovement);
window.onkeydown=function(e)
{
keyCode = e.keyCode || e.which || window.Event;
if(keyCode == 37 && currDirection != "right")
{
currDirection = "left";
snake.rotation= -90;
tempX = snakeArray[0].x;
tempY = snakeArray[0].y;
}
else if(keyCode == 39 && currDirection !="left")
{
currDirection = "right";
snake.rotation = 90;
tempX = snakeArray[0].x;
tempY = snakeArray[0].y;
}
else if(keyCode == 38 && currDirection != "down")
{
currDirection = "up";
snake.rotation = 360;
tempX = snakeArray[0].x;
tempY = snakeArray[0].y;
}
else if(keyCode == 40 && currDirection != "up")
{
currDirection = "down";
snake.rotation = 180;
tempX = snakeArray[0].x;
tempY = snakeArray[0].y;
}
}
}
function createSnakeHead()
{
snake = new createjs.Bitmap("assets/images/snake.png");
snake.type = "head";
var randX = Math.floor(Math.random()*800);
var randY = Math.floor(Math.random()*500);
snake.x = randX;
snake.y = randY;
snake.regX = snake.image.width/2;
snake.regY = snake.image.height/2;
snakeArray.push(snake);
}
function createFood()
{
food = new createjs.Bitmap("assets/images/food.png");
var randX = Math.floor(Math.random()*800);
var randY = Math.floor(Math.random()*500);
food.x = randX;
food.y = randY;
}
function snakeMovement()
{
console.log(snakeArray.length);
for(var i=0;i<=snakeArray.length-1;i++)
{
if(currDirection=="left")
{
snakeArray[i].rotation= -90;
snakeArray[i].x = snakeArray[i].x - 2;
prevX = snakeArray[i].x;
prevY = snakeArray[i].y;
if (snakeArray[i].x <= 0)
{
snakeArray[i].x = stageWidth;
}
snakeBodyMovement(prevX,prevY);
}
else if(currDirection == "right")
{
//tempX = snakeArray[0].x;
snakeArray[i].rotation= 90;
snakeArray[i].x = snakeArray[i].x + 2;
prevX = snakeArray[i].x;
prevY = snakeArray[i].y;
if (snakeArray[i].x >= stageWidth)
{
snakeArray[i].x = 0;
}
snakeBodyMovement(prevX,prevY);
snakeArray[i].currDirection = "right";
}
else if(currDirection == "up")
{
//tempY = snakeArray[0].y;
snakeArray[i].rotation= 360;
snakeArray[i].y = snakeArray[i].y - 2;
prevX = snakeArray[i].x;
prevY = snakeArray[i].y;
if(snakeArray[i].y <=0)
{
snakeArray[i].y = stageHeight;
}
snakeBodyMovement(prevX,prevY);
snakeArray[i].currDirection = "up";
}
else if(currDirection == "down")
{
//var tempY = snakeArray[0].y;
snakeArray[i].rotation= 180;
snakeArray[i].y = snakeArray[i].y + 2;
prevX = snakeArray[i].x;
prevY = snakeArray[i].y;
if(snakeArray[i].y >= stageHeight)
{
snakeArray[i].y = 0;
}
snakeBodyMovement(prevX,prevY);
snakeArray[i].currDirection = "down";
}
}
foodSnakeCollision();
stage.update();
}
function foodSnakeCollision()
{
var intersection = ndgmr.checkPixelCollision(snake,food,CHECK_HIT_ALPHA);
if(intersection)
{
console.log("Eat food");
var randX = Math.floor(Math.random()*800);
var randY = Math.floor(Math.random()*500);
food.x = randX;
food.y = randY;
createSnake();
}
}
function createSnake()
{
var snakeBody = new createjs.Bitmap("assets/images/snake.png");
snakeBody.type = "body";
snakeBody.regX = snake.image.width/2;
snakeBody.regY = snake.image.height/2;
if(currDirection=="left")
{
snakeBody.x = snakeArray[snakeArray.length-1].x + 25;
snakeBody.y =snakeArray[snakeArray.length-1].y +0;
}
if(currDirection == "right")
{
snakeBody.x = snakeArray[snakeArray.length-1].x - 25;
snakeBody.y =snakeArray[snakeArray.length-1].y - 0;
}
if(currDirection == "up")
{
snakeBody.x = snakeArray[snakeArray.length-1].x + 0;
snakeBody.y =snakeArray[snakeArray.length-1].y + 25;
}
if(currDirection == "down")
{
snakeBody.x = snakeArray[snakeArray.length-1].x - 0;
snakeBody.y =snakeArray[snakeArray.length-1].y - 25;
}
snakeArray.push(snakeBody);
console.log(snakeArray.length + "after collision");
stage.addChild(snakeBody);
}
function snakeBodyMovement(prevX,prevY)
{
for(var i=1;i<=snakeArray.length-1;i++)
{
if(currDirection == "left")
{
snakeArray[i].x = prevX + 15;
snakeArray[i].y = prevY;
}
else if(currDirection == "right")
{
snakeArray[i].x = prevX - 15;
snakeArray[i].y = prevY;
}
else if(currDirection == "up")
{
snakeArray[i].x = prevX;
snakeArray[i].y = prevY + 15;
}
else if(currDirection == "down")
{
snakeArray[i].x = prevX;
snakeArray[i].y = prevY - 15;
}
}
}
in gameScreen.js file,the new snakebody that i add using snakebody is not appending one after the other. It is adding one below the other.Please suggest how do i smoothly move the snake body and the additional snake parts that gets added once it collides with the food.
I think the root of your problem here is that you aren't preloading your images. Consider your code block from GameScreen.js
snake = new createjs.Bitmap("assets/images/snake.png");
snake.type = "head";
var randX = Math.floor(Math.random()*800);
var randY = Math.floor(Math.random()*500);
snake.x = randX;
snake.y = randY;
console.log("Snake head width: " + snake.image.width);
snake.regX = snake.image.width/2;
snake.regY = snake.image.height/2;
The image isn't loaded from the server until the declaration of the Bitmap is made. Because loading images is asynchronous, your image won't necessarily be loaded by the time it hits the line snake.regX = snake.image.width/2; and the width and height will both be 0. You can confirm this by looking at the console log I have added. With your registration points off, all your positioning will be off as well.
My suggestion would be to use the preloadjs library that is part of the createjs suite to preload your images. http://www.createjs.com/Docs/PreloadJS/modules/PreloadJS.html.
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 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);
I'm making a game where your mouse is a cross hair and you click on zombies moving across the screen. I'm having troubles figuring out how to find if the mouse has clicked on a zombie. The zombies are made in JavaScript so I can't use the onclick attribute in HTML. This is my code.
var mouseX;
var mouseY;
$(document).ready(function(){
var canvasWidth = 640;
var canvasHeight = 480;
var canvas = $("#gameCanvas")[0];
var context = canvas.getContext("2d");
var score = 0;
var timer = 0;
var spawnZombie = false;
//crosshair
var crossHair = new Image();
var crosshairX = 50;
var crosshairY = 50;
crossHair.src = "media/crosshair.png";
//zombies
var zombies = [];
var zombieLeft = new Image();
zombieLeft.src = "media/zombieLEFT.gif";
var zombieRight = new Image();
zombieRight.src = "media/zombieRIGHT.gif";
var fps = 30;
setInterval(function(){
update();
draw();
}, 1000/fps);
function update(){
timer += 1;
crosshairX = mouseX - 445;
crosshairY = mouseY - 125;
if(timer >= 70){
timer = 0;
spawnZombie = true;
}
zombies.forEach(function(zombie) {
zombie.update();
document.body.onmousedown = function() {
console.log(zombie.x.toString() + ", " + zombie.y.toString());
//if(mouseX)
};
});
zombies = zombies.filter(function(zombie){
return zombie.active;
});
if(spawnZombie){
zombies.push(Zombie(null, "left"));
zombies.push(Zombie(null, "right"));
spawnZombie = false;
}
}
function draw(){
context.clearRect(0,0, canvasWidth, canvasHeight);
context.fillStyle = "#000";
context.font = "20px Comic Sans MS";
context.fillText("Score: " + score, 50, 50);
zombies.forEach(function(zombie) {
zombie.draw();
});
context.drawImage(crossHair, crosshairX, crosshairY, 100, 100);
}
function Zombie(I, dir){
I = I || {};
I.active = true;
I.speed = 5;
I.y = getRandomInt(50, 350);
if(dir == "left"){
I.x = 800;
}
else if(dir == "right"){
I.x = -100;
}
I.width = 100;
I.height = 100;
I.inBounds = function() {
return I.x >= 0 && I.x <= canvasWidth &&
I.y >= 0 && I.y <= canvasHeight;
};
I.draw = function(){
if(dir == "left"){
context.drawImage(zombieLeft, this.x, this.y, this.width, this.height);
}
else if(dir == "right"){
context.drawImage(zombieRight, this.x, this.y, this.width, this.height);
}
};
I.update = function(){
if(dir == "left"){
this.x -= this.speed;
}
else if(dir == "right"){
this.x += this.speed;
}
};
I.onclick = function(){
I.remove();
};
return I;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
});
$( document ).on( "mousemove", function( event ) {
mouseX = event.pageX;
mouseY = event.pageY;
});
This is the specific spot where I'm trying to detect if the zombie has been clicked on within my update functio
zombies.forEach(function(zombie) {
zombie.update();
document.body.onmousedown = function() {
console.log(zombie.x.toString() + ", " + zombie.y.toString());
//if(mouseX)
};
});
I can't use the onclick attribute in HTML.
But you can use the addEventListener method in your javascript:
eg.
zombieLeft.addEventListener('click', myFunction, false);
document.body.onmousedown = function(event) {
console.log(zombie.x.toString() + ", " + zombie.y.toString());
if(event.pageX == zombie.x && event.pageY == zombie.y){
//Zombie clicked
}
};
This is pseudo code. You can attach event and you can check for x and y.
I'm making a game for school and wanted to place some trees in it. I thought it would be nice if i could make an array and place several trees from the array in the canvas. it seems that the array doesn't draw the trees on the canvas. I'm looking at it for hours and can't figure it out. Could somebody help me, please?
i've got two different .js documents. one is the general file and one for the trees.
First the general:
$(document).ready(function() {
var horse = new Image();
horse.src = "ash.png"
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var xPos = 0;
var yPos = 0;
var animStep = 0;
var sx = 0;
var sy = 96;
var previousStep = Date.now();
var moveRight = false;
var moveLeft = false;
var moveUp = false;
var moveDown = false;
var achtergrond = 0;
//background 1
var grass = new Image();
grass.src = "grass.png";
var grassPattern;
grass.onload = function(){
grassPattern = context.createPattern(grass,"repeat");
}
//background 2
var cave = new Image();
cave.src = "cave.png";
var cavePattern;
cave.onload = function(){
cavePattern = context.createPattern(cave,"repeat");
}
//start drawfunction --------------------------------------------
function draw(){
//make an array:
var objects = [];
//make the chests:
objects.push( new Chest(100,200) );
objects.push( new Chest(200,200) );
objects.push( new Chest(200,100) );
for (var i = 0; i < objects.length; i++) {
objects[i].draw();
}
update();
spritesheet();
//spritesheet back in the canvas:
if ( xPos > canvas.width ) {
xPos = 0;
achtergrond = 1;
}
if (xPos < -32){
xPos = canvas.width;
achtergrond = 0;
}
if ( yPos > canvas.height ) {
// put the y to 0
yPos = 0;
achtergrond = 1;
}
if ( yPos < -32 ) {
yPos = canvas.height;
achtergrond = 0;
}
if (achtergrond == 0){
context.fillStyle=grassPattern;
context.fillRect (0,0,canvas.width,canvas.height);
}
else if (achtergrond == 1){
context.fillStyle=cavePattern;
context.fillRect (0,0,canvas.width,canvas.height);
}
context.drawImage(horse,animStep*32,sy,28,32,xPos,yPos,30,32);
// call the function walk:
walk();
requestAnimationFrame(draw);
}
draw();
//end draw function ----------------------------------------------------
$(document).keydown( function(evt) {
if (evt.which == 39){ // if the right arrow key is pressed
moveRight = true;
}
if (evt.which == 37){ // if the left arrow key is pressed
moveLeft = true;
}
if (evt.which == 38){ // if the up arrow key is pressed
moveUp = true;
}
if (evt.which == 40){ // if the down arrow key is pressed
moveDown = true;
}
});
$(document).keyup( function(evt) {
if (evt.which == 39){ // if the right arrow key is lifted
moveRight = false;
}
if (evt.which == 37){ // if the left arrow key is lifted
moveLeft = false;
}
if (evt.which == 38){ // if the up arrow key is lifted
moveUp = false;
}
if (evt.which == 40){ // if the down arrow key is lifted
moveDown = false;
}
});
function update() {
if (moveRight) {
xPos += 4;
} else if (moveLeft) {
xPos -= 4;
} else if (moveUp) {
yPos -= 4;
} else if (moveDown) {
yPos += 4;
}
}
function walk(){
if (Date.now() - previousStep > 1000/10) {
animStep += 1;
if (animStep == 5) {
animStep = 0;
}
previousStep = Date.now();
}
}
function spritesheet() {
if (moveUp) {
sy = 65;
} else if (moveDown) {
sy = 0;
} else if (moveRight){
sy = 96;
} else if (moveLeft) {
sy = 32;
}
// als we in geen enkele richting lopen (! betekent niet)
if (!moveRight && !moveLeft && !moveUp && !moveDown) {
// staan we blijkbaar stil en gebruiken we de neutrale pose
sx = animStep = 0;
} else {
// anders het huidige stapje maal de breedte van 1 stapje
sx = animStep * 32;
}
}
});
and the second .js file:
function Chest(x,y) {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// Chest Image object maken
var img = new Image();
img.src = "boom.png";
this.draw = function() {
context.drawImage(img,0,0,33,33,this.x,this.y,33,33);
}
}
and ofcourse there is the canvas HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="rAF.js"></script>
<script src="objects.js"></script>
<script src="index.js"></script>
<title>Untitled Document</title>
</head>
<body>
<canvas id="myCanvas" width="600" height="400"></canvas>
</body>
</html>
Inside your Chest-function, declare the img.variable as local:
function Chest(x,y) {
//The function should be able to find these global variables without you delcaring them inside
//var canvas = document.getElementById('myCanvas');
//var context = canvas.getContext('2d');
//declaring your x and y variables
this.x = x;
this.y = y;
// Chest Image object maken
this.img = new Image();
this.img.src = "boom.png";
this.draw = function() {
context.drawImage(this.img,0,0,33,33,this.x,this.y,33,33);
}
}
I'm trying to add links to the images in my JS array so that, when clicked, they direct you to a info page.
I tried to use the following code but the images won't show.
var WorkArray = new Array(['work/01.png',"http://www.stackoverflow.com"],
['work/02.png',"http://www.stackoverflow.com"],
['work/03.png',"http://www.stackoverflow.com"],
['work/04.png',"http://www.stackoverflow.com"]);
If I remove the links the images do show.
I'm using a variation of this code: http://bouncingdvdlogo.com/
Here is my full code:
var width = 400;
var height = 400;
var swoosh = 4;
var stopafter=0; //set time in seconds before image disappears. Use 0 for never
var maxswoosh = 50;
var xMax;
var yMax;
var xPos = 0;
var yPos = 0;
var xDir = 'right';
var yDir = 'down';
var screenSavouring = true;
var tempswoosh;
var newXDir;
var newYDir;
function setupShit() {
if (document.all) {
xMax = document.body.clientWidth
yMax = document.body.clientHeight
document.all("work").style.visibility = "visible";
}
else if (document.layers||document.getElementById) {
xMax = window.innerWidth-0;
yMax = window.innerHeight;
if (document.getElementById)
document.getElementById("work").style.visibility="visible"
else
document.layers["work"].visibility = "show";
}
setTimeout('moveIt()',500);
}
function moveIt() {
if (screenSavouring == true) {
calculatePosition();
if (document.all) {
document.all("work").style.left = xPos + document.body.scrollLeft;
document.all("work").style.top = yPos + document.body.scrollTop;
}
else if (document.layers) {
document.layers["work"].left = xPos + pageXOffset;
document.layers["work"].top = yPos + pageYOffset;
}
else if (document.getElementById) {
document.getElementById("work").style.left = xPos + pageXOffset;
document.getElementById("work").style.top = yPos + pageYOffset;
}
doit=setTimeout('moveIt()',30);
}
}
function calculatePosition() {
if (xDir == "right") {
if (xPos > (xMax - width - swoosh)) {
xDir = "left";
cC();
}
}
else if (xDir == "left") {
if (xPos < (0 + swoosh)) {
xDir = "right";
cC();
}
}
if (yDir == "down") {
if (yPos > (yMax - height - swoosh)) {
yDir = "up";
cC();
}
}
else if (yDir == "up") {
if (yPos < (0 + swoosh)) {
yDir = "down";
cC();
}
}
if (xDir == "right") {
xPos = xPos + swoosh;
}
else if (xDir == "left") {
xPos = xPos - swoosh;
}
else {
xPos = xPos;
}
if (yDir == "down") {
yPos = yPos + swoosh;
}
else if (yDir == "up") {
yPos = yPos - swoosh;
}
else {
yPos = yPos;
}
}
if (document.all||document.layers||document.getElementById){
window.onload = setupShit;
window.onresize = new Function("window.location.reload()");
}
var WorkArray = new Array(['work/01.png',"http://www.stackoverflow.com", "Your text goes here"],
['work/02.png',"http://www.stackoverflow.com", "Your text goes here"],
['work/03.png',"http://www.stackoverflow.com", "Your text goes here"],
['work/04.png',"http://www.stackoverflow.com", "Your text goes here"]);
var nelements = WorkArray.length;
preload_image_object = new Image();
var i = 0;
for(i=0; i<=nelements; i++) {
preload_image_object.src = WorkArray[i];
}
var currentImage = 0
function cC() {
currentImage = (currentImage + 1) % WorkArray.length;
document.getElementById("work").style.backgroundImage="url('"+WorkArray[currentImage]+"')";
}
Thanks!
Try replacing your for loop with below
for(i=0; i<nelements; i++) {
preload_image_object.src = WorkArray[i][0];
}
Also Replace function cC() with below:
function cC() {
var nelements = WorkArray.length;
var rdmnum = Math.floor(Math.random() * nelements);
var currentImage = rdmnum++;
if (currentImage == nelements) {
rdmnum = Math.floor(Math.random() * nelements);
}
currentImage = (currentImage + 1) % WorkArray.length;
document.getElementById("work").style.backgroundImage = "url('" + WorkArray[currentImage][0] + "')";
}