How change the speed of each shape?
I tried to play with pct but I guess this is wrong way:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
window.requestAnimFrame = (function (callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
// shape stuff
var shapes = [];
var points;
// shape#1
points = pointsToSingleArray([{
x: 20,
y: 20
}, {
x: 50,
y: 100
}, {
x: 75,
y: 20
}, {
x: 100,
y: 100
}]);
shapes.push({
width: 20,
height: 10,
waypoints: points,
color: "red"
});
// shape#2
points = pointsToSingleArray([{
x: 0,
y: 0
}, {
x: 180,
y: 0
}, {
x: 180,
y: 180
}, {
x: 0,
y: 180
}, {
x: 0,
y: 0
}, {
x: 100,
y: 80
}]);
shapes.push({
width: 20,
height: 20,
waypoints: points,
color: "blue"
});
// animation stuff
var index = 0;
var fps = 60;
// start animating
animate();
function pointsToSingleArray(points) {
// array to hold all points on this polyline
var allPoints = [];
// analyze all lines formed by this points array
for (var a = 1; a < points.length; a++) { // loop through each array in points[]
// vars for interpolating steps along a line
var dx = points[a].x - points[a - 1].x;
var dy = points[a].y - points[a - 1].y;
var startX = points[a - 1].x;
var startY = points[a - 1].y;
// calc 100 steps along this particular line segment
for (var i = 1; i <= 100; i++) {
var pct = Math.min(1, i * .01);
var nextX = startX + dx * pct;
var nextY = startY + dy * pct;
allPoints.push({
x: nextX,
y: nextY
});
}
}
return (allPoints);
}
function animate() {
setTimeout(function () {
// this flag becomes true if we made any moves
// If true, we later request another animation frame
var weMoved = false;
// clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw all shapes
for (var i = 0; i < shapes.length; i++) {
// get reference to next shape
var shape = shapes[i];
// check if we still have waypoint steps for this shape
if (index < shape.waypoints.length) {
// we're not done, so set the weMoved flag
weMoved = true;
// draw this shape at its next XY
drawShape(shape, index);
} else {
// we're done animating this shape
// draw it in its final position
drawShape(shape, shape.waypoints.length - 1);
}
}
// goto next index XY in the waypoints array
// Note: incrementing by 2 doubles animation speed
index += 2;
// if weMoved this frame, request another animation loop
if (weMoved) {
requestAnimFrame(animate)
};
}, 1000 / fps);
}
function drawShape(shape, waypointIndex) {
var x = shape.waypoints[waypointIndex].x;
var y = shape.waypoints[waypointIndex].y;
ctx.fillStyle = shape.color;
ctx.fillRect(x, y, shape.width, shape.height);
}
Maybe somebody know examples with changing speed, or how to make the code better.
http://jsfiddle.net/4DxLL/ - changing speed
var index = [0, 0];
shapes.push({
width: 20,
height: 10,
waypoints: points,
color: "red",
speed: 10,
});
index[i] += shape.speed;
Related
I created a little game with JavaScript while i am learning it.
I would like to get a count clicker in it. So you can see how many times you have clicked on the canvas before you die. (so it resets right after the 'game over'.
Here is the JS code i have at the moment:
window.addEventListener("load", function () {
//constants
var GAME_WIDTH = 640;
var GAME_HEIGHT = 360;
//keep the game going
var gameLive = true;
//current level
var level = 1;
//enemies
var enemies = [{
x: 100, //x coordinate
y: 100, //y coordinate
speedY: 2, //speed in Y
w: 40, //width
h: 40 //heght
},
{
x: 200,
y: 0,
speedY: 2,
w: 40,
h: 40
},
{
x: 330,
y: 100,
speedY: 3,
w: 40,
h: 40
},
{
x: 450,
y: 100,
speedY: -3,
w: 40,
h: 40
}
];
//the player object
var player = {
x: 10,
y: 160,
speedX: 2.5,
isMoving: false, //keep track whether the player is moving or not
w: 40,
h: 40
};
//the goal object
var goal = {
x: 580,
y: 160,
w: 50,
h: 36
}
// var zonder waarde
var img = {};
var movePlayer = function () {
player.isMoving = true;
}
var stopPlayer = function () {
player.isMoving = false;
}
//grab the canvas and context
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
//event listeners to move player
canvas.addEventListener('mousedown', movePlayer);
canvas.addEventListener('mouseup', stopPlayer);
canvas.addEventListener('touchstart', movePlayer);
canvas.addEventListener('touchend', stopPlayer);
var load = function () {
img.player = new Image();
img.player.src = 'images/ping.png';
img.background = new Image();
img.background.src = 'images/sea.png';
img.enemy = new Image();
img.enemy.src = 'images/enemy.png';
img.goal = new Image();
img.goal.src = 'images/fish.png';
};
//update the logic
var update = function () {
//check if you've won the game
if (checkCollision(player, goal)) {
// leven +1
level++;
// level in console
console.log(level);
// get player back in position
player.x = 10;
player.y = 160;
//increase the speed of the enemies by 1
//increase the speed of the enemies by 1
enemies.forEach(function (enemies) {
if (enemies.speedY > 0) {
enemies.speedY++;
} else {
enemies.speedY--;
}
});
}
//update player
if (player.isMoving) {
player.x = player.x + player.speedX;
}
enemies.forEach(function (element, index) {
//check for collision with player
if (checkCollision(player, element)) {
//stop the game
gameLive = false;
alert('Game Over!');
//reload page
window.location = "";
};
//move enemy
element.y += element.speedY;
//check borders
if (element.y <= 10) {
element.y = 10;
//element.speedY = element.speedY * -1;
element.speedY *= -1;
} else if (element.y >= GAME_HEIGHT - 50) {
element.y = GAME_HEIGHT - 50;
element.speedY *= -1;
}
});
};
//show the game on the screen
var draw = function () {
//clear the canvas
ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
//draw background
ctx.drawImage(img.background, 0, 0);
//draw player
ctx.drawImage(img.player, player.x, player.y);
//draw enemies
enemies.forEach(function (element, index) {
ctx.drawImage(img.enemy, element.x, element.y);
});
//draw goal
ctx.drawImage(img.goal, goal.x, goal.y);
//for seeing the level in canvas
//color points
ctx.fillStyle = "#339900";
//font points
ctx.font = "60px Michroma";
//point shower
ctx.fillText(level, 10, 55);
};
//gets executed multiple times per second
var step = function () {
update();
draw();
if (gameLive) {
window.requestAnimationFrame(step);
}
};
//check the collision between two rectangles
var checkCollision = function (rect1, rect2) {
var closeOnWidth = Math.abs(rect1.x - rect2.x) <= Math.max(rect1.w, rect2.w);
var closeOnHeight = Math.abs(rect1.y - rect2.y) <= Math.max(rect1.h, rect2.h);
return closeOnWidth && closeOnHeight;
}
//initial kick
load();
step();
});
I tried some things out of hand but i couldn't figure it out. Thanks a lot for your help! :)
Kind regards
Add a new variable to increment then within the movePlayer function increment this value. When the game is over you can reset the variable to 0.
For example, below the current level variable add var clickCount = 0;
Then within the movePlayer function add clickCount += 1;
As you are currently reloading the page once the game ends the variable will be reset.
This variable could be output in a simple DIV on the page and does not have to be part of the canvas.
It would be best if you had a working example with the images too. You could do this on https://codesandbox.io/ or https://codepen.io/
UPDATE
Add a DOM element <div id="clickCount">0</div> onto your page. Then replace the movePlayer with the below.
var movePlayer = function () {
clickCount += 1;
player.isMoving = true;
document.getElementById('clickCount').innerHTML = clickCount;
}
This will then update the DIV with the new count, you can then use CSS to position and style the DIV as you want.
Sorry for my english it is not my native language. I hope you understand me.
I made a ball that moves in a specific path around the canvas i define. Everything is going fine and my ball moves correctly, but i notice that when the ball reaches a corner it's speed is lower than it is when it moves straight. Does anyone Knows why this happens?
Here is my code.
Thanks in advance!
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var pathArray = [];
pathArray.push({
x: 150,
y: 100
});
pathArray.push({
x: 1375,
y: 100
});
pathArray.push({
x: 1375,
y: 230
});
pathArray.push({
x: 150,
y: 230
});
pathArray.push({
x: 150,
y: 320
});
pathArray.push({
x: 1375,
y: 320
});
pathArray.push({
x: 1375,
y: 450
});
pathArray.push({
x: 150,
y: 450
});
var polypoints = makePolyPoints(pathArray);
var width = 15;
var height = 30;
var speed = 1 / 2;
var position = 0;
animate();
function animate() {
setTimeout(function() {
requestAnimFrame(animate);
position += speed;
if (position > polypoints.length - 1) {
return;
}
var pt = polypoints[position];
if (pt) {
ctx.save();
ctx.beginPath();
ctx.translate(pt.x, pt.y);
ctx.arc(-width / 2, -height / 2, 12, 0, 2 * Math.PI);
ctx.fillStyle = "#B22222";
ctx.fill();
ctx.restore();
}
}, 1000 / 60);
}
function makePolyPoints(pathArray) {
var points = [];
for (var i = 1; i < pathArray.length; i++) {
var startPt = pathArray[i - 1];
var endPt = pathArray[i];
var dx = endPt.x - startPt.x;
var dy = endPt.y - startPt.y;
for (var n = 0; n <= 200; n++) {
var x = startPt.x + dx * n / 200;
var y = startPt.y + dy * n / 200;
points.push({
x: x,
y: y
});
}
}
return (points);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="myCanvas" width="1515" height="950" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
It's because when your makePolyPoints() function splits the path into points, it always creates 200 points per line, not taking the actual distance into account.
What you wanna do is calculate the distance using pythagoras, and then set the number of points accordingly. I included a speedFactor into the function parameters, so you can fine tune.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var pathArray = [];
pathArray.push({
x: 150,
y: 100
});
pathArray.push({
x: 1375,
y: 100
});
pathArray.push({
x: 1375,
y: 230
});
pathArray.push({
x: 150,
y: 230
});
pathArray.push({
x: 150,
y: 320
});
pathArray.push({
x: 1375,
y: 320
});
pathArray.push({
x: 1375,
y: 450
});
pathArray.push({
x: 150,
y: 450
});
var polypoints = makePolyPoints(pathArray, 5);
var width = 15;
var height = 30;
var speed = 1 / 2;
var position = 0;
animate();
function animate() {
setTimeout(function() {
requestAnimFrame(animate);
position += speed;
if (position > polypoints.length - 1) {
return;
}
var pt = polypoints[position];
if (pt) {
ctx.save();
ctx.beginPath();
ctx.translate(pt.x, pt.y);
ctx.arc(-width / 2, -height / 2, 12, 0, 2 * Math.PI);
ctx.fillStyle = "#B22222";
ctx.fill();
ctx.restore();
}
}, 1000 / 60);
}
function makePolyPoints(pathArray, speedFactor) {
var points = [];
for (var i = 1; i < pathArray.length; i++) {
var startPt = pathArray[i - 1];
var endPt = pathArray[i];
var dx = endPt.x - startPt.x;
var dy = endPt.y - startPt.y;
var distance = Math.sqrt(dx*dx+dy*dy)
var steps = distance/speedFactor
for (var n = 0; n <= steps; n++) {
var x = startPt.x + dx * n / steps;
var y = startPt.y + dy * n / steps;
points.push({
x: x,
y: y
});
}
}
return (points);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="myCanvas" width="1515" height="950" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
I am currently using a piece of code that I have found online for drawing a diagram by a set of angles and lengths, the problem I am having is constructing the array on the fly.
The array that works fine is this
arr = [
{ angle: 0, h: 100 },
{ angle: 45, h: 100 },
{ angle: 90, h: 300 },
{ angle: 135, h: 100 },
{ angle: 180, h: 100 }
];
but I am struggling with the syntax to insert the information into an array to match this format, here is what I have so far but this causes me an error which I am not sure.
for( var i = 1; i < 42;i++) {
arr[i].angle = document.getElementById("1m2mangle"+i).value;
arr[i].h = document.getElementById("1m2mlength"+i).value};
}
Any suggestions would be much appreciated, here is the code for drawing the lines from the input array.
ctx.moveTo(pos.x, pos.y);
pos = getAngle(ctx, pos.x, pos.y, arr[i].angle, arr[i].h);
ctx.lineTo(pos.x, pos.y);
Thanks
--Revised Function --
function draw<%response.write(counter1)%>() {
var arr = [];
for( var i = 1; i < 42;) {
alert(document.getElementById("<%response.write(counter1)%>m2mangle"+i)).value);
arr.push({
angle: document.getElementById("<%response.write(counter1)%>m2mangle1").value, h: document.getElementById("<%response.write(counter1)%>m2mlength1").value});
i++;
}
var canvas = document.getElementById('curtainCanvas<%response.write(counter1)%>');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.font = "20px Georgia";
var pos = { x: 15, y: 15 };
ctx.fillText(1,10,10);
for (var i = 0; i < arr.length; i++) {
// alert(pos.x);
ctx.moveTo(pos.x, pos.y);
pos = getAngle(ctx, pos.x, pos.y, arr[i].angle, arr[i].h);
ctx.lineTo(pos.x, pos.y);
ctx.fillText(i+2,pos.x, pos.y);
}
ctx.stroke();
}
}
This is how it's done with JS:
for( var i = 1; i < 42;i++) {
arr.push({
angle: document.getElementById("1m2mangle"+i).value,
h: document.getElementById("1m2mlength"+i).value
});
}
WE're basically pushing a new object into the end of the array, which is the structure you need in your case.
I can reshape polygon with mouse by using code in snippet. After drawing polygon, users can change shape by moving points. But I want to modify shape without changing line lengths. The points will change as possible but length of the lines will remain the same.
How can I do this?
var canvas, ctx;
var canvasIsMouseDown = false;
var radius = 6;
var pointIndex = -1;
var points = [
{ x: 10, y: 10 },
{ x: 100, y: 50 },
{ x: 150, y: 100 },
{ x: 60, y: 110 },
{ x: 30, y: 160 }
];
function start() {
canvas = document.getElementById("cnPolygon");
ctx = canvas.getContext("2d");
canvas.addEventListener("mousemove", canvasMouseMove);
canvas.addEventListener("mousedown", canvasMouseDown);
canvas.addEventListener("mouseup", canvasMouseUp);
draw();
}
function canvasMouseMove(ev) {
if (!canvasIsMouseDown || pointIndex === -1) return;
points[pointIndex].x = ev.pageX - this.offsetLeft;
points[pointIndex].y = ev.pageY - this.offsetTop;
draw();
}
function canvasMouseDown(ev) {
canvasIsMouseDown = true;
var x = ev.pageX - this.offsetLeft;
var y = ev.pageY - this.offsetTop;
pointIndex = -1;
var dist;
for (var i = 0; i < points.length; i++) {
dist = Math.sqrt(Math.pow((x - points[i].x), 2) + Math.pow((y - points[i].y), 2));
if (dist <= radius) {
pointIndex = i;
break;
}
}
}
function canvasMouseUp(ev) {
canvasIsMouseDown = false;
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (var i = 0; i < points.length; i++) {
ctx.lineTo(points[i].x, points[i].y);
}
ctx.closePath();
ctx.stroke();
for (var i = 0; i < points.length; i++) {
ctx.beginPath();
ctx.arc(points[i].x, points[i].y, radius, 0, Math.PI * 2);
ctx.stroke();
}
}
document.addEventListener("DOMContentLoaded", start);
<canvas id="cnPolygon" width="200" height="200" style="border:solid 1px silver"></canvas>
Take a look at this
var canvas, ctx;
var canvasIsMouseDown = false;
var radius = 3;
var pointIndex = -1;
var points = [
{ x: 10, y: 10 },
{ x: 100, y: 50 },
{ x: 150, y: 100 },
{ x: 60, y: 110 },
{ x: 30, y: 160 }
];
// PHYSICS START ----------------
var stiffness = 0.25 // defines how elastic the contrainst should be
var oscillations = 10 // defines how many iterations should be made, more iterations mean higher precision
function getAngle(x1,y1,x2,y2){
return Math.atan2(y2-y1,x2-x1) + Math.PI/2
}
function getConstraintPos(tx,ty,ox,oy,dist){
var rot = getAngle(tx,ty,ox,oy)
var x = tx+Math.sin(rot)*dist
var y = ty-Math.cos(rot)*dist
return [x,y]
}
function applyContraintForce(point,pos){
point.x += (pos[0] - point.x)*stiffness
point.y += (pos[1] - point.y)*stiffness
}
function defineDistances(){
for (var i = 0; i < points.length; i++) {
var next_point = points[(i+1)%points.length]
points[i].distance = Math.sqrt(Math.pow((next_point.x - points[i].x), 2) + Math.pow((next_point.y - points[i].y), 2))
}
}
function updateContraints(){
// forward pass
for (var i=0;i<points.length;i++)
{
if(i==pointIndex) continue
var j = (+i+1)%points.length
var pos = getConstraintPos(points[j].x,points[j].y,points[i].x,points[i].y,points[i].distance)
applyContraintForce(points[i],pos)
}
//backward pass
for (var i=points.length-1;i>=0;i--)
{
if(i==pointIndex) continue
var j = (i-1)
j = j<0 ? points.length+j : j
var pos = getConstraintPos(points[j].x,points[j].y,points[i].x,points[i].y,points[j].distance)
applyContraintForce(points[i],pos)
}
}
// PHYSICS END ----------------
function start() {
canvas = document.getElementById("cnPolygon");
ctx = canvas.getContext("2d");
canvas.addEventListener("mousemove", canvasMouseMove);
canvas.addEventListener("mousedown", canvasMouseDown);
canvas.addEventListener("mouseup", canvasMouseUp);
defineDistances()
draw();
}
function canvasMouseMove(ev) {
if (!canvasIsMouseDown || pointIndex === -1) return;
points[pointIndex].x = ev.pageX - this.offsetLeft;
points[pointIndex].y = ev.pageY - this.offsetTop;
for(var i=0;i<oscillations;i++){
updateContraints()
}
draw();
}
function canvasMouseDown(ev) {
canvasIsMouseDown = true;
var x = ev.pageX - this.offsetLeft;
var y = ev.pageY - this.offsetTop;
pointIndex = -1;
var dist;
for (var i = 0; i < points.length; i++) {
dist = Math.abs(Math.sqrt(Math.pow((x - points[i].x), 2) + Math.pow((y - points[i].y), 2)));
if (dist <= radius) {
pointIndex = i;
break;
}
}
}
function canvasMouseUp(ev) {
canvasIsMouseDown = false;
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (var i = 0; i < points.length; i++) {
ctx.lineTo(points[i].x, points[i].y);
}
ctx.closePath();
ctx.stroke();
for (var i = 0; i < points.length; i++) {
ctx.beginPath();
ctx.arc(points[i].x, points[i].y, radius * 2, 0, Math.PI * 2);
ctx.stroke();
}
}
document.addEventListener("DOMContentLoaded", start);
<canvas id="cnPolygon" width="500" height="300" style="border:solid 1px silver"></canvas>
What this does is calculate the angle between two given points and applies a force based on that angle and the distance delta. The force applied is multiplied by the stiffness.
This has to be done forwards (point A -> point B) and backwards (point A <- point B) in order to account for the differences between the last to first point in the chain.
NOTE this is not 100% accurate. The accuracy can be increased by the iterations count, but as #bhspencer already pointed out, there are cases where this is impossible, simply because of geometry.
I want to modify the platformer game that I find in codepen.
http://codepen.io/loktar00/pen/JEdqD
the original is like the below image.
I want to change it to be:
I want to zoom in the viewport to player and making a camera-like view where I could scroll a level within a canvas element.
Like this game http://www.html5quintus.com/quintus/examples/platformer_full/
The viewport and camera is tracking the player.
This is my code:
(function () {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = 100,
height = 100,
player = {
x: width / 2,
y: height - 15,
width: 5,
height: 5,
speed: 3,
velX: 0,
velY: 0,
jumping: false,
grounded: false
},
keys = [],
friction = 0.8,
gravity = 0.3;
var boxes = [];
// player's position
var playerX = 20;
var playerY = 20;
// how far offset the canvas is
var offsetX = 0;
var offsetY = 0;
// dimensions
boxes.push({
x: 0,
y: 0,
width: 10,
height: height
});
boxes.push({
x: 0,
y: height - 2,
width: width,
height: 50
});
boxes.push({
x: width - 10,
y: 0,
width: 50,
height: height
});
boxes.push({
x: 120,
y: 10,
width: 80,
height: 80
});
boxes.push({
x: 170,
y: 50,
width: 80,
height: 80
});
boxes.push({
x: 220,
y: 100,
width: 80,
height: 80
});
boxes.push({
x: 270,
y: 150,
width: 40,
height: 40
});
canvas.width = width;
canvas.height = height;
function update() {
// check keys
if (keys[38] || keys[32] || keys[87]) {
// up arrow or space
if (!player.jumping && player.grounded) {
player.jumping = true;
player.grounded = false;
player.velY = -player.speed * 2;
}
}
if (keys[39] || keys[68]) {
// right arrow
if (player.velX < player.speed) {
player.velX++;
offsetX--;
}
}
if (keys[37] || keys[65]) {
// left arrow
if (player.velX > -player.speed) {
player.velX--;
offsetX++;
}
}
player.velX *= friction;
player.velY += gravity;
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = "black";
ctx.beginPath();
player.grounded = false;
for (var i = 0; i < boxes.length; i++) {
ctx.rect(boxes[i].x, boxes[i].y, boxes[i].width, boxes[i].height);
var dir = colCheck(player, boxes[i]);
if (dir === "l" || dir === "r") {
player.velX = 0;
player.jumping = false;
} else if (dir === "b") {
player.grounded = true;
player.jumping = false;
} else if (dir === "t") {
player.velY *= -1;
}
}
if(player.grounded){
player.velY = 0;
}
player.x += player.velX;
player.y += player.velY;
ctx.save();
ctx.translate(offsetX, offsetY);
// clear the viewport
ctx.clearRect(-offsetX, -offsetY, 100,100);
ctx.fill();
ctx.fillStyle = "red";
ctx.fillRect(player.x, player.y, player.width, player.height);
ctx.fillRect(playerX-offsetX, playerY-offsetY, 8, 8);
// draw the other stuff
var l = boxes.length;
for (var i = 0; i < l; i++) {
// we should really only draw the things that intersect the viewport!
// but I am lazy so we are drawing everything here
var x = boxes[i][0];
var y = boxes[i][1];
ctx.fillStyle = 'lightblue';
ctx.fillRect(x, y, 8, 8);
ctx.fillStyle = 'black';
ctx.fillText(x + ', ' + y, x, y) // just to show where we are drawing these things
}
ctx.restore();
requestAnimationFrame(update);
}
function colCheck(shapeA, shapeB) {
// get the vectors to check against
var vX = (shapeA.x + (shapeA.width / 2)) - (shapeB.x + (shapeB.width / 2)),
vY = (shapeA.y + (shapeA.height / 2)) - (shapeB.y + (shapeB.height / 2)),
// add the half widths and half heights of the objects
hWidths = (shapeA.width / 2) + (shapeB.width / 2),
hHeights = (shapeA.height / 2) + (shapeB.height / 2),
colDir = null;
// if the x and y vector are less than the half width or half height, they we must be inside the object, causing a collision
if (Math.abs(vX) < hWidths && Math.abs(vY) < hHeights) {
// figures out on which side we are colliding (top, bottom, left, or right)
var oX = hWidths - Math.abs(vX),
oY = hHeights - Math.abs(vY);
if (oX >= oY) {
if (vY > 0) {
colDir = "t";
shapeA.y += oY;
} else {
colDir = "b";
shapeA.y -= oY;
}
} else {
if (vX > 0) {
colDir = "l";
shapeA.x += oX;
} else {
colDir = "r";
shapeA.x -= oX;
}
}
}
return colDir;
}
document.body.addEventListener("keydown", function (e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
keys[e.keyCode] = false;
});
window.addEventListener("load", function () {
update();
});
<h3>A, D or Arrow keys to move, W or space to jump</h3>
<canvas id="canvas"></canvas>
But this does not work.
You can use the same code that you had in the codepen, but add a couple lines in the load event, before the first update().
Let's say something like:
window.addEventListener("load", function () {
ctx.scale(2,2);
ctx.translate(-100,-100);
update();
});
This will zoom by two times and center on new coordinates, BUT keep in mind that you have to do it yourself if you want to re-center when the player is going out of the view.
As a partial way of doing this, you can check if the player moved and translate the canvas using the opposite values of player.velX and player.velY. Something like:
var playerMoved = false;
if (keys[38] || keys[32] || keys[87]) {
playerMoved = true;
//...Other stuff
}
if (keys[39] || keys[68]) {
playerMoved = true;
//...Other stuff
}
if (keys[37] || keys[65]) {
playerMoved = true;
//...Other stuff
}
if (playerMoved) {
// You still need to check quite a few things, like
// the player being out of bounds, the view not translating
// when x less than or bigger then a specific value, and so on
ctx.translate(-player.velX, -player.velY);
}
This is not a complete solution because that would require quite some code, but it should get you started.