So I have this sprite animation which goes fine when it's not in movement (I need it to go on 20 fps max because if not the animation would be too fast), but when I try to move it across the screen, the movement looks really choppy. Any ideas on how to make the movement smoothly? Increase the framerate works, but I'd like to see if there is another option aside of that.
var canvasA = document.createElement("canvas");
var canvasB = document.createElement("canvas");
var contextA = canvasA.getContext("2d");
var contextB = canvasB.getContext("2d");
canvasA.style.position = "absolute";
canvasB.style.position = "absolute";
var xpos = 0;
var ypos = 0;
var index = 0;
var frameSizeX = 140;
var frameSizeY = 395;
var numFrames = 20;
var drawing_character = false;
var xPosition = 0;
var now, then, elapsed, startTime, fps, fpsInterval;
var fpscounter = setInterval(updatefps, 1000);
var forw = true;
var cfps = 0;
// Pictures
var background = new Image();
background.src = "http://i.imgur.com/3FDB45h.png";
var character = new Image();
character.src = "http://i.imgur.com/tziJajG.png";
function redraw() {
contextB.clearRect(0, 0, canvasB.width, canvasB.height);
contextB.drawImage(background, 0, 0);
}
function drawchar() { // Input= fps max
requestAnimationFrame(drawchar);
now = Date.now();
elapsed = now - then;
if (elapsed > fpsInterval) {
then = now - (elapsed % fpsInterval);
contextA.clearRect(0, 0, 800, 600);
contextA.drawImage(character,
xpos,
ypos,
frameSizeX,
frameSizeY,
xPosition,
0,
frameSizeX,
frameSizeY);
xpos += frameSizeX;
index += 1;
if (index >= numFrames) {
xpos = 0;
ypos = 0;
index = 0;
} else if (xpos + frameSizeX > character.width) {
xpos = 0;
ypos += frameSizeY;
}
cfps++;
}
}
function updatefps() {
document.getElementById("fps").innerHTML = "FPS: " + cfps;
cfps = 0;
}
function aqui() {
prepareCanvas();
setInterval(redraw, 1000/60);
animarchar(20);
setInterval(move, 1);
}
function move() {
if (forw === true) {
xPosition += 1;
if (xPosition === 300){
forw = false;}
} else {
xPosition -= 1;
if (xPosition === 0){
forw = true;}
}
}
function prepareCanvas() {
canvasB.width = 800;
canvasB.height = 600;
canvasA.width = canvasB.width;
canvasA.height = canvasB.height;
//document.body.appendChild(canvasB);
document.body.appendChild(canvasA);
}
function animarchar(fps) {
fpsInterval = 1000 / fps;
then = Date.now();
startTime = then;
drawchar();
}
window.onload = function () {
aqui();
};
Here is a jsFiddle: https://jsfiddle.net/qb171ghf/
Related
I'm trying to create a 2D platformer in JavaScript, I'm getting no errors, but it's not working properly. Pressing the left arrow or the up arrow key does nothing, pressing the right arrow key causes the X-Pos to start incrementing by 1 pixel per tick. I realize this code is long and my 'physics' logic is completely twisted and backwards, but I can't understand anyone's guides on how to add phsyics and velocity and acceleration and gravity and I'm just super confused. I started using JavaScript a week ago and I really have no idea what I'm doing, so any recommendations about any of my code, even things that aren't technically 'problems' would be most appreciated. Thanks guys, you're dope <3
<!DOCTYPE html>
<html>
<meta charset="utf-8"/>
<head>
<title>For The Intended</title>
</head>
<body>
<canvas id="canvas" width="1200" height="800"></canvas>
<!-- <script src="platform.js"></script> -->
<script>
//
//notes
//
//Block collision should come when velocity tries to move, and the x-y position should be player.x + player.velocity to check exactly where the collision will be
//
//
//
//
//
//
//Canvas Settings
var cvs = document.getElementById("canvas");
var ctx = cvs.getContext('2d');
cvs.style = "position:absolute; left: 60%; width: 1200; margin-left: -800px";
//Variables
var platforms = [];
var imgCount = 0
var totalImgCount = 3
var lastUpdate = Date.now();
var keys = {};
//Controls
//Images
var platformImage = new Image();
var playerImage = new Image();
var bgImage = new Image();
platformImage.src = "images/platform.png";
playerImage.src = "images/forward1.png";
playerImage.src = "images/backward1.png";
bgImage.src = "images/bg.png";
platformImage.onload = function() {
imgCount += 1
}
playerImage.onload = function() {
imgCount += 1
}
bgImage.onload = function() {
imgCount += 1
}
//Objects
//Platforms
function Platform(x, y, length, height) {
this.x = x;
this.y = y;
this.length = length;
this.height = height;
platforms.push(this)
}
platform = new Platform(30,30,30,30)
platform = new Platform(40,40,40,40)
//Player
function Player(x, y, gravity, velocityX, velocityY, acceleration, isJumping, direction){
this.x = x
this.y = y
this.gravity = gravity
this.velocityX = velocityX
this.velocityY = velocityY
this.acceleration = acceleration
this.isJumping = isJumping
this.direction = direction
}
player = new Player(200, 600, 0.7, 1, 1, false, "forward")
function jump() {
if (player.isJumping == false) {
player.velocityY = -15;
player.isJumping = true;
}
}
function jumpingHandler() {
if (player.isJumping) {
player.velocityY += player.gravity;
player.y += player.velocityY;
draw();
if (player.y > 600) {
player.y = 600;
player.velocityY = 0;
player.isJumping = false;
}
}
}
*function move(e) {
if(keys[e.keyCode]) {
if(keys[38]) {
jump();
}
if(keys[37]) {
if (player.x > 150){
if (player.acceleration > -5){
player.acceleration = Math.floor(player.acceleration);
player.acceleratoion -= 1
player.acceleration = Math.floor(player.acceleration);
}
player.direction = "backward"
playerImage.src = "images/backward1.png";
}
}
if(keys[39]) {
if (player.x < 1050){
console.log("hey")
if (player.acceleration < 5){
console.log("hey2")
player.acceleration = Math.floor(player.acceleration);
player.acceleration += 1
player.acceleration = Math.floor(player.acceleration);
}
player.direction = "forward"
playerImage.src = "images/forward1.png";
}
}
}
}*
//Game Requirements
function draw() {
if (imgCount == 3) {
for (var i = 0; i < platforms.length; i++) {
ctx.drawImage(platformImage, platforms[i].x, platforms[i].y)
//Do something
}
ctx.drawImage(playerImage, player.x, player.y)
}
}
setInterval(update, 33);
function updateKeys() {
window.onkeyup = function(e) { keys[e.keyCode] = false; move(e)}
window.onkeydown = function(e) { keys[e.keyCode] = true; move(e)}
}
function update() {
if (player.acceleration > 1) {player.acceleration -= 0.2}
if (player.acceleration < 1) {player.acceleration += 0.2}
player.acceleration = Math.floor(player.acceleration);
player.velocityX = player.acceleration
player.x += (player.velocityX)
console.log("Velocity" + player.velocityX)
console.log("Acceleration" + player.acceleration)
console.log("X-Pos" + player.x)
jumpingHandler()
updateKeys()
draw()
}
</script>
</body>
</html>
I wish to create a simple webgame that involves a tiled board. I have a collection of svg's for the background of each square (i.e one for grass, one for stone, one for dirt etc). I also have svg's for items that will be displayed on the layer above the background (such as trees, wood, sword).
I have an in memory database of what the background for each square is and if and which item it contains.
I wish to be able to:
* Zoom in or out
* Scroll left or right
* Scolll up or down
* Have items displayed above the background for that square
Only needs to work in recent versions of modern browsers
What is the best approach for this:
1. Have a canvas object. Get the current zoom, top most XY, canvas width and canvas height. Loop though the squares in the in memory database and print the corresponding SVG's in the correct locations. Each time it is scrolled or zoomed reprint the entire board.
2. Have a div. Get the current zoom, top most XY, canvas width and canvas height. Loop though the squares in the in memory database and create SVG's in the correct locations.
Each time the board scrolls add new SVGs as they become visible, delete SVGs as they move of the board. Translate all the existing SVGs by the appropriate amount.
Each time the board zooms enlarge or shrink all the existing SVGs based on the new zoom level.
3. Some third approach that I am unaware of.
The example below uses two modules svg to load images (Any image format will work) & board which handles panning, zooming & rendering. It also provides an onClick event which will give you an object that describes the tile that has been clicked on.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
display: block;
margin: 30px auto 0px auto;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
var svg = function() {
"use strict";
var svgImages = [];
var areImagesLoaded = true;
var isPageLoaded = false;
addEventListener("load",function() { isPageLoaded = true; isFinished(); });
var exports = {
onload: function() {},
request: null,
get: null
};
function isFinished() {
if (isPageLoaded && areImagesLoaded) {
exports.onload();
}
}
function onSvgError() {
this.isDone = true;
console.warn("SVG " + this.src + " failed to load.");
}
function onSvgLoaded() {
this.isDone = true;
for (var id in svgImages) {
if (!svgImages[id].isDone) {
return;
}
}
areImagesLoaded = true;
isFinished();
}
function request(id,path) {
if (svgImages[id]) {
return;
}
areImagesLoaded = false;
var img = document.createElement("img");
img.onerror = onSvgError;
img.onload = onSvgLoaded;
img.isDone = false;
img.id = id;
img.src = path;
svgImages[id] = img;
}
function get(id) {
return svgImages[id];
}
exports.request = request;
exports.get = get;
return exports;
}();
var board = function() {
"use strict";
var canvasWidth = 0;
var canvasHeight = 0;
var canvas = null;
var ctx = null;
var frameRequested = false;
var tileWidth = 0;
var tileHeight = 0;
var tileTypes = [];
var boardWidth = 0;
var boardHeight = 0;
var board = [];
var hasInitialized = false;
var camera = {
x: 0.0,
y: 0.0,
zoom: 1.0
};
function mapToBoard(x,y) {
var invZoom = 1.0 / camera.zoom;
return [
(x - (canvasWidth >> 1)) * invZoom - camera.x,
(y - (canvasHeight >> 1)) * invZoom - camera.y
];
}
var isMouseDragging = false;
var mouseStartX = 0;
var mouseStartY = 0;
var mouseLastX = 0;
var mouseLastY = 0;
var tileEvent = {
background: "",
foreground: "",
x: 0,
y: 0
};
function onTileSelected(e) {
}
function onMouseDown(e) {
isMouseDragging = true;
var bounds = canvas.getBoundingClientRect();
mouseStartX = mouseLastX = e.clientX - bounds.left;
mouseStartY = mouseLastY = e.clientY - bounds.top;
}
function onMouseUp(e) {
isMouseDragging = false;
var bounds = canvas.getBoundingClientRect()
var x = e.clientX - bounds.left - mouseStartX;
var y = e.clientY - bounds.top - mouseStartY;
var l = Math.sqrt(x * x + y * y);
if (l < 2.0) {
[x,y] = mapToBoard(e.clientX - bounds.left,e.clientY - bounds.top);
if (x > 0 && y > 0 && x < boardWidth * tileWidth && y < boardHeight * tileHeight) {
x = (x / tileWidth) | 0;
y = (y / tileHeight) | 0;
var tile = board[x + y * boardWidth];
tileEvent.background = tile.background;
tileEvent.foreground = tile.foreground;
tileEvent.x = x;
tileEvent.y = y;
} else {
tileEvent.background = "";
tileEvent.foreground = "";
tileEvent.x = -1;
tileEvent.y = -1;
}
onTileSelected(tileEvent);
}
}
function onMouseMove(e) {
if (hasInitialized && isMouseDragging) {
var bounds = canvas.getBoundingClientRect();
var x = e.clientX - bounds.left;
var y = e.clientY - bounds.top;
camera.x += (x - mouseLastX) / camera.zoom;
camera.y += (y - mouseLastY) / camera.zoom;
mouseLastX = x;
mouseLastY = y;
requestDraw();
}
}
function onWheel(e) {
if (Math.sign(e.deltaY) === -1) {
camera.zoom *= 1.1;
} else {
camera.zoom *= 0.9;
}
requestDraw();
}
function draw() {
ctx.fillStyle = "gray";
ctx.fillRect(-canvasWidth >> 1,-canvasHeight >> 1,canvasWidth,canvasHeight);
var _tileWidth = tileWidth * camera.zoom;
var _tileHeight = tileHeight * camera.zoom;
var _ox = camera.x * camera.zoom;
var _oy = camera.y * camera.zoom;
var _x = _ox;
var _y = _oy;
for (var x = 0; x <boardWidth; ++x) {
for (var y = 0; y < boardHeight; ++y) {
var index = x + y * boardWidth;
var tile = board[index];
var background = tileTypes[tile.background];
var foreground = tileTypes[tile.foreground];
if (background) {
ctx.drawImage(
background,
_x,
_y,
_tileWidth,
_tileHeight
);
}
if (foreground) {
ctx.drawImage(
foreground,
_x,
_y,
_tileWidth,
_tileHeight
);
}
_y += _tileHeight;
}
_y = _oy;
_x += _tileWidth;
}
frameRequested = false;
}
function requestDraw() {
if (!frameRequested) {
frameRequested = true;
requestAnimationFrame(draw);
}
}
return {
BACKGROUND: 0,
FOREGROUND: 1,
set canvas(canvasID) {
if (!hasInitialized) {
canvas = document.getElementById(canvasID);
canvas.onmousedown = onMouseDown;
canvas.onmouseup = onMouseUp;
canvas.onmousemove = onMouseMove;
canvas.onwheel = onWheel;
ctx = canvas.getContext("2d");
}
},
set canvasWidth(w) {
if (!hasInitialized && canvas) {
canvasWidth = canvas.width = w;
}
},
set canvasHeight(h) {
if (!hasInitialized && canvas) {
canvasHeight = canvas.height = h;
}
},
set tileWidth(w) {
if (!hasInitialized) {
tileWidth = w;
}
},
set tileHeight(h) {
if (!hasInitialized) {
tileHeight = h;
}
},
set width(w) {
if (!hasInitialized) {
boardWidth = w;
}
},
set height(h) {
if (!hasInitialized) {
boardHeight = h;
}
},
set onTileSelected(callback) {
onTileSelected = callback;
},
get width() {
return boardWidth;
},
get height() {
return boardHeight;
},
get onTileSelected() {
return onTileSelected;
},
defineTileTypes: function(types) {
if (types.length % 2 !== 0) {
return;
}
for (var i = 0; i < types.length; i += 2) {
var id = types[i];
var img = types[i + 1];
tileTypes[id] = img;
}
},
init: function() {
camera.x = -(boardWidth >> 1) * tileWidth;
camera.y = -(boardHeight >> 1) * tileHeight;
ctx.translate(canvasWidth >> 1,canvasHeight >> 1);
board.length = boardWidth * boardHeight;
for (var i = 0; i < board.length; ++i) {
board[i] = {
background: "",
foreground: ""
};
}
hasInitialized = true;
requestAnimationFrame(draw);
},
set: function(type,id,x,y) {
if (hasInitialized
&& tileTypes[id]
&& x > -1
&& x < boardWidth
&& y > -1
&& y < boardHeight) {
var index = x + y * boardWidth;
if (type === this.BACKGROUND) {
board[index].background = id;
} else {
board[index].foreground = id;
}
requestDraw();
}
}
};
}();
void function() {
"use strict";
svg.request("grass","https://i.stack.imgur.com/CkvU7.png");
svg.request("water","https://i.stack.imgur.com/an6a5.png");
svg.onload = function() {
board.canvas = "canvas";
board.canvasWidth = 180;
board.canvasHeight = 160;
board.tileWidth = 25;
board.tileHeight = 25;
board.width = 20;
board.height = 20;
board.defineTileTypes([
"GRASS",svg.get("grass"),
"WATER",svg.get("water")
]);
board.init();
for (var x = 0; x < board.width; ++x) {
for (var y = 0; y < board.height; ++y) {
board.set(board.BACKGROUND,"WATER",x,y);
if (Math.random() > 0.2) {
board.set(board.BACKGROUND,"GRASS",x,y);
} else {
board.set(board.BACKGROUND,"WATER",x,y);
}
}
}
}
board.onTileSelected = function(e) {
if (e.background === "GRASS") {
board.set(board.BACKGROUND,"WATER",e.x,e.y);
} else {
board.set(board.BACKGROUND,"GRASS",e.x,e.y);
}
}
}();
</script>
</body>
</html>
I want to click on one of the floating particles, upon clicking it, I want the particle colour to change from light grey to blue and then fade. Particle quantity is set as 100, as particles are clicked on to fade away particle quantity decreases. I'm unfamiliar with js, just started learning about canvas and particle systems yesterday, this is code from a pen that I've changed a bit and would like to add more changes to by adding the fade onclick event. I know that the particles within canvas are under one variable that defines them altogether, I don't know how to isolate one particle in the canvas to work with as I would need to know it's exact x,y coordinates.
Would I then have to find the coordinates for all 100 particles and add elements to each individual particle- and how do I do this?
$(document).ready(function() {
var PARTICLE_QUANT = 100;
var FPS = 60;
var BOUNCE = -1;
var PARTICLE_COLOR = '#ced4d4';
var ARC_RADIUS = 12;
var Particles = function($element) {
if ($element.length === 0) {
return;
}
this.$element = $element;
this.lastTimeStamp = null;
this.particles = [];
this.init();
};
var proto = Particles.prototype;
proto.init = function() {
this.createChildren()
.layout()
.enable();
};
proto.createChildren = function() {
this.canvas = this.$element[0];
this.context = this.canvas.getContext('2d');
this.canvasWidth = this.canvas.width;
this.canvasHeight = this.canvas.height;
this.lastTimeStamp = new Date().getTime();
return this;
};
proto.layout = function() {
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame;
})();
return this;
};
proto.removeChildren = function() {
this.context = null;
this.canvasWidth = null;
this.canvasHeight = null;
this.lastTimeStamp = null;
return this;
};
proto.enable = function() {
this.createParticleData();
this.renderLoop();
};
proto.createParticleData = function() {
var i = 0;
var l = PARTICLE_QUANT;
for (; i < l; i++) {
this.particles[i] = {};
this.setParticleData(this.particles[i]);
}
};
proto.setParticleData = function(particle) {
particle.x = Math.random() * this.canvasWidth;
particle.y = Math.random() * this.canvasHeight;
particle.vx = (Math.random()) - 0.5;
particle.vy = (Math.random()) - 0.5;
};
proto.update = function() {
var i = 0;
var l = PARTICLE_QUANT;
for (; i < l; i++) {
var particle = this.particles[i];
particle.x += particle.vx;
particle.y += particle.vy;
if (particle.x > this.canvasWidth) {
particle.x = this.canvasWidth;
particle.vx *= BOUNCE;
} else if (particle.x < 0) {
particle.x = 0;
particle.vx *= BOUNCE;
}
if (particle.y > this.canvasHeight) {
particle.y = this.canvasHeight;
particle.vy *= BOUNCE;
} else if (particle.y < 0) {
particle.y = 0;
particle.vy *= BOUNCE;
}
}
};
proto.draw = function() {
var i = 0;
if (!this.context) {
return;
}
this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
this.context.fillStyle = PARTICLE_COLOR;
for (; i < PARTICLE_QUANT; i++) {
var particle = this.particles[i];
this.context.save();
this.context.beginPath();
this.context.arc(particle.x, particle.y, ARC_RADIUS, 0, Math.PI * 2);
this.context.fill();
this.context.restore();
}
};
proto.renderLoop = function() {
requestAnimationFrame(this.renderLoop.bind(this));
this.update();
this.draw();
};
var particles = new Particles($('#js-particles'));
//Everything above works, it is what comes next (below), is this the right approach?
var elem = document.getElementById('js-particles'),
elemLeft = elem.offsetLeft,
elemTop = elem.offsetTop,
context = elem.getContext('2d'),
elements = [];
// Add event listener for `click` events.
elem.addEventListener('click', function(event) {
var x = event.pageX - elemLeft,
y = event.pageY - elemTop;
// Collision detection between clicked offset and element.
elements.forEach(function(element) {
if (y > element.top && y < element.top + element.height && x > element.left && x < element.left + element.width)
});
}, false);
// Add element.
elements.push({
colour: '#05EFFF',
width: 150,
height: 100,
top: 20,
left: 15
});
// Render elements.
elements.forEach(function(element) {
context.fillStyle = element.colour;
context.fillRect(element.left, element.top, element.width, element.height);
});
<canvas id="js-particles" class="particles" width="960" height="960">
<p>text appears if browser doesn 't support canvas</p>
</canvas>
The Problem
I am creating a game that involves dodging projectiles. The player is in control of an image of a ship and I dont want the ship to move exactly together as this looks very unrealistic.
The Question
Is there a way to control how fast the image moves, how can i slow the movemnt of the image down?
The Code
var game = create_game();
game.init();
//music
var snd = new Audio("Menu.mp3");
snd.loop = true;
snd.play();
document.getElementById('mute').addEventListener('click', function (evt) {
if ( snd.muted ) {
snd.muted = false
evt.target.innerHTML = 'mute'
}
else {
snd.muted = true
evt.target.innerHTML = 'unmute'
}
})
function create_game() {
debugger;
var level = 1;
var projectiles_per_level = 1;
var min_speed_per_level = 1;
var max_speed_per_level = 2;
var last_projectile_time = 0;
var next_projectile_time = 0;
var width = 600;
var height = 500;
var delay = 1000;
var item_width = 30;
var item_height = 30;
var total_projectiles = 0;
var projectile_img = new Image();
var projectile_w = 30;
var projectile_h = 30;
var player_img = new Image();
var c, ctx;
var projectiles = [];
var player = {
x: 200,
y: 400,
score: 0
};
function init() {
projectile_img.src = "projectile.png";
player_img.src = "player.png";
level = 1;
total_projectiles = 0;
projectiles = [];
c = document.getElementById("c");
ctx = c.getContext("2d");
ctx.fillStyle = "#ff6600";
ctx.fillRect(0, 0, 500, 600);
c.addEventListener("mousemove", function (e) {
//moving over the canvas.
var bounding_box = c.getBoundingClientRect();
player.x = (e.clientX - bounding_box.left) * (c.width / bounding_box.width) - player_img.width / 2;
}, false);
setupProjectiles();
requestAnimationFrame(tick);
}
function setupProjectiles() {
var max_projectiles = level * projectiles_per_level;
while (projectiles.length < max_projectiles) {
initProjectile(projectiles.length);
}
}
function initProjectile(index) {
var max_speed = max_speed_per_level * level;
var min_speed = min_speed_per_level * level;
projectiles[index] = {
x: Math.round(Math.random() * (width - 2 * projectile_w)) + projectile_w,
y: -projectile_h,
v: Math.round(Math.random() * (max_speed - min_speed)) + min_speed,
delay: Date.now() + Math.random() * delay
}
total_projectiles++;
}
function collision(projectile) {
if (projectile.y + projectile_img.height < player.y + 74) {
return false;
}
if (projectile.y > player.y + 74) {
return false;
}
if (projectile.x + projectile_img.width < player.x + 177) {
return false;
}
if (projectile.x > player.x + 177) {
return false;
}
return true;
}
function maybeIncreaseDifficulty() {
level = Math.max(1, Math.ceil(player.score / 10));
setupProjectiles();
}
function tick() {
var i;
var projectile;
var dateNow = Date.now();
c.width = c.width;
for (i = 0; i < projectiles.length; i++) {
projectile = projectiles[i];
if (dateNow > projectile.delay) {
projectile.y += projectile.v;
if (collision(projectile)) {
initProjectile(i);
player.score++;
} else if (projectile.y > height) {
initProjectile(i);
} else {
ctx.drawImage(projectile_img, projectile.x, projectile.y);
}
}
}
ctx.font = "bold 24px sans-serif";
ctx.fillStyle = "#ff6600";
ctx.fillText(player.score, c.width - 50, 50);
ctx.fillText("Level: " + level, 20, 50);
ctx.drawImage(player_img, player.x, player.y);
maybeIncreaseDifficulty();
requestAnimationFrame(tick);
}
return {
init: init
};
}
https://jsfiddle.net/a6nmy804/4/ (Broken)
Throttle the player's movement using a "timeout" countdown
Create a global var playerFreezeCountdown=0.
In mousemove change player.x only if playerFreezeCountdown<=0.
If playerFreezeCountdown>0 you don't change player.x.
If playerFreezeCountdown<=0 you both change player.x and also set playerFreezeCountdown to a desired "tick timeout" value: playerFreezeCountdown=5. This timeout will cause prevent the player from moving their ship until 5 ticks have passed.
In tick, always decrement playerFreezeCountdown--. This will indirectly allow a change to player.x after when playerFreezeCountdown is decremented to zero or below zero.
I am trying to make this game, you should not collide the falling object. I have the objects falling and I have my black square, but it flashes when I run it and Im not sure how to make the code stop when the two objects collide together.
here is the code that I have so far!
<html>
<body>
<canvas id="canvasRegn" width="600" height="450"style="margin:100px;"></canvas>
<script>
var ctx;
var imgBg;
var imgDrops;
var noOfDrops = 50;
var fallingDrops = [];
function drawBackground(){
ctx.drawImage(imgBg, 0, 0); //Background
}
function draw() {
drawBackground();
for (var i=0; i< noOfDrops; i++)
{
ctx.drawImage (fallingDrops[i].image, fallingDrops[i].x, fallingDrops[i].y); //The rain drop
fallingDrops[i].y += fallingDrops[i].speed; //Set the falling speed
if (fallingDrops[i].y > 480) { //Repeat the raindrop when it falls out of view
fallingDrops[i].y = -25 //Account for the image size
fallingDrops[i].x = Math.random() * 800; //Make it appear randomly along the width
}
}
}
function setup() {
var canvas = document.getElementById('canvasRegn');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
imgBg = new Image();
imgBg.src = "http://www.hamdancommunications.com/HComm/img/wite%20square.png";
setInterval(draw, 36);
for (var i = 0; i < noOfDrops; i++) {
var fallingDr = new Object();
fallingDr["image"] = new Image();
fallingDr.image.src = 'http://s18.postimg.org/o6jpmdf9x/Line1.jpg';
fallingDr["x"] = Math.random() * 800;
fallingDr["y"] = Math.random() * 5;
fallingDr["speed"] = 3 + Math.random() * 5;
fallingDrops.push(fallingDr);
anotherGame();
}
}
}
setup();
function anotherGame(){
var canvas = document.getElementById("canvasRegn");
var ctx = canvas.getContext('2d');
canvas.addEventListener("mousedown", clicked);
canvas.addEventListener("mousemove", moved);
canvas.addEventListener("mouseup", released);
var isclicked = 0;
var square = new Object();
square.color = "black";
square.x = 100;
square.y = 100;
square.w = 50;
square.h = 50;
var offX = 0;
var offY = 0;
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = square.color;
ctx.fillRect(square.x,square.y,square.w,square.h);
}
function game(){
}
function clicked(e){
var x = e.offsetX;
var y = e.offsetY;
if(x >= square.x && x <= square.x + square.w &&
y >= square.y && y <= square.y + square.h){
isclicked = 1;
offX = x - square.x;
offY = y - square.y;
}
}
function moved(e){
if(isclicked == 1){
var x = e.offsetX;
var y = e.offsetY;
square.x = x - offX;
square.y = y - offY;
}
}
function released(e){
var x = e.offsetX;
var y = e.offsetY;
isclicked = 0;
}
var drawtimer = setInterval(draw, 1000/30);
var gametimer = setInterval(game, 1000/10);
}
</script>
</body>
</html>