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);
Related
I am trying to create a duck hunting game using JavaScript. The following code should move duck images from the left side to the right side of the canvas. There doesn't seem to be any syntax error but nothing happens when I test the code. I would appreciate any help.
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var time = Math.round(Math.random()*100);
var ducs = [];
canvas.width = 500;
canvas.height = 500;
document.body.appendChild(canvas);
// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "images/DHbackground.jpg";
// Duck image
var duckReady = false;
var duckImage = new Image();
duckImage.onload = function () {
duckReady = true;
};
duckImage.src = "images/duck.png";
// Handle mouse and keyboard controls
var mouseDown = {
x: 0,
y: 0,
};
function getClickPosition(e) {
mouseDown.x = e.clientX;
mouseDown.y = e.clientY;
};
canvas.addEventListener("click", getClickPosition, false);
var reset = function(){
// To do: resets the game
};
// Draw everything
var render = function () {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
time = time-1;
if (time < 0){
var duck = {
cur_X: 0,
cur_Y: Math.round(Math.random()*500),
final_X: 500,
final_Y: Math.round(Math.random()*500),
};
time = Math.round(Math.random()*100);
ducs.push(duck);
for (var i = 0; i < ducs.Lenght; i++){
ctx.drawImage(duckImage, ducs[i].cur_X, ducs[i].cur_Y);
console.log(ducs[i].cur_X);
}
}
// Score
ctx.fillStyle = "rgb(250, 250, 250)";
ctx.font = "24px Helvetica";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Ducks killed: " + 3, 10, 10);
};
var update = function (modifier) {
for (var i = 0; i < ducs.Lenght; i++){
ducs[i].cur_X = ducs[i].cur_X + Math.floor(((ducs[i].final_X - ducs[i].cur_X)/500)+1);
ducs[i].cur_Y = ducs[i].cur_Y + Math.floor(((ducs[i].final_Y - ducs[i].cur_Y)/500)+1);
if (ducs[i].cur_X > 500){
ducs.splice(i, 1);
}
}
};
// The main game loop
var main = function () {
var now = Date.now();
var delta = now - then;
render();
update(delta / 1000);
then = now;
// Request to do this again ASAP
requestAnimationFrame(main);
};
// Cross-browser support for requestAnimationFrame
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
var then = Date.now();
reset();
main();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Duck Hunt Pandy</title>
</head>
<body>
<script src="js/game.js"> </script>
</body>
</html>
I found a typo:
var update = function (modifier) {
for (var i = 0; i < ducs.Lenght; i++){
Length is spelled incorrectly
First problem. You misspelled length.
for (var i = 0; i < ducs.length; i++){
Second is that you need to make sure to draw the ducks each time the loop runs.
if (time < 0){
var duck = {
cur_X: 0,
cur_Y: Math.round(Math.random()*500),
final_X: 500,
final_Y: Math.round(Math.random()*400),
};
time = Math.round(Math.random()*100);
ducs.push(duck);
}
for (var i = 0; i < ducs.length; i++){
ctx.drawImage(duckImage, ducs[i].cur_X, ducs[i].cur_Y);
console.log(ducs[i].cur_X);
}
third is that you need to remove the ducks when they reach the end (you were checking for 500, but their flight final was 400).
var duck = {
cur_X: 0,
cur_Y: Math.round(Math.random()*500),
final_X: 500,
final_Y: Math.round(Math.random()*400),
};
if (ducs[i].cur_X > 500){
ducs.splice(i, 1);
}
https://jsfiddle.net/ygh6mfpw/6/
Edit: Fix for duck movement
How do I make the shape disappear like the text does? I've gone through the code and they're practically identical except that one is created when the user spins the mouse wheel and the other is created when the user clicks on the screen, but the text disappears after time and the triangle does not. I feel like there's something small I must be missing. Here's the code:
<html>
<head>
<script>
var canvas;
var context;
var triangles = [];
var texts = [];
var timer;
var textSayings = ['Cool!', 'Nice!', 'Awesome!', 'Wow!', 'Whoa!', 'Super!', 'Woohoo!', 'Yay!', 'Yeah!', ':)', ':D'];
function init() {
canvas = document.getElementById('canvas');
context = canvas.getContext("2d");
//resize canvas to fit the window
resizeCanvas();
window.addEventListener('resize', resizeCanvas, false);
window.addEventListener('orientationchange', resizeCanvas, false);
canvas.onwheel = function(event) {
handleWheel(event.clientX, event.clientY);
};
canvas.onclick = function(event) {
handleClick(event.clientX, event.clientY);
}
var timer = setInterval(resizeCanvas, 30);
}
function Triangle(x,y,triangleColor) {
this.x = x;
this.y = y;
this.triangleColor = triangleColor;
this.vx = Math.random() * 80 - 40;
this.vy = Math.random() * 80 - 40;
this.time = 250;
}
function Text(x,y,textColor,word) {
this.x = x;
this.y = y;
this.word = word;
this.textColor = textColor;
this.vx = Math.random() * 20 - 10;
this.vy = Math.random() * 20 - 10;
this.time = 300;
}
function handleWheel(x,y) {
var colors = [[255,0,0],[255,255,255],[0,0,255]];
var triangleColor = colors[Math.floor(Math.random()*colors.length)];
triangles.push(new Triangle(x,y,triangleColor));
for (var i=0; i<triangles.length; i++) {
drawTriangle(triangles[i]);
}
}
function handleClick(x,y) {
var colors = [[255,0,0],[255,255,0],[0,0,255]];
var textColor = colors[Math.floor(Math.random()*colors.length)];
texts.push(new Text(x,y,textColor,pickWord()));
for (var i=0; i<texts.length; i++) {
drawText(texts[i]);
}
}
function timeToFade(time) {
if(time > 100) {
return 1;
}
else {
return time / 100;
}
}
function pickWord() {
return textSayings[Math.floor(Math.random() * textSayings.length)];
}
function drawText(text) {
context.font = "bold 80px Verdana";
var gradient=context.createLinearGradient(0,0,canvas.width,0);
gradient.addColorStop("0","magenta");
gradient.addColorStop("0.25","yellow");
gradient.addColorStop("0.5","lime");
gradient.addColorStop("0.75","aqua");
gradient.addColorStop("1.0","magenta");
context.fillStyle = gradient;
context.fillText(text.word,text.x,text.y);
}
function drawTriangle(triangle) {
context.beginPath();
context.moveTo(triangle.x,triangle.y);
context.lineTo(triangle.x+25,triangle.y+25);
context.lineTo(triangle.x+25,triangle.y-25);
var gradient = context.createLinearGradient(0,0,canvas.width,0);
gradient.addColorStop("0","red");
gradient.addColorStop("0.25","salmon");
gradient.addColorStop("0.5","aqua");
gradient.addColorStop("0.75","lime");
gradient.addColorStop("1.0","orange");
context.fillStyle = gradient;
context.fill();
}
function resizeCanvas() {
canvas.width = window.innerWidth-20;
canvas.height = window.innerHeight-20;
fillBackgroundColor();
for (var i=0; i<triangles.length; i++) {
var t = triangles[i];
drawTriangle(t);
if (t.x + t.vx > canvas.width || t.x + t.vx < 0)
t.vx = -t.vx
if (t.y + t.vy > canvas.height || t.y + t.vy < 0)
t.vy = -t.vy
if (t.time === 0) {
triangles.splice(i,1);
}
t.time -= 3;
t.x += t.vx;
t.y += t.vy;
}
for (var i=0; i<texts.length; i++) {
var te = texts[i];
drawText(te);
if (te.x + te.vx > canvas.width || te.x + te.vx < 0)
te.vx = -te.vx
if (te.y + te.vy > canvas.height || te.y + te.vy < 0)
te.vy = -te.vy
if (te.time === 0) {
texts.splice(i,1);
}
te.time -= 3;
te.x += te.vx;
te.y += te.vy;
}
}
function fillBackgroundColor() {
context.globalCompositeOperation = 'source-over';
context.fillStyle = 'rgba(0, 0, 0, 1)';
context.fillRect(0,0,canvas.width,canvas.height);
context.globalCompositeOperation = 'lighter';
}
window.onload = init;
</script>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
</body>
</html>
It's because the triangle time isn't a multiple of 3, while the text time is so when you check this if statement:
if (t.time === 0) {
triangles.splice(i,1);
}
It's never true.
You can fix this by changing the if statement to:
if (t.time <= 0) {
triangles.splice(i,1);
}
This is actually my fault since it's a bug that was in my previous answer. Sorry about that.
jsfiddle:
https://jsfiddle.net/0rst8def/
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();
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);
}
}
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!