Square is falling down faster on each confirmed game over alert - javascript

I have square in canvas which goes up when user clicks the canvas.Otherwise falls down.When square hits the ground,Game Over alert appears and expects action from user.If confirmed by user ,game starts again but problem here is ,starts to fall always faster when user wants to play again.Here my JS code below.How can I make its falling down speed constant as same as first always?
var c = document.getElementById("gameCanvas");
var ctx = c.getContext("2d");
var recWidth,recHeight,xPos,yPos;
var gameStarted=false;
boxInitializer();
function startGame(){
this.gameStarted=true;
init();
}
function boxInitializer(){
this.recWidth = 100;
this.recHeight = 100;
this.xPos = (document.getElementById("gameCanvas").width/2) - (recWidth/2);
this.yPos = (document.getElementById("gameCanvas").height/2) - (recHeight/2);
ctx.fillRect(xPos,yPos,recWidth,recHeight);
console.log('XPos:'+xPos+'YPos:'+yPos);
}
function init(){
if(gameStarted){
const myVar=250;
this.c.addEventListener('click', Up,false);
setInterval(Down,myVar);
console.log(myVar);
setInterval(obstacleGenerator,2000);
function obstacleGenerator(){
console.log("Obstacle generated");
}
function drawSquare(){
this.ctx.fillRect(this.xPos,this.yPos,this.recWidth,this.recHeight);
}
function clearSquare(){
this.ctx.clearRect(this.xPos,this.yPos,this.recWidth,this.recHeight);
}
function Up()
{
clearSquare();
yPos-=40;
drawSquare();
}
function Down()
{
clearSquare();
this.yPos+=30;
console.log(yPos);
drawSquare();
if(this.yPos>=830){
this.gameStarted=false;
GameOver();
}
}
function GameOver(){
if (confirm("GAME OVER!")) {
clearSquare();
boxInitializer();
startGame();
} else {
}
}
}
}
JS Fiddle : https://jsfiddle.net/qmz3186h/

Here you need to clear your gameStarted Down interval on gameOver
you can have a variable to hold interval, and clear same in Game over function
var interval; // initialize at top
interval = setInterval(Down,myVar); // replace with this in `if(gameStarted)` loop
clearInterval(interval ) // clear interval on confirm("GAME OVER!")

Related

keyIsPressed to write on canvas where mouse is clicked p5js

I am working on a function which enables users to write onto screen where mouse has been clicked however there are a few problems.
Firstly: keyIsPressed is executed multiple times making each key appear more than once with a single click.
Secondly: It will only allow for a single letter to be printed before the mouseX and mouseY are set back to -1.
Here is my code:
function setup() {
createCanvas(400, 400);
var startMouseX = -1;
var startMouseY = -1;
var drawing = false;
}
function draw() {
background(220);
if(mouseIsPressed)
{
startMouseX = mouseX;
startMouseY = mouseY;
drawing = true;
}
else if(keyIsPressed)
{
textSize(20);
text(key,startMouseX,startMouseY);
startMouseX += textWidth(key);
}
else{
drawing = false;
startMouseX = -1;
startMouseY = -1;
}
}
Any help would be appreciated thanks
I think the approach with the 'drawing' variable works.
But instead of drawing the new letter in draw you can use the keyTyped() function. In the same manner you could use mouseMoved() to reset the 'drawing' variable
var drawing = true;
function setup() {
createCanvas(400, 400);
}
function keyTyped() {
if (drawing) text(key, mouseX, mouseY);
drawing = false;
}
function mouseMoved() {
drawing = true;
}
my solution:
let drawing = false;
let drawMouseX = -1;
let drawMouseY = -1;
function setup() {
createCanvas(400, 400);
background("white");
}
function keyTyped(){
if(!drawing){
drawing = true;
drawMouseX = mouseX;
drawMouseY = mouseY;
}
text(key, drawMouseX, drawMouseY)
drawMouseX += textWidth(key);
}
function mouseMoved(){
drawing = false;
}
This makes it so the things you type are permanently on the canvas. Is this what you wanted? if not, it would be a lot harder.

P5js: why is my bg framerate not refreshing properly?

I have 2 sets of code in here. One is the simple bounce off code. The other is a function. I've tried to make it a function but it doesn't seem to be working properly.
The bg framerate doesn't clear in the sense that a string of balls show rather than a ball bouncing and animating.
if(this.y_pos > 400) this condition doesn't seem to be working even tho it works when it is drawn in the draw function.
var sketch = function (p) {
with(p) {
p.setup = function() {
createCanvas(800, 600);
// x_pos = 799;
// y_pos = 100;
// spdx = -random(5,10);
// spdy = random(12,17);
};
p.draw = function() {
background(0);
// fill(255);
// ellipse(x_pos,y_pos,50);
// x_pos += spdx;
// y_pos += spdy;
// if(y_pos > 400)
// {
// spdy *= -1;
// }
// for( var i = 0; i < 10; i++)
avalance(799, 100, random(5,10), random(12,17));
};
function avalance(x, y, spdx, spdy)
{
this.x_pos = x;
this.y_pos = y;
this.spdx = spdx;
this.spdy = spdy;
this.x_pos = 799;
this.y_pos = 100;
this.spdx = 1;
this.spdy = 1;
this.movement = function()
{
this.x_pos += -spdx;
this.y_pos += spdy;
if(this.y_pos > 400)
{
this.spdy *= -1;
}
}
this.draw = function()
{
this.movement();
this.drawnRox();
}
this.drawnRox = function()
{
fill(255);
ellipse(this.x_pos,this.y_pos,50);
}
}
}
};
let node = document.createElement('div');
window.document.getElementById('p5-container').appendChild(node);
new p5(sketch, node);
body {
background-color:#efefef;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.js"></script>
<div id="p5-container"></div>
Let's address both issues:
The draw() function is called for each new frame and in it you call avalance which creates a new ball. To fix that you need to
Create a global variable let ball; out of setup() and draw() so that you can reuse that later;
In setup create a new ball and assign it to your ball variable: ball = new avalance(799, 100, random(5,10), random(12,17));
In draw() you want to update the ball and that's what its own draw() function does (I would advise renaming it update() for example, to avoid confusion with the p5 specific draw() function). So you just need to call ball.draw() in draw().
This creates a ball which moves but still don't respect your 400px limit.
The issue is that in movement() you add spdx and spdy to the position but when the ball crosses the limit you update this.spdy, so you need to update the function with this code:
this.x_pos += -this.spdx;
this.y_pos += this.spdy;
And you should be good! Here is a code pend with your code working as you intend.
Also as a bonus advise: You probably want to use some p5.Vector objects to store positions, speeds and accelerations it really makes your code easier to read and to use. You could also rename your function Avalance (capital A) to show that you actually use a class and that this function shouldn't be called without new.
As #statox suggested, do new avalance(799, 100, random(5,10), random(12,17)) in the setup() section and call draw of the ball in draw() section.
You can test the code below by clicking "Run code snippet".
var sketch = function (p) {
with(p) {
var ball;
p.setup = function() {
createCanvas(800, 600);
ball = new avalance(799, 100, random(5,10), random(12,17));
};
p.draw = function() {
background(0);
ball.draw();
};
function avalance(x, y, spdx, spdy)
{
function movement ()
{
x += -spdx;
y += spdy;
if (y > height || y < 0)
{
spdy *= -1;
}
if (x > width || x < 0)
{
spdx *= -1;
}
}
this.draw = function()
{
movement();
drawnRox();
}
function drawnRox ()
{
fill(255);
ellipse(x,y,50);
}
}
}
};
let node = document.createElement('div');
window.document.getElementById('p5-container').appendChild(node);
new p5(sketch, node);
body {
background-color:#efefef;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.js"></script>
<div id="p5-container"></div>

Run canvas animation and video synchronously

I want to animate stuff on a canvas using the window.requestanimationframe() method on top of two video (e.g. for highlighting important stuff in both videos). Currently, the animation runs and after that, the videos start playing together. So how can I execute everything (both videos and canvas animation) simultaneously?
class Animation {
constructor(canvas, data) {
this.canvas = document.getElementById(canvas);
this.ctx = this.canvas.getContext('2d');
this.data = data;
this.start = 0;
this.counter = 0;
this.running = false;
this.draw = function(){
console.log(this);
console.log("Draw");
if(!document.querySelector('video').playing){
// init
this.ctx.clearRect(0, 0, 300, 300); // clear canvas
// get data
var in_video_data = this.data['in_video'];
// draw CircleLineTimeSeries
for (var i=0; i<in_video_data.length; i++){
var item = in_video_data[i];
// if counter in phase intervall
if (this.counter >= item['start'] && this.counter <= item['end']){
console.log(item);
if (item['object'] == 'CircleLineTimeSeries'){
this.visualizeCircleLine(item['raw_kps'][0][this.counter],
item['raw_kps'][1][this.counter]);
}
}
}
// Increase time variable
this.counter += 1;
}
if (this.running){
window.requestAnimationFrame(this.draw.bind(this));
}
}
}
visualizeCircleLine(kps0, kps1){
this.ctx.beginPath();
this.ctx.moveTo(kps0[0], kps0[1]);
this.ctx.lineTo(kps1[0], kps1[1]);
this.ctx.stroke();
}
play(){
this.running = true;
window.requestAnimationFrame(this.draw.bind(this));
}
pause(){
this.running = false;
}
}
The code for running the video and the canvas animation:
/**
* Event handler for play button
*/
function playPause(){
if (running){
running = false;
animation.pause();
video0.pause();
video1.pause();
} else {
running = true;
animation.play();
video0.play();
video1.play();
}
}
Thank you in advance :)
As #Kaiido noted, you have to listen for updates in current time of the video. There is respective media event - timeupdate. Furthermore you should have a list of key frames of the video when to show your animation. Whenever timeupdate event fires, check the current time for reaching some key frame and, if so, notify your requestanimationframe callback to run animation via some shared variable.

Javascript canvas "game". Hero mooves only one time

Im trying to make simple game in canvas. I made animation for hero using setTimeout() function. I check pressed keys with function moove(e):
Everything works pretty fine when i press leftarrow or rightarrow for the first time, but then hero doesnt moove. Any recomendations to the code is appreciated.
var cns = document.getElementById("can");
cns.height = 600;
cns.width = 300;
var ctx = cns.getContext("2d");
var hero = new Image();
hero.src = "images/hero.png";
hero.onload = function() {
ctx.drawImage(hero, 120, 570);
hero.xx = 120;
hero.yy = 570;
};
var intervalL, intervalR, intervalLL, intervalRR;
var keys = [];
function moove(e) {
keys[e.keyCode] = (e.type == "keydown");
if (keys[37]) {
clearTimeout(intervalR);
clearTimeout(intervalRR);
goLeft(hero);
} else {
clearTimeout(intervalL);
clearTimeout(intervalLL);
}
if (keys[39]) {
clearTimeout(intervalL);
clearTimeout(intervalLL);
goRight(hero);
} else {
clearTimeout(intervalR);
clearTimeout(intervalRR);
}
}
function goLeft(img) {
var x = img.xx,
y = img.yy;
function f() {
ctx.clearRect(img.xx, img.yy, img.width, img.height);
ctx.drawImage(img, x, y);
img.xx = x;
img.yy = y;
x -= 1.2;
if (x < -35) {
x = cns.width;
}
}
if (!intervalL) {
intervalL = setTimeout(function run() {
f();
intervalLL = setTimeout(run, 5);
}, 5);
}
}
Function goRight is similiar to goLeft.
Function moove is called in tag body onkeydown='moove(event)' onkeyup='moove(event)'.
You can check the project here: https://github.com/Fabulotus/Fabu/tree/master/Canvas%20game%20-%20dodge%20and%20jump
The reason it doesn't work the first time is because the first time through you are setting the position to its previous position (x = image.xx) then updating x after you draw. You should update the x value x -= 1.2 before calling drawImage
Here is a "working" version of your code:
var cns = document.getElementById("can");
cns.height = 170;
cns.width = 600;
var ctx = cns.getContext("2d");
var hero = new Image();
hero.src = "http://swagger-net-test.azurewebsites.net/api/Image";
hero.onload = function() {
ctx.drawImage(hero, cns.width-10, cns.height/2);
hero.xx = cns.width-10;
hero.yy = cns.height/2;
};
var intervalL, intervalR, intervalLL, intervalRR;
var keys = [];
function goLeft(img) {
function f() {
ctx.beginPath()
ctx.clearRect(0, 0, cns.width, cns.height);
ctx.drawImage(img, img.xx, img.yy);
img.xx--;
if (img.xx < -img.width) {
img.xx = cns.width;
}
}
if (!intervalL) {
intervalL = setTimeout(function run() {
f();
intervalLL = setTimeout(run, 5);
}, 5);
}
}
goLeft(hero)
<canvas id="can">
As you can see the function goLeft has been significantly simplified.
One recommendation: avoid the many setTimeout and clearTimeout instead use one setInterval to call a draw function that takes care of drawing everything on your game, all the other function should just update the position of your gameObjects.

Stopping more than one instance of a function running at a time

I am fairly new to JavaScript and have searched everywhere for an answer to my question and cant seem to find anything related at all. This tells me that I'm missing something with my understanding of how my program works.
I have written a small game where the player navigates through a randomly generated maze using a gameloop that checks keydown events every x milliseconds. The game has a difficulty dropdown menu and then the game is started my clicking a button that calls a function to create a canvas where the game is drawn.
My problem is that when the button is clicked again to create a new maze without reloading the page, the gameloop for the original maze is still running and so key events are registered twice. This is causing some unexpected behavior. It's as though every time the button is clicked, a new instance of the function is running. Is there some way that each time the button is clicked I can set it to stop the previous game function?
var canvas;
var div;
var mazeGenButton;
$(document).ready(function () {
canvas = null;
div = document.getElementById('canvascontainer');;
mazeGenButton = document.getElementById("mazeGenButton");
mazeGenButton.onclick = createInstance;
});
function createInstance() {
if (canvas != null) {
div.removeChild(document.getElementById("myCanvas"));
}
canvas = document.createElement('canvas');
canvas.id = "myCanvas";
canvas.width = 1000;
canvas.height = 1000;
div.appendChild(canvas);
drawMaze();
};
var drawMaze = function () {
//code here to create the game(not posted)
//here is the Key listener - not sure if it's related
var keyState = {};
window.addEventListener('keydown', function (e) {
keyState[e.keyCode || e.which] = true;
}, true);
window.addEventListener('keyup', function (e) {
keyState[e.keyCode || e.which] = false;
}, true);
function gameLoop() {
//left
if (keyState[37] || keyState[65]) {
if (isLegalMove(playerXPos - 1, playerYPos)) {
grid[playerXPos][playerYPos].removePlayerCell();
playerXPos -= 1;
grid[playerXPos][playerYPos].setPlayerCell();
}
}
//right
if (keyState[39] || keyState[68]) {
if (isLegalMove(playerXPos + 1, playerYPos)) {
grid[playerXPos][playerYPos].removePlayerCell();
playerXPos += 1;
grid[playerXPos][playerYPos].setPlayerCell();
}
}
//up
if (keyState[38] || keyState[87]) {
if (isLegalMove(playerXPos, playerYPos - 1)) {
grid[playerXPos][playerYPos].removePlayerCell();
playerYPos -= 1;
grid[playerXPos][playerYPos].setPlayerCell();
}
}
//down
if (keyState[40] || keyState[83]) {
if (isLegalMove(playerXPos, playerYPos + 1)) {
grid[playerXPos][playerYPos].removePlayerCell();
playerYPos += 1;
grid[playerXPos][playerYPos].setPlayerCell();
}
}
drawSurroundingCells();
setTimeout(gameLoop, 50);
}
}

Categories