Placing an object from an array in a canvas - javascript

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);
}
}

Related

Moving an image on a canvas with arrow keys

I'm trying to get a block I've called "Sword" to move up and down when using the arrow keys, I have event listeners and handlers but for some reason they're just not talking to each other and I dunno why.
Here is the HTML, it's very simple, just draws a canvas to use.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>17013455_assignment_2</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="17013455_ass2_task1.js"></script>
</html>
This is the Javascript, the canvas has a background drawn on, and the "sword" is drawn as a box, my key handlers should move the sword on the Y axis depending on the sword's height and it's space in the Y axix.
window.onload=function () {
var canvas = document.getElementById("canvas");
var gc = canvas.getContext("2d");
canvas.width = 640;
canvas.height = 448;
gc.clearRect(0, 0, canvas.width, canvas.height);
var background = new Image();
background.src = "https://i.imgur.com/9mPYXqC.png";
//sword dimentions
var swordHeight = 50;
var swordWidth = 25;
var swordX = 50;
var swordY = 220;
//controls for player
var upPressed = false;
var downPressed = false;
if (downPressed && swordY < canvas.height - swordHeight) {
swordY += 10;
}
else if (upPressed && swordY > 0) {
swordY -= 10;
}
function keyUpHandler(e) {
if (e.keyCode === 38) {
upPressed = false;
}
else if (e.keyCode === 40) {
downPressed = false;
}
}
function drawSword() {
/*Make a box to represent a sword until sprites are used*/
gc.beginPath();
gc.rect(swordX, swordY, swordWidth, swordHeight);
gc.fillStyle = "#000000";
gc.fill();
gc.closePath();
}
function keyDownHandler(e) {
if (e.keyCode === 38) {
upPressed = true;
}
else if (e.keyCode === 40) {
downPressed = true;
}
}
function render() {
background.onload = function () {
gc.drawImage(background, 0, 0)};
drawSword();
}
document.addEventListener("keydown", keyDownHandler, "false");
document.addEventListener("keyup", keyUpHandler, "false");
render();
setInterval(render, 10);
};
Move this part of code
if (downPressed && swordY < canvas.height - swordHeight) {
swordY += 10;
}
else if (upPressed && swordY > 0) {
swordY -= 10;
}
to render() function.
Your function should look like this:
function render() {
if (downPressed && swordY < canvas.height - swordHeight) {
swordY += 10;
}
else if (upPressed && swordY > 0) {
swordY -= 10;
}
gc.drawImage(background, 0, 0)};
drawSword();
}
and this part
background.onload = function () {
gc.drawImage(background, 0, 0)};
to window.onload = function(){} scope

Javascript Canvas Game - How to know when object crosses its own path?

I am new to Javascript. I am trying to make a canvas game similar to Snake, but without the fruits.
The game is over if the player crosses his own path. The following is my code. Do you know how can I determine when the red rectangle crosses its own path and use the game over function?
Thank you!
var player;
var touch = 0;
function startGame() {
myGameArea.start();
player = new component(30, 30, "red", 270, 270);
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 600;
this.canvas.height = 600;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function(e) {
myGameArea.key = e.keyCode;
})
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y) {
this.gamearea = myGameArea;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
/*myGameArea.clear();*/
player.speedX = 0;
player.speedY = 0;
if (myGameArea.key == 37) {
player.speedX = -10;
}
if (myGameArea.key == 39) {
player.speedX = 10;
}
if (myGameArea.key == 38) {
player.speedY = -10;
}
if (myGameArea.key == 40) {
player.speedY = 10;
}
if (player.x <= 0 || player.x >= 570 || player.y <= 0 || player.y >= 570) { //When the player goes out of the canvas
gameOver();
}
player.newPos();
player.update();
}
function gameOver() {
var r = confirm("GAME OVER. Restart?");
if (r == true) {
window.location.reload();
} else {
window.open("https://www.google.ca");
}
}
canvas {
padding-left: 0;
padding-right: 0;
margin-left: auto;
margin-right: auto;
display: block;
background-color: #000;
}
<body onload="startGame()">
</body>
Array as a Queue.
The way this game is traditionally done is using a special array type called a queue. Like a real queue you have items added at one end and removed at the other, or first in first out.
Javascript does not have a special array type for a queue but it has all the functions needed to implement a queue.
Push and shift
Array.push(item); // pushes an item onto the top of the array
Array.shift(); // removes an item from the start of the queue
So for the snake game imagine the head as the end of the queue. Every time it moves one forward you place another item on the queue. At the other end you remove an item if the length of the array is longer than the snake length;
var snake = [];
var snakeLength = 10;
function snakeMove(x,y){ // position to move head
checkForHit(x,y); // see below
snake.push({x:x,y:y}); // put another headpiece on the queue
if(snake.length > snakeLength){ // is the length longer than it should be
snake.shift(); // remove a tail item
}
}
To draw the snake you just iterate each part drawing it at the X,y position
To test if the snake has run its self over use the following function
function checkForHit(x,y){
for(var i = 0; i < snake.length; i++){
if(snake[i].x === x && snake[i].y === y){
// Snake has hit its self
}
}
}
When the snake eats something it traditionally grows in length. this is easily done by simply increasing the length variable. snakeLength += 1 makes the queue longer.
And a demo as i have not played the game in so long why not.
"use strict";
var score = 0;
var canvas = document.createElement("canvas");
var scoreE = document.createElement("div");
scoreE.style.color = "white";
scoreE.style.font = "16px arial";
scoreE.style.position = "absolute";
scoreE.style.top = "10px";
scoreE.style.left = "10px";
scoreE.style.width = "600px";
scoreE.style.textAlign = "center";
scoreE.textContent = "Click canvas area to get focus";
canvas.width = 600;
canvas.height = 200;
var ctx = this.canvas.getContext("2d");
document.body.appendChild(canvas);
document.body.appendChild(scoreE);
var lastKeyDown = 0;
window.addEventListener('keydown', function(e) {
lastKeyDown = e.keyCode;
e.preventDefault()
})
var snakePartSize = 8;
var playWidth = canvas.width /snakePartSize;
var playHeight = canvas.height /snakePartSize;
var snake = [];
var snakeLength = 10;
var snakePosX = 0;
var snakePosY = 0;
var snakeDirX = 0;
var snakeDirY = 0;
var snakeSpeed = 16; // number of frame between moves
var gameOver = true;
var instDrawn = false;
var food = [];
var foodFreq = 60;
var yum = 0;
var yumCol = ["red","orange","yellow"];
function startSnake(){
ctx.fillStyle = "black";
ctx.fillRect(0,0,canvas.width,canvas.height);
snakePosX = Math.floor(playWidth / 2);
snakePosY = Math.floor(playHeight / 2);
snakeDirX = 0;
snakeDirY = 0;
snakeLength = 10;
snake = [];
snakeSpeed = 16;
move(snakePosX,snakePosY); // set first pos
food = [];
score = 0;
}
function testHit(x,y){
if(x < 0 || y < 0 || y >= playHeight || x >= playWidth ){
return true;
}
for(var i = 0; i < snake.length; i ++){
if(snake[i].x === x && snake[i].y === y){
return true;
}
}
}
function testFood(x,y){
for(var i = 0; i < food.length; i ++){
if(food[i].x === x && food[i].y === y){
food.splice(i,1);
i --;
yum = 4;
score += 100;
snakeLength += 1;
if(snakeLength % 4 === 0){
snakeSpeed -= snakeSpeed > 1 ? 1:0;
}
}
}
}
function addFood(){
var x = Math.floor(Math.random() * playWidth );
var y = Math.floor(Math.random() * playHeight );
if(!testHit(x,y)){
food.push({x:x,y:y});
drawFood();
}
}
function move(x,y){
if(testHit(x,y)){
gameOver = true;
return;
}
testFood(x,y);
snake.push({x : x, y : y});
drawSnakeHead();
if(snake.length > snakeLength){
drawSnakeTail();
snake.shift();
}
}
function drawYum(){
for(var i = 0; i < snake.length; i ++){
ctx.fillStyle = yumCol[yum];
ctx.fillRect(snake[i].x*snakePartSize, snake[i].y*snakePartSize, snakePartSize, snakePartSize);
}
}
function drawFood(){
var f = food[food.length-1];
ctx.fillStyle = "green";
ctx.fillRect(f.x*snakePartSize, f.y*snakePartSize, snakePartSize, snakePartSize);
}
function drawSnakeHead(){
var head = snake[snake.length-1];
ctx.fillStyle = "red";
ctx.fillRect(head.x*snakePartSize, head.y*snakePartSize, snakePartSize, snakePartSize);
}
function drawSnakeTail(){
var head = snake[0];
ctx.fillStyle = "black";
ctx.fillRect(head.x*snakePartSize, head.y*snakePartSize, snakePartSize, snakePartSize);
}
var counter = 0;
function update(){
counter += 1;
if(!gameOver){
if(snakeDirX === 0){
if(lastKeyDown === 37){ // left
snakeDirX = -1;
snakeDirY = 0;
}
if(lastKeyDown === 39){ // right
snakeDirX = 1;
snakeDirY = 0;
}
}
if(snakeDirY === 0){
if(lastKeyDown === 38){ // up
snakeDirY = -1;
snakeDirX = 0;
}
if(lastKeyDown === 40){ // down
snakeDirY = 1;
snakeDirX = 0;
}
}
lastKeyDown = 0;
if(counter % foodFreq ===0){
addFood();
}
if(counter % snakeSpeed === 0){
snakePosX += snakeDirX;
snakePosY += snakeDirY;
score += 1;
move(snakePosX ,snakePosY);
}
if((counter % 2 === 0) && yum > 0){
yum -= 1;
drawYum();
}
scoreE.textContent = "Score : "+ score;
}
if(gameOver){
if(!instDrawn){
instDrawn = true;
ctx.fillStyle = "white";
ctx.font = "32px arial";
ctx.textAlign = "center";
ctx.fillText("GAME OVER",canvas.width /2, canvas.height /2);
ctx.font = "16px arial";
ctx.fillText("Press a direction key to start.",canvas.width /2, canvas.height /2+32);
}
if(lastKeyDown >= 37 && lastKeyDown <= 40){
gameOver = false;
instDrawn = false;
counter = -1;
startSnake();
}
}
requestAnimationFrame(update);
}
requestAnimationFrame(update);
startSnake();

Javascript Html5 canvas problems

This is a game I am making. I cant figure out why it is not working. I have the JS fiddle here http://jsfiddle.net/aa68u/4/
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);
// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "http://6269-9001.zippykid.netdna-cdn.com/wp-content/uploads/2013/11/Woods-Wallpaper.jpg";
// Ship image
var shipReady = false;
var shipImage = new Image();
shipImage.onload = function () {
shipImage = true;
};
shipImage.src = "http://s29.postimg.org/3widtojzn/hero.png";
// Astroid image
var astroidReady = false;
var astroidImage = new Image();
astroidImage.onload = function () {
astroidReady = true;
};
astroidImage.src = "http://s29.postimg.org/4r4xfprub/monster.png";
// Game objects
var ship = {
speed: 256;
};
var astroid = {};
var health = 100;
window.keyStates = {};
addEventListener('keydown', function (e) {
keyStates[e.keyCode || e.key] = true;
e.preventDefault();
e.stopPropagation();
}, true);
addEventListener('keyup', function (e) {
keyStates[e.keyCode || e.key] = false;
e.preventDefault();
e.stopPropagation();
}, true);
var reset = function () {
astroid.width = 10;
astroid.height = 10;
astroid.x = 32 + (Math.random() * (canvas.width - 64));
astroid.y = 32 + (Math.random() * (canvas.height - 64));
ship.speed = 256;
for (var p in keyStates) keyStates[p]= false;
};
// Update game objects
function update (modifier) {
if (keyStates[38] ==true) { // Player holding up
astroid.x -= ship.speed * modifier;
}
if (keyStates[40]==true) { // Player holding down
astroid.x += ship.speed * modifier;
}
if (keyStates[37]==true) { // Player holding left
astroid.y -= ship.speed * modifier;
}
if (keyStates[39]==true) { // Player holding right
astroid.y += ship.speed * modifier;
}
if (astroid.width) < 200{
astroid.width +=10;
astroid.height += 10;
}
if (astroid.width) > 200{
reset();
}
// Are they touching?
if (keyStates[32] == true && ship.x <= (astroid.x + 32) && astroid.x <= (ship.x + 32) && ship.y <= (astroid.y + 32) && astroid.y <= (ship.y + 32)) {
monstersCaught += 1;
reset();
}
};
// Draw everything
var render = function () {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
if (shipReady) {
ctx.drawImage(heroImage, hero.x, hero.y);
}
if (astroidReady) {
ctx.drawImage(monsterImage, monster.x, monster.y);
}
// Score
ctx.fillStyle = "rgb(250, 250, 250)";
ctx.font = "24px Helvetica";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Your Health: " + health, 32, 32);
};
// The main game loop
var main = function () {
var now = Date.now();
var delta = now - then;
if (delta > 20) delta = 20;
update(delta / 1000);
render();
then = now;
};
// Let's play this game!
reset();
var then = Date.now();
setInterval(main, 1); // Execute as fast as possible
The game is supposed to be a ship(shoe image) that is avoiding astroids that get bigger(ants) but when you move your ship(shoe) stays in the same place and the astroids(ants) move. The ants/astroids also get bigger like you are going close to them.
var ship = {
speed: 256;
};
Remove the ; after the value.
if astroid.width < 200{
and
if astroid.width > 200{
Need parentheses around the if conditions.
The error console is helpful! But now it's just stuck in an infinite loop of monsterImage is not defined. Just... go back, write your code more carefully, and use the error console! It's there for a reason!

javascript timer runs too fast on android in webview

EDIT: I found a solution. See answers below
I wrote a game in html5. I have the game running using setTimeout(func,1000/FPS). I then recall the timeout, hence making a loop. (FPS is set to equal 30.) Everything ran fine in chrome on my android phone, but when I put it into a webview on android, the timers ran what looked like 10 times faster than they did in the browser. How can I fix this/why is this happening? Thanks!
<html>
<head>
<title>...</title>
<style>
...
</style>
</head>
<body style="-webkit-user-select:none; cursor:default; margin:0px; padding:0px; overflow:hidden; position : fixed;">
<script>
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 480;
canvas.height = 800;
canvas.style.width = window.innerWidth;
canvas.style.height = window.innerHeight;
canvas.style.float = "left";
//canvas.style.transform = "translate3d(0,0,0)";
document.body.appendChild(canvas);
var started = 0;
var vy = 0;
var startImage = new Image();
startImage.src = "img/start.png";
startImage.onload = function(){
ctx.drawImage(startImage,0,0);
//touchstart
addEventListener("touchstart",function(e) {
if(started == 0){
loadGame();
started = 1;
}else{
vy = -15;
}
},false);
};
var bgImage;
function loadGame(){
bgImage = new Image();
bgImage.src = "img/background.png";
bgImage.onload = function(){
loadPlayer();
};
}
var player;
var playerX = 64;
var playerY = 0;
var playerHeight = 60;
var playerWidth = 76;
var stopTime = false;
var stopFall = false;
function loadPlayer(){
player = new Image();
player.src = "img/hero.png";
player.onload = function() {
loadwalls();
};
}
var walls;
function loadwalls(){
wall = new Image();
wall.src = "img/wall.png";
wall.onload = function() {
loadGameover();
};
}
var gameO;
function loadGameover(){
gameO = new Image();
gameO.src = "img/gameover.png";
gameO.onload = function() {
init();
};
}
var walls = [];
function draw(){
canvas.width = 480;
canvas.height = 800;
ctx.drawImage(bgImage,0,0);
ctx.drawImage(player,playerX,playerY);
for(var i=0;i<walls.length;i++){
if(walls[i][0] > -200){
ctx.drawImage(wall,walls[i][0],walls[i][1]);
ctx.drawImage(wall,walls[i][0],walls[i][1]-839-3.25*playerHeight);
walls[i][0] -= 4;
if((walls[i][1] < 785 || vy < 0) && (walls[i][1] > 15 || vy > 0)){
walls[i][1] += vy;
}
if(vy < 10){
vy += 2;
}
}
if(playerX > walls[i][0]+128-playerWidth && walls[i][2] == 0){
walls[i][2] = 1;
score += 1;
}
if(playerX < walls[i][0]+128 && playerX > walls[i][0]-playerWidth){
if(playerY < walls[i][1]-3.25*playerHeight-5 || playerY > walls[i][1]-playerHeight+5){
gameOver();
}
}
}
}
function drawFall(){
canvas.width = 480;
canvas.height = 800;
ctx.drawImage(bgImage,0,0);
for(var i=0;i<walls.length;i++){
ctx.drawImage(wall,walls[i][0],walls[i][1]);
ctx.drawImage(wall,walls[i][0],walls[i][1]-839-3.25*playerHeight);
}
ctx.scale(1, -1);
ctx.drawImage(player,playerX,-playerY-playerHeight);
ctx.scale(1, -1);
var score = 0;
var highscore = 0;
var state = window.localStorage.getItem("....");
if (state) {
highscore = parseInt(state);
}
var FPS = 30;
function init(){
var time = 0;
var wallTime = 0;
stopTime = false;
stopFall = false;
setTimeout(function (){
if(started == 1){
playerY = playerHeight/2*Math.sin(time)+canvas.width/2+playerHeight;
draw();
time+=0.1;
wallTime += 0.1;
if(time > Math.PI*2){
time = 0;
}
if(wallTime >= 10){
walls.push([480,Math.random()*(800-3.25*playerHeight*2)+5*playerHeight,0]);
wallTime = 0;
}
}
if(!stopTime){
setTimeout(arguments.callee, 1000/FPS);
}
},1000/FPS);
setTimeout(function(){
var advert=document.getElementById("ad");
advert.style.top = "0";
},1000);
document.getElementById('iad').src += '';
}
function gameOver(){
stopTime = true;
var fallSpeed = 5;
var fall = setTimeout(function(){
playerY+=fallSpeed;
fallSpeed += 1;
playerX+=5;
drawFall();
if(playerY>800+50){
stopFall = true;
canvas.width = 480;
canvas.height = 800;
canvas.style.width = window.innerWidth;
canvas.style.height = window.innerHeight;
ctx.drawImage(gameO,0,0);
walls = [];
if(score > highscore){
window.localStorage.setItem(".....", ""+score);
highscore = score;
}
score = 0;
vy = 0;
playerX = 64;
playerY = 0;
started = 0;
var advert=document.getElementById("ad");
advert.style.top = ""+parseInt(canvas.style.height);
}
if(!stopFall){
setTimeout(arguments.callee, 1000/FPS);
}
},1000/FPS);
}
</script>
<div id="ad" style="height:200px; overflow:hidden; position:absolute; top:-200;left:0;"><iframe src="ads/ad.html" scrolling="no" frameBorder="0" id="iad" onload="this.width = window.innerWidth;" height="200"></iframe></div>
</body>
</html>
For some reason, requestAnimationFrame() runs fine on Android, but setTimeout() runs way faster than expected. For anybody else with this issue, and because requestAnimationFrame() is more accurate and efficient than set interval/timeout, just replace all
setTimeout(func,1000/FPS);
with
//it will (try to) run at a constant 60 FPS
requestAnimationFrame(func);

appending images using easeljs and javascript for snake game

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.

Categories