how to changes the background time in html canvas AI - javascript

enter image description here this is a picture of AI gaming project.
My problem is this.in this project has two times.one is daytime and night time.
this project works successfully.but I need instead of changes color of daytime and night time change a picture. I have day time and night time picture how will I insert those I tried many ways but I couldn't please help someone to do this
window.onload = init();
function init()
{
cs = document.getElementById("canvas3");
ctx = cs.getContext("2d"); // set context as 2D
ctx.rect(10,50,900,700);
ctx.fill();
// Coordinates and speed of player
var x1 = 580;
var y1 = 200;
var SPEED = 5;
// initialize visibility duration count
var count = 0;
//initialize time of day
timeofday = "Day Time";
hourcount = 0;
// initialize enemy state
EnemyCanSee = false;
enemyCOLOR = "green";
// Handle keyboard controls
var keysDown = {};
addEventListener("keydown", function (e){
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function (e) {
delete keysDown[e.keyCode];
}, false);
//create a player to control
function player(x1, y1)
{
//ctx.fillStyle = "green";
//ctx.fillRect(x1, y1, 40, 40);
var demoImage = new Image(); // make image object
demoImage.src = "player.jpg"; // set image path
ctx.drawImage(demoImage, x1, y1, 40, 40);
}
function drawObstacle()
{
var demoImage = new Image(); // make image object
demoImage.src = "wall.jpg"; // set image path
ctx.drawImage(demoImage, 500, 150, 50, 200);
}
function drawEnemy()
{
ctx.beginPath();
ctx.arc(100,230,50,0,2*Math.PI,false);
ctx.fillStyle= enemyCOLOR;
ctx.fill();
}
function drawDungeonDoor()
{
var demoImage = new Image(); // make image object
demoImage.src = "door.jpg"; // set image path
ctx.drawImage(demoImage, 300, 250, 50, 60);
}
function clear()
{
ctx.fillStyle = "rgb(255, 255, 255)";
ctx.beginPath();
ctx.rect(0, 0, 800, 500);
ctx.closePath();
ctx.fill();
}
function drawStuff()
{
if (timeofday == "Night Time")
{
ctx.fillStyle = "black";
ctx.rect(10,50,900,700);
ctx.fill();
}
player(x1,y1);
drawObstacle();
drawDungeonDoor();
drawEnemy();
ctx.fillStyle = "red";
ctx.font = "20px Arial";
ctx.fillText(timeofday, 100, 70);
}
function checkVisibility()
{
if ((y1<150)|| (y1>350)||(x1<500))
EnemyCanSee = true;
else
EnemyCanSee = false;
}
function shootPlayer()
{
ctx.lineWidth = 5;
ctx.strokeStyle = 'yellow';
ctx.moveTo(100,230);
ctx.lineTo(x1,y1);
ctx.stroke();
var demoImage = new Image(); // make image object
demoImage.src = "explode.jpg"; // set image path
ctx.drawImage(demoImage, x1-50, y1-50, 160, 160);
}
function updateStuff()
{
if (hourcount>240) //12 hours scaled up to 1200
timeofday = "Night Time";
if (hourcount>480) //12 hours scaled up to 1200
{
timeofday = "Day Time";
hourcount = 0;
}
checkVisibility();
// control the ninja using arrow keys
if (38 in keysDown && y1>0)
{
y1 = y1-SPEED;
}
if (40 in keysDown && y1<460)
{
y1 = y1+SPEED;
}
if (37 in keysDown && x1>0)
{
x1 = x1-SPEED;
}
if (39 in keysDown && x1<600)
{
x1 = x1+SPEED;
}
if (EnemyCanSee == true && timeofday == "Day Time")
{
enemyCOLOR = "red";
count = count + 1;
}
else
{
enemyCOLOR = "green";
count = 0;
}
if (count > 60) //player was visible for few seconds
{
shootPlayer();
}
}
function GameLoop()
{ clear();
updateStuff();
drawStuff();
hourcount = hourcount+1;
setTimeout(GameLoop, 1000 / 50);
}
GameLoop();
}

if (timeofday == "Night Time")
{
ctx.fillStyle = "black";
ctx.rect(10,50,900,700);
ctx.fill();
}
there is no else condition for day time
you can also use image with condition using
var background = new Image();
background.src = "http://i.imgur.com/yf6d9SX.jpg";
background.onload = function(){
ctx.drawImage(background,0,0);
}

Related

Prevent player from "flying"

I am currently trying to make an endless runner game, and I've just finished making the jumping mechanics. However, if the player were to hold the up arrow key, or press it before they touched the ground, they are able to mimic the ability to "fly". I am not sure how to prevent them from "flying" if they have not touched the ground yet. If anyone has any ideas, please let me know. My code is below:
let ctx = document.querySelector("canvas").getContext("2d");
// Screen
ctx.canvas.height = 512;
ctx.canvas.width = 512;
// Images
let bg = new Image;
bg.src = "./Background.png";
let fl = new Image;
fl.src = "./Floor.png";
// Player
let y = 256;
let speed = 2.5;
let pl = new Image;
pl.src = "./Idle.png";
pl.onload = function() {
ctx.drawImage(pl, 0, y);
};
// Jumping
let UP = false;
// Ducking
let DOWN = false;
document.onkeydown = function(e) {
if (e.keyCode == 38) UP = true;
if (e.keyCode == 40) DOWN = true;
};
document.onkeyup = function(e) {
if (e.keyCode == 38) UP = false;
if (e.keyCode == 40) DOWN = false;
};
// Frames
function update() {
// Clear
ctx.clearRect(0, 0, 512, 512);
// Background
ctx.drawImage(bg, 0, 0);
// Floor
ctx.drawImage(fl, 0, 384);
ctx.drawImage(fl, 128, 384);
ctx.drawImage(fl, 256, 384);
ctx.drawImage(fl, 384, 384);
// UP
if (UP) {
if (y > 100) {
ctx.drawImage(pl, 0, y -= speed);
} else {
UP = false;
};
} else if (!UP) {
if (y < 256) {
ctx.drawImage(pl, 0, y += speed);
} else {
ctx.drawImage(pl, 0, y);
};
};
// DOWN
if (DOWN) {
pl.src = "./Duck.png";
} else if (!DOWN) {
pl.src = "./Idle.png";
};
};
setInterval(update, 10);

How to set a delay in each penalty shot in HTML5 JS Canvas football penalty game

I am trying to make a simple football penalty game using HTML5/JS Canvas. The aim is to make a game where you control the goal keeper and you have three attempts to save the ball.
I have most of the functionality done, I have a score system and collision detection.
Currently I have a delay on the first attempt. I am however finding difficulty in adding a delay before the ball is shot into the goal in the second and third attempt.
I am using the method requestAnimationFrame() to paint my shapes on my canvas. If there is still attempts available, the ball is positioned to its original location but then there is no delay and fires the ball immediately.
Any advice ? Thanks!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Football</title>
<style>
* { padding: 0; margin: 0; }
canvas { background: #a5bd7b; display: block; margin: 0 auto; }
</style>
</head>
<body>
<canvas id="myCanvas" width="300" height="250"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext("2d");
//Sets the original position of the ball
var x = canvas.width/2;
var y = 50;
// Defines values that will be added to the position of x and y values
// List of possible values for the x position
var x_options = [3.5, 3, 2.5, 2, 1.5, 1, 0.5, 0, -0.5, -1, -1.5, -2, -2.5, -3, -3.5];
// Gets a random value from the x_options array
var dx = x_options[Math.floor(Math.random() * x_options.length)];
var dy = 5;
var ballRadius = 10;
// Defines the height and width of the goal
var goal_height = 40;
var goal_width = 200
// Defines the height, width and position of goalie
var goalieHeight = 20;
var goalieWidth = 40;
var goalieX = (canvas.width-goalieWidth)/2;
var goalieY = (canvas.height - goal_height) - 30;
// Set to false by default
var rightPressed = false;
var leftPressed = false;
var goalkeeper_blocked = 0;
var goalkeeper_missed = 0;
var attempts_left = 3;
var attempt1 = true;
var attempt2 = false;
var attempt3 = false;
var footBall = {
shapes : {
ball: function (){
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2, false);
ctx.fillStyle = "red";
ctx.fill();
ctx.closePath();
},
goal : function (){
ctx.beginPath();
ctx.rect((canvas.width - goal_width) / 2 , canvas.height - goal_height, goal_width, goal_height);
ctx.strokeStyle = "#000000";
ctx.stroke();
ctx.closePath();
},
goalie : function(){
ctx.beginPath();
ctx.rect(goalieX, goalieY, goalieWidth, goalieHeight);
ctx.fillStyle = "#666666";
ctx.fill();
ctx.closePath();
},
score : function(){
ctx.font = "16px Arial";
ctx.fillStyle = "#ffffff";
ctx.fillText("Score: "+goalkeeper_blocked, 8, 20);
},
missed : function(){
ctx.font = "16px Arial";
ctx.fillStyle = "#ffffff";
ctx.fillText("Missed: "+goalkeeper_missed, 8, 40);
},
attempts : function(){
ctx.font = "16px Arial";
ctx.fillStyle = "#ffffff";
ctx.fillText("Attempts left: "+attempts_left, canvas.width-110, 20);
}
},
controls : {
keyDownHandler : function (e){
if(e.keyCode == 39) {
rightPressed = true;
}
else if(e.keyCode == 37) {
leftPressed = true;
}
},
keyUpHandler : function(e){
if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 37) {
leftPressed = false;
}
}
},
calculateScore : function(){
if(goalkeeper_missed > goalkeeper_blocked){
alert("GAME OVER! YOU HAVE LOST!");
document.location.reload();
} else {
alert("GAME OVER! YOU HAVE WON!");
document.location.reload();
}
},
animateBall : function (){
// Sets a delay of 3 second before it shoots
setTimeout(function(){
x += dx;
y += dy;
}, 3000);
},
resetShapePositions : function(){
//Sets the original position of the ball
x = canvas.width/2;
y = 50;
// Sets a new shooting path
dx = x_options[Math.floor(Math.random() * x_options.length)];
dy = 5;
// Resets the goalie to the middle
goalieX = (canvas.width-goalieWidth)/2;
},
draw : function(){
// This ensures that the ball doesn't leave a trail
// Clears the canvas of this shape each frame
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draws shapes on the canvas
footBall.shapes.ball();
footBall.shapes.goal();
footBall.shapes.goalie();
footBall.shapes.score();
footBall.shapes.missed();
footBall.shapes.attempts();
// adds values to the balls x and y position every frame
footBall.animateBall();
// Ball hits the goal
if(y + dy > canvas.height - goal_height) {
attempts_left--;
goalkeeper_missed++;
if (!attempts_left){
footBall.calculateScore();
}
else {
footBall.resetShapePositions();
}
} // Ball saved by goalie
else if (x > goalieX && x < goalieX + goalieWidth && y + dy > goalieY - ballRadius){
attempts_left--;
goalkeeper_blocked++;
if (!attempts_left){
footBall.calculateScore();
}
else {
footBall.resetShapePositions();
}
}
// makes paddle move left and right and only within the canvas
if(rightPressed && goalieX < canvas.width-goalieWidth) {
goalieX += 7;
}
else if(leftPressed && goalieX > 0) {
goalieX -= 7;
}
requestAnimationFrame(footBall.draw);
}
}
footBall.draw();
// Defines what functions are fired when keydown or keyup event triggers
document.addEventListener("keydown", footBall.controls.keyDownHandler, false);
document.addEventListener("keyup", footBall.controls.keyUpHandler, false);
</script>
</body>
</html>
Add some properties to football that control if/when a shot is occuring:
// is a shot in progress?
isShooting:false,
// the time when next shot will start
nextShotTime:0,
// delay between shots
delayUntilNextShot:3000,
Then in the animation loop, use these properties to appropriately delay the next shot:
If isShooting, process the shot,
If not isShooting, see if the required delay has elapsed between shots. If yes, set isShooting=true,
When the goalie blocks or misses the shot, set isShooting=false and set nextShotTime=currentTime+delayUntilNextShot,
Example code and a Demo:
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext("2d");
//Sets the original position of the ball
var x = canvas.width/2;
var y = 50;
// Defines values that will be added to the position of x and y values
// List of possible values for the x position
var x_options = [3.5, 3, 2.5, 2, 1.5, 1, 0.5, 0, -0.5, -1, -1.5, -2, -2.5, -3, -3.5];
// Gets a random value from the x_options array
var dx = x_options[Math.floor(Math.random() * x_options.length)];
var dy = 5;
var ballRadius = 10;
// Defines the height and width of the goal
var goal_height = 40;
var goal_width = 200
// Defines the height, width and position of goalie
var goalieHeight = 20;
var goalieWidth = 40;
var goalieX = (canvas.width-goalieWidth)/2;
var goalieY = (canvas.height - goal_height) - 30;
// Set to false by default
var rightPressed = false;
var leftPressed = false;
var goalkeeper_blocked = 0;
var goalkeeper_missed = 0;
var attempts_left = 3;
var attempt1 = true;
var attempt2 = false;
var attempt3 = false;
var footBall = {
// is a shot in progress
isShooting:false,
// time when next shot will run
nextShotTime:0,
// delay until next shot will run
delayUntilNextShot:3000,
shapes : {
ball: function (){
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2, false);
ctx.fillStyle = "red";
ctx.fill();
ctx.closePath();
},
goal : function (){
ctx.beginPath();
ctx.rect((canvas.width - goal_width) / 2 , canvas.height - goal_height, goal_width, goal_height);
ctx.strokeStyle = "#000000";
ctx.stroke();
ctx.closePath();
},
goalie : function(){
ctx.beginPath();
ctx.rect(goalieX, goalieY, goalieWidth, goalieHeight);
ctx.fillStyle = "#666666";
ctx.fill();
ctx.closePath();
},
score : function(){
ctx.font = "16px Arial";
ctx.fillStyle = "#ffffff";
ctx.fillText("Score: "+goalkeeper_blocked, 8, 20);
},
missed : function(){
ctx.font = "16px Arial";
ctx.fillStyle = "#ffffff";
ctx.fillText("Missed: "+goalkeeper_missed, 8, 40);
},
attempts : function(){
ctx.font = "16px Arial";
ctx.fillStyle = "#ffffff";
ctx.fillText("Attempts left: "+attempts_left, canvas.width-110, 20);
}
},
controls : {
keyDownHandler : function (e){
if(e.keyCode == 39) {
rightPressed = true;
}
else if(e.keyCode == 37) {
leftPressed = true;
}
},
keyUpHandler : function(e){
if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 37) {
leftPressed = false;
}
}
},
calculateScore : function(){
if(goalkeeper_missed > goalkeeper_blocked){
alert("GAME OVER! YOU HAVE LOST!");
document.location.reload();
} else {
alert("GAME OVER! YOU HAVE WON!");
document.location.reload();
}
},
resetShapePositions : function(){
//Sets the original position of the ball
x = canvas.width/2;
y = 50;
// Sets a new shooting path
dx = x_options[Math.floor(Math.random() * x_options.length)];
dy = 5;
// Resets the goalie to the middle
goalieX = (canvas.width-goalieWidth)/2;
},
drawField: function(){
// This ensures that the ball doesn't leave a trail
// Clears the canvas of this shape each frame
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draws shapes on the canvas
footBall.shapes.ball();
footBall.shapes.goal();
footBall.shapes.goalie();
footBall.shapes.score();
footBall.shapes.missed();
footBall.shapes.attempts();
},
draw : function(currentTime){
// makes paddle move left and right and only within the canvas
if(rightPressed && goalieX < canvas.width-goalieWidth) {
goalieX += 7;
}
else if(leftPressed && goalieX > 0) {
goalieX -= 7;
}
// draw the scene
footBall.drawField();
// delay until next shot time is due
if(!footBall.isShooting){
// time has elapsed, let's shoot again
if(currentTime>footBall.nextShotTime){
footBall.isShooting=true;
}else{
// time has not elapsed, just request another loop
requestAnimationFrame(footBall.draw);
return;
}
}
// adds values to the balls x and y position every frame
x += dx;
y += dy;
// Ball hits the goal
if(y + dy > canvas.height - goal_height) {
// end the shot
footBall.isShooting=false;
// delay the next shot
footBall.nextShotTime=currentTime+footBall.delayUntilNextShot;
attempts_left--;
goalkeeper_missed++;
if (!attempts_left){
footBall.calculateScore();
}
else {
footBall.resetShapePositions();
}
} // Ball saved by goalie
else if (x > goalieX && x < goalieX + goalieWidth && y + dy > goalieY - ballRadius){
// end the shot
footBall.isShooting=false;
// delay the next shot
footBall.nextShotTime=currentTime+footBall.delayUntilNextShot;
attempts_left--;
goalkeeper_blocked++;
if (!attempts_left){
footBall.calculateScore();
}
else {
footBall.resetShapePositions();
}
}
requestAnimationFrame(footBall.draw);
}
}
footBall.drawField();
footBall.nextShotTime=footBall.delayUntilNextShot;
requestAnimationFrame(footBall.draw);
// Defines what functions are fired when keydown or keyup event triggers
document.addEventListener("keydown", footBall.controls.keyDownHandler, false);
document.addEventListener("keyup", footBall.controls.keyUpHandler, false);
* { padding: 0; margin: 0; }
canvas { background: #a5bd7b; display: block; margin: 0 auto; }
<canvas id="myCanvas" width="300" height="250"></canvas>

Remove background in canvas game

I am trying to learn JavaScript and found this tutorial:
http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/
But i can not figure out how to remove the background from the game.
Any help with removing the background would be appreciated! :)
Code that affects the background:
// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "images/background.png";
// Draw everything
var render = function () {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
The whole JavaScript file:
http://www.lostdecadegames.com/demos/simple_canvas_game/js/game.js
// 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 = "images/background.png";
// Hero image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
heroReady = true;
};
heroImage.src = "images/hero.png";
// Monster image
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function () {
monsterReady = true;
};
monsterImage.src = "images/monster.png";
// Game objects
var hero = {
speed: 256 // movement in pixels per second
};
var monster = {};
var monstersCaught = 0;
// Handle keyboard controls
var keysDown = {};
addEventListener("keydown", function (e) {
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function (e) {
delete keysDown[e.keyCode];
}, false);
// Reset the game when the player catches a monster
var reset = function () {
hero.x = canvas.width / 2;
hero.y = canvas.height / 2;
// Throw the monster somewhere on the screen randomly
monster.x = 32 + (Math.random() * (canvas.width - 64));
monster.y = 32 + (Math.random() * (canvas.height - 64));
};
// Update game objects
var update = function (modifier) {
if (38 in keysDown) { // Player holding up
hero.y -= hero.speed * modifier;
}
if (40 in keysDown) { // Player holding down
hero.y += hero.speed * modifier;
}
if (37 in keysDown) { // Player holding left
hero.x -= hero.speed * modifier;
}
if (39 in keysDown) { // Player holding right
hero.x += hero.speed * modifier;
}
// Are they touching?
if (
hero.x <= (monster.x + 32)
&& monster.x <= (hero.x + 32)
&& hero.y <= (monster.y + 32)
&& monster.y <= (hero.y + 32)
) {
++monstersCaught;
reset();
}
};
// Draw everything
var render = function () {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
if (heroReady) {
ctx.drawImage(heroImage, hero.x, hero.y);
}
if (monsterReady) {
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("Goblins caught: " + monstersCaught, 32, 32);
};
// The main game loop
var main = function () {
var now = Date.now();
var delta = now - then;
update(delta / 1000);
render();
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;
// Let's play this game!
var then = Date.now();
reset();
main();
Just empty the image source:
bgImage.src='';
Then...
bgImage.onload will never execute,
bgReady will always be false,
if (bgReady){ ctx.drawImage(bgImage, 0, 0); } will never execute,
Your background will remain transparent!

Why is my line not drawing over time?

I am trying to have a line draw to the canvas over a certain amount of time(ten seconds to be exact). I'm able to see that the script is counting to a certain time and then stopping, but I'm not seeing the line being drawn. Can anyone show me what I'm doing wrong?
$(document).ready(function(){
canvas = document.getElementById("test");
ctx = canvas.getContext("2d");
var count = 0;
var start_x = 0;
var start_y = 100;
var end_x = 50;
var end_y = 100;
var counter = setInterval(countNumbers, 1000);
ctx.beginPath();
ctx.moveTo(start_x, start_y);
console.log("Start");
function countNumbers(){
count += 1;
ctx.lineTo((start_x + count), start_y);
console.log(count);
if((start_x == end_x) || (count == 10)){
clearInterval(counter);
console.log("End");
}
}
ctx.lineWidth = 5;
ctx.strokeStyle = "white";
ctx.stroke();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="test"></canvas>
Try to move stroke inside the Interval. Because in your case stroke are called immediately without lineTo data. And after that lineTo are called in interval function and cannot be rendered without stroke.
$(document).ready(function(){
canvas = document.getElementById("test");
ctx = canvas.getContext("2d");
var count = 0;
var start_x = 0;
var start_y = 100;
var end_x = 50;
var end_y = 100;
var counter = setInterval(countNumbers, 1000);
ctx.beginPath();
ctx.moveTo(start_x, start_y);
console.log("Start");
function countNumbers(){
count += 1;
ctx.lineTo((start_x + count), start_y);
console.log(count);
if((start_x == end_x) || (count == 10)){
clearInterval(counter);
console.log("End");
ctx.lineWidth = 5; // <----- move here
ctx.strokeStyle = "white";
ctx.stroke();
}
}
})
Also ensure that you are not drawing white lines on white background
$(document).ready(function(){
canvas = document.getElementById("test");
ctx = canvas.getContext("2d");
var count = 0;
var start_x = 0;
var start_y = 100;
var end_x = 50;
var end_y = 100;
var counter = setInterval(countNumbers, 1000);
ctx.beginPath();
ctx.moveTo(start_x, start_y);
console.log("Start");
ctx.lineWidth = 5;
ctx.strokeStyle = "black";
function countNumbers(){
count += 1;
ctx.lineTo((start_x + count), start_y);
ctx.stroke();
console.log(count);
if((start_x == end_x) || (count == 10)){
clearInterval(counter);
console.log("End");
ctx.strokeStyle = "white";
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="test"></canvas>
I would count down for the step. This will allow you to figure out the step.
I modified your code to allow you to pass parameters into the interval function to minimize global scope variables. Since I passed a reference of the interval into itself, you no longer need to have global variables.
I created two function, the first will create a path and then stroke it. The second one will stroke a sub-line after each tick of the interval. I added a simple check for even-odd to swap between colors.
$(document).ready(function() {
var canvas = $('canvas#test')[0];
var ctx = canvas.getContext('2d');
var count = 10;
var start_x = 50, start_y = 50;
var end_x = 250, end_y = 150;
var delta_x = end_x - start_x, delta_y = end_y - start_y;
var step_x = delta_x / count, step_y = delta_y / count;
canvas.width = 300;
canvas.height = 200;
// Fill canvas with solid black.
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'black';
ctx.fill();
// Kick off the line stroke timer. No more global variables!
var counter = setInterval(function(opts) {
// Pass a reference to the timer into the interval.
strokeLineTimerLive(counter, opts);
}, 500, {
ctx : ctx,
n : count,
x1 : start_x,
y1 : start_y,
x2 : end_x,
y2 : end_y,
dx : step_x,
dy : step_y,
});
// After the interval has ended, the path is finally stroked.
function strokeLineTimer(timer, opts) {
if (!opts.init) {
console.log("Start");
opts.ctx.beginPath();
opts.ctx.moveTo(opts.x1, opts.y1);
opts.ctx.lineWidth = 5;
opts.ctx.strokeStyle = 'white';
opts.init = true;
}
opts.n -= 1;
opts.ctx.lineTo((opts.x1 += opts.dx), (opts.y1 += opts.dy));
console.log(opts.n);
if ((opts.x1 == opts.x2) || (opts.n == 0)){
clearInterval(timer);
opts.ctx.stroke();
console.log("End");
}
}
// After each tick of the interval, a line is stroked.
function strokeLineTimerLive(timer, opts) {
if (!opts.init) {
console.log("Start");
opts.ctx.beginPath();
opts.ctx.moveTo(opts.x1, opts.y1);
opts.ctx.lineWidth = 5;
opts.init = true;
}
opts.n -= 1;
opts.ctx.strokeStyle = opts.n % 2 == 0 ? 'white' : 'red';
opts.ctx.lineTo((opts.x1 += opts.dx), (opts.y1 += opts.dy));
opts.ctx.stroke();
console.log(opts.n);
if ((opts.x1 == opts.x2) || (opts.n == 0)){
clearInterval(timer);
console.log("End");
} else {
opts.ctx.beginPath();
opts.ctx.moveTo(opts.x1, opts.y1);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="test"></canvas>

Sprites not drawing on canvas (Javascript)

I drew 6 sprites (which are squares) and they are suppose to spawn on my canvas after certain amount of seconds (I have a timer) but only one of them is being drawn at 0,0 coordinates for some reason, and even after the certain amount of seconds, none of the sprites are being drawn.
I would really appreciate some help and if you have any questions leave a comment below and i will answer immediately.
You can see the demo here which you will clearly understand what i am talking about.
Or Here is all of my code for Javascirpt:
//Setting the canvas and context
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var keys = []; // contains, for each keyCode, the key status
//================
// CAR Class
//================
//Uploading obstacle car
var carImage = new Image();
carImage.src = "img/Car.png";
function Car(x, y, speed, mod, angle) {
this.x = x; // x center of car
this.y = y; // y center of car
this.speed = speed;
this.mod = mod;
this.angle = angle;
this.listenInput = function(dt) {
if (keys[37]) {
this.x -= this.speed*dt;
}
if (keys[39]) {
this.x += this.speed*dt;
}
};
this.move = function (dt) {
this.x += dt*(this.speed * this.mod) * Math.cos(Math.PI / 180 * this.angle);
this.y += dt*(this.speed * this.mod) * Math.sin(Math.PI / 180 * this.angle);
if (this.y > canvasHeight + 150) {
this.spawn();
}
};
this.draw = function () {
context.save();
context.translate(this.x, this.y);
context.rotate(this.angle* Math.PI / 180);
context.drawImage(carImage, -(carImage.width / 2), -(carImage.height / 2));
context.restore();
if (this.x > context.canvas.width){
context.beginPath();
context.fillStyle = "red";
context.font = "50px Verdana";
context.fillText("Out of bounds! Get Back!", 100, 100);
}
if (this.x < 0){
context.beginPath();
context.fillStyle = "red";
context.font = "50px Verdana";
context.fillText("Out of bounds! Get Back!", 100, 100);
}
};
this.testCollision = function(other) {
dx = (Math.abs(other.x - this.x));
dy = (Math.abs(other.y - this.y));
da = (carImage.width / 2);
db = (carImage.height);
if (dx < da && dy < db) {
this.mod = 0;
}
};
}
//================
//ENTER: USER CAR
//================
var userCar = new Car(450, canvasHeight - 100, 4/16, -1, -90);
//=========================
//Properties for score keep
//=========================
var score;
var startTime;
var gameOver;
var spaceBarPressed = false;
//=========================
// Launch the game
//=========================
setupKeys();
setupGame () ;
var gameTime=Date.now();
gameLoop();
//=====================
//ENTER: OBSTACLE CARS
//=====================
var obstacleCar1;
var obstacleCar2;
var obstacleCar3;
var obstacleCar4;
var obstacleCar5;
var obstacleCar6;
// ================
//Starting game
// ================
function setupGame () {
obstacleCar1 = new Car(100, 10, 5, 2.9, 90);
obstacleCar2 = new Car(300, 10, 5, 2.9, 90);
obstacleCar3 = new Car(450, 10, 5, 2.9, 90);
obstacleCar4 = new Car(600, 10, 5, 2.9, 90);
obstacleCar5 = new Car(750, 10, 5, 2.9, 90);
obstacleCar6 = new Car(900, 10, 5, 2.9, 90);
gameOver = false;
startTime = Date.now();
score = 0;
}
//=========================
//Properties for score keep
//=========================
var score;
var startTime;
var gameOver;
var spaceBarPressed = false;
//=========================
// Launch the game
//=========================
setupGame();
gameLoop();
//===========================
//Draw Final and Elasped Time
//===========================
function drawElapsedTime() {
context.save();
context.fillStyle = "black";
context.font = "30px Verdana";
context.fillText(parseInt((Date.now() - startTime) / 1000) + " secs", canvas.width - 110, 40);
context.restore();
}
function drawFinalScore() {
context.save();
context.fillStyle = "black";
context.font = "30px Verdana";
context.fillText("Game Over: " + score + " secs", 368, 100);
context.font = "12px Verdana";
context.fillText("Press space to restart", 450, 150);
context.restore();
}
//========================
//All game draw properties
//========================
function gameLoop() {
requestAnimationFrame(gameLoop);
context.clearRect(0, 0, canvas.width, canvas.height);
var now=Date.now();
var dt = now-gameTime;
if (dt>16) dt=16;
gameTime+=dt;
if (gameOver) {
drawFinalScore();
if (spaceBarPressed) {
setupGame();
}
return;
}
obstacleCar1.move();
obstacleCar1.draw();
obstacleCar1.testCollision(userCar);
//Spawn obstacle cars at different times
if (parseInt((Date.now() - startTime) / 1000) >= 3){
obstacleCar2.move();
obstacleCar2.testCollision(userCar);
obstacleCar2.draw();
}
if (parseInt((Date.now() - startTime) / 1000) >= 5){
obstacleCar3.move();
obstacleCar3.testCollision(userCar);
obstacleCar3.draw();
}
if (parseInt((Date.now() - startTime) / 1000) >= 7){
obstacleCar4.move();
obstacleCar4.testCollision(userCar);
obstacleCar4.draw();
}
if (parseInt((Date.now() - startTime) / 1000) >= 10){
obstacleCar5.move();
obstacleCar5.testCollision(userCar);
obstacleCar5.draw();
}
if (parseInt((Date.now() - startTime) / 1000) >= 13){
obstacleCar6.move();
obstacleCar6.testCollision(userCar);
obstacleCar6.draw();
}
//ULTIMATE MODE increase speed for all cars
if (parseInt((Date.now() - startTime) / 1000) >= 15){
obstacleCar1.speed = 9;
obstacleCar2.speed = 9;
obstacleCar3.speed = 9;
obstacleCar4.speed = 9;
obstacleCar5.speed = 9;
obstacleCar6.speed = 9;
}
//Display ULTIMATE MODE When it starts
if (parseInt((Date.now() - startTime) / 1000) >= 15 && parseInt((Date.now() - startTime) / 1000) <= 19){
context.beginPath();
context.fillStyle = "red";
context.font = "50px Verdana";
context.fillText("ULTIMATE MODE!", 100, 100);
}
if (obstacleCar1.mod === 0) {
score = parseInt((Date.now() - startTime) / 1000);
gameOver = true;
spaceBarPressed = false;
}
if (obstacleCar2.mod === 0) {
score = parseInt((Date.now() - startTime) / 1000);
gameOver = true;
spaceBarPressed = false;
}
if (obstacleCar3.mod === 0) {
score = parseInt((Date.now() - startTime) / 1000);
gameOver = true;
spaceBarPressed = false;
}
if (obstacleCar4.mod === 0) {
score = parseInt((Date.now() - startTime) / 1000);
gameOver = true;
spaceBarPressed = false;
}
if (obstacleCar5.mod === 0) {
score = parseInt((Date.now() - startTime) / 1000);
gameOver = true;
spaceBarPressed = false;
}
if (obstacleCar6.mod === 0) {
score = parseInt((Date.now() - startTime) / 1000);
gameOver = true;
spaceBarPressed = false;
}
userCar.draw();
userCar.listenInput(dt);
drawElapsedTime();
}
//========================
// Keys handling
//========================
function setupKeys() {
var listenedKeys = [32, 37, 38, 39, 40];
function keyUpHandler(event) {
var keyCode = event.keyCode;
if (listenedKeys.indexOf(keyCode) == -1) return;
keys[keyCode] = false;
}
function keyDownHandler(event) {
var keyCode = event.keyCode;
if (listenedKeys.indexOf(keyCode) == -1) return;
keys[keyCode] = true;
if (keyCode == 32) {
spaceBarPressed = true;
}
event.preventDefault();
}
//Event listeners for keys
window.addEventListener("keydown", keyDownHandler, false);
window.addEventListener("keyup", keyUpHandler, false);
}
Also, if you need my html, i will give it immediately
Thanks!
In function function gameLoop() you should call obstacleCar1.move() with parameter dt, like so:
obstacleCar1.move(dt)
Otherwise it is not defined in obstacleCar1.move(), which leads to obstacleCar1.x not being defined.

Categories

Resources