Preventing javascript from accessing arrays that don't exist - javascript

var gameMap = [ [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1],
[1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1],
[1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1],
[1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1],
[1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] ]
var can = document.getElementById('gc')
var c = can.getContext('2d')
var di = null
var start = [0,0]
var end = [5,5]
document.addEventListener('keydown',keydown)
document.addEventListener('keyup',keyup)
function update() {
c.clearRect(0,0,can.width,can.height)
switch(di) {
case 'left':
start[0] -= 1
end[0] -= 1
break;
case 'up':
start[1] -= 1
end[1] -= 1
break;
case 'right':
start[0] += 1
end[0] += 1
break;
case 'down':
start[1] += 1
end[1] += 1
break;
}
if(start[0]<0) {
start[0] = 0;
}if(start[1]<0) {
start[1] = 0
}if(end[0]>20) {
end[0] = 20
}if(end[1]>20) {
end[1] = 20
}
can.style.border = '1px black solid'
map()
requestAnimationFrame(update)
}
requestAnimationFrame(update)
function keydown(evt) {
switch(evt.keyCode) {
case 37:
di = 'left'
break;
case 38:
di = 'up'
break;
case 39:
di = 'right'
break;
case 40:
di = 'down'
break;
}
}
function keyup() {
di = null
}
function map() {
var mapx = 0
var mapy = 0
for(var i = start[1]; i<end[1]; i++) {
for(var j = start[0]; j<end[0]; j++) {
switch(gameMap[i][j]) {
case 1:
c.fillRect(mapx,mapy,30,30)
break;
case 0:
break;
}
mapx+=30
}
mapy+=30
mapx = 0
}
}
<!doctype html>
<html>
<canvas id='gc' width=200 height=200></canvas>
</html>
We have a tile map
We have a start and an end
And a draw map function.
When the 'di' (direction) goes above the array, the screen will become white.
So I tried to prevent it by making sure that the start[0], start[1], end[0], end[1] does not exceed the array.
However, the drawing was reduced (try to go out of the array in the snippet)
Why is this so?

You need some adjustmets if the pane goes out of range.
The adjustment bases on the pane width or height and the data array size.
I suggest to call requestAnimationFrame first on run time and then after an event.
Mabe you combine map and update actually it is not clear, what they are for, especially because both handles canvas operations.
function update() {
can.style.border = '1px black solid';
map();
}
function keydown(evt) {
di = { 37: 'left', 38: 'up', 39: 'right', 40: 'down' }[evt.keyCode];
switch (di) {
case 'left':
start[0]--;
end[0]--;
break;
case 'up':
start[1]--;
end[1]--;
break;
case 'right':
start[0]++;
end[0]++;
break;
case 'down':
start[1]++;
end[1]++;
break;
}
if (start[0] < 0) {
start[0] = 0;
end[0] = paneWidth;
}
if (start[1] < 0) {
start[1] = 0;
end[1] = paneHeight;
}
if (end[0] > gameMap[0].length) {
start[0] = gameMap[0].length - paneWidth;
end[0] = gameMap[0].length;
}
if (end[1] > gameMap.length) {
start[1] = gameMap.length - paneHeight;
end[1] = gameMap.length;
}
requestAnimationFrame(update);
}
function keyup() {
di = null;
}
function map() {
var mapx = 0,
mapy = 0;
c.clearRect(0, 0, can.width, can.height);
for (var i = start[1]; i < end[1]; i++) {
for (var j = start[0]; j < end[0]; j++) {
switch (gameMap[i][j]) {
case 1:
c.fillRect(mapx, mapy, 30, 30);
break;
case 0:
break;
}
mapx += 30;
}
mapy += 30;
mapx = 0;
}
}
var gameMap = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1],
[1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
],
can = document.getElementById('gc'),
c = can.getContext('2d'),
di = null,
paneWidth = 6,
paneHeight = 6,
start = [0, 0],
end = [paneWidth, paneHeight];
document.addEventListener('keydown', keydown);
document.addEventListener('keyup', keyup);
requestAnimationFrame(update);
<canvas id="gc" width="180" height="180"></canvas>

You have 8 constraints to enforce and are only enforcing 4.
Eg. your code ensures that start[0] >= 0 but it doesn't ensure start[0] < 20.

Related

Making collisions using a map from an array

So i am making a Mario game. The level is made using a map from an array.
const map =
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,];
const size = 128;
I want to make a function which would return the index of the block that is under mario.
I tried writing
export function findBlockUnder(posX: number, posY: number) {
for (let index = 0; index < map.length; index++) {
return map[index]}
}
but this only returns the first number of the array.
If i got this to work, after i would get a number for findBlockUnder, i would write something like this
const floorUnderMario = findBlockUnder(posX, posY)
if (floorUnderMario = "0") {
velocityY += deltaTime * 0.003;
} else {
velocityY = 0;
}
As of right now i have made the 4 outer borders by just using written Y coords
export function findBlockUnder(posX: number, posY: number) {
return 1320
}
export function findBlockAbove(posX: number, posY: number) {
return 1200
}
export function findBlockRight(posX:number, posY:number){
return 3380
}
export function findBlockLeft(posX:number, posY:number){
return -375
}
const bloksPaLabi = findBlockRight(posX, posY);
if (posX>bloksPaLabi){
posX=bloksPaLabi;
}
const bloksPaKreisi = findBlockLeft(posX, posY);
if (posX<bloksPaKreisi){
posX=bloksPaKreisi;
}
So if someone could help me, how would i write a code to get the index of the block under mario? Heres the full code:
level.ts
import bricksSrc from "./images/bricks3.png"
import questionSrc from "./images/question.png"
const siena = document.createElement("img");
siena.src = bricksSrc;
const question = document.createElement("img");
question.src = questionSrc;
const map =
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,];
const size = 128;
export function findBlockUnder(posX: number, posY: number) {
return 1320
}
export function findBlockAbove(posX: number, posY: number) {
return 1200
}
export function findBlockRight(posX:number, posY:number){
return 3380
}
export function findBlockLeft(posX:number, posY:number){
return -375
}
export function MapDraw(context: CanvasRenderingContext2D, marioPosX: number, marioPosY: number) {
const mapOffsetX = marioPosX;
const mapOffsetY = marioPosY;
for (let index = 0; index < map.length; index++) {
const x = (index % 32);
const y = Math.floor(index / 32);
if (map[index] == 1) {
context.drawImage(siena,
x * size - mapOffsetX,
y * size - mapOffsetY,
size,
size);
}
if (map[index] == 2) {
context.drawImage(question,
x * size - mapOffsetX,
y * size - mapOffsetY,
size,
size);
}
// if (map[index] == 0) {
// context.fillStyle = "#ffffff"
// context.fillRect(x * size - mapOffsetX, y * size, size, size);
// }
}
function resize() {
let width = document.documentElement.clientWidth;
let maxWidth = Math.floor(document.documentElement.clientHeight / 0.5625);
if (width > maxWidth) {
width = maxWidth;
}
context.canvas.style.width = width + "px";
context.canvas.style.height = Math.floor(width * 0.5625) + "px";
};
window.addEventListener("resize", resize, { passive: true });
resize();
}
mario.ts
import marioSrc from "./images/8mario_burned.png";
/*
const canvas = document.createElement("canvas2");
document.body.appendChild(canvas);
canvas.style.outline = "1px solid black";
canvas.style.cursor = "none";
*/
const mario = new Image();
mario.src = marioSrc;
export function drawMario(
context: CanvasRenderingContext2D,
centerX: number,
centerY: number,
) {
context.drawImage(mario, centerX, centerY, 100, 100);
}
index.ts
import { drawMario } from "./mario"
import {
MapDraw,
findBlockUnder,
findBlockAbove,
findBlockRight,
findBlockLeft,
} from "./level"
import backSrc from "./images/background.png";
const canvas = document.createElement("canvas");
document.body.appendChild(canvas);
canvas.style.outline = "1px solid black";
canvas.style.cursor = "none";
canvas.width = 2048;
canvas.height = 1024;
const context = canvas.getContext("2d");
context.fillStyle = "rgb(200,120,60)";
const back = new Image();
back.src = backSrc;
function drawback(
context: CanvasRenderingContext2D,
posX: number,
posY: number,
) {
context.drawImage(back, -posX / 10, -posY / 10, canvas.width * 1.5, canvas.height * 1.5);
}
window.requestAnimationFrame(renderLoop);
const sprite2 = document.createElement("img");
sprite2.src =
"https://i.pinimg.com/originals/4b/91/1c/4b911c7d968feeaa993d24c93ddb821e.png";
let posX = 20;
let posY = 20;
let velocityY = 0;
let velocityX = 0;
let previousTime = 0;
let movementStarted = 0;
let wasMoving = false;
let keysPressed: string[] = [];
canvas.oncontextmenu = function (event) {
event.preventDefault();
};
/** NB! `document`, nevis `canvas` */
document.addEventListener("keydown", function (e) {
if (keysPressed.indexOf(e.key) === -1) {
keysPressed.push(e.key);
}
});
document.addEventListener("keyup", function (e) {
let idx = keysPressed.indexOf(e.key);
if (idx > -1) {
keysPressed.splice(idx, 1);
}
});
function renderLoop(time: number) {
context.clearRect(0, 0, canvas.width, canvas.height);
if (previousTime === 0) {
previousTime = time;
}
const deltaTime = time - previousTime;
previousTime = time;
moveMario(deltaTime);
drawback(context, posX, posY);
MapDraw(context, posX, posY);
drawMario(context, 500, 500);
// drawSprite2(time, deltaTime);
window.requestAnimationFrame(renderLoop);
}
function moveMario(deltaTime: number) {
const isMoving = keysPressed.indexOf("ArrowRight") > -1;
if (isMoving) {
posX += deltaTime * 0.8;
}
const isMovingLeft = keysPressed.indexOf("ArrowLeft") > -1;
if (isMovingLeft) {
posX -= deltaTime * 0.8;
}
const gridaZemMario = findBlockUnder(posX, posY)
const isFalling = posY < gridaZemMario;
if (isFalling) {
velocityY += deltaTime * 0.003;
} else {
velocityY = 0;
posY = gridaZemMario;
}
console.log (gridaZemMario)
const bloksVirsMario = findBlockAbove(posX, posY);
const bloksPaLabi = findBlockRight(posX, posY);
if (posX>bloksPaLabi){
posX=bloksPaLabi;
}
const bloksPaKreisi = findBlockLeft(posX, posY);
if (posX<bloksPaKreisi){
posX=bloksPaKreisi;
}
if (posY>410 && posX<100 && posY<600 ){
posY=410;
velocityY=0
}
const isMovingUp = keysPressed.indexOf("ArrowUp") > -1;
if (isMovingUp && !isFalling) {
velocityY = -1.5;
// posY -= deltaTime * 4;
}
posY += deltaTime * velocityY;
}
I am not sure what you try to acchieve so maybe I got your question wrong but your const map is just an array that only has a one dimensional index x.
In your function findBlockUnder(posX: number, posY: number) you pass x and y.
What you might need is a matrix like const map = [][]?
Also everything your findBlockUnder function does is returning the first result of your array because return will leave your for loop early and therefore not loop through the entire array

How to display arrays as visuals in Javascript (e.g. for a maze)

So, I am making a maze, in javascript. I do not know how to display an array (such as 1's and 0's) graphically. The best way is to show you the code:
var maze= [
[0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,0],
[0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,1],
[0,0,1,1,1,0,0,1,1,0,0,1,0,0,0,0,1,0,0,1],
[0,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,0,1],
[0,0,1,0,1,1,0,1,0,0,0,1,1,1,0,0,1,0,0,0],
[0,0,1,1,0,1,1,0,0,0,0,0,0,1,0,0,1,1,1,1],
[0,0,0,1,1,0,1,1,1,1,1,1,0,0,0,0,0,1,0,1],
[0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,1],
];
With the 0's representing walls, and the 1's representing empty space, and 2 meaning the end of the maze, how can I display this as a maze using only javascript? Shall I make each 0 an individual rectangle? How can I do this?
Please do not make fun as I am just starting out.
Here is the code for reference (this is on "coding with chrome", as it was the easiest to use, as I did not have to import anything).
//PART 1 : THE CHARACTER
//Where is the character???
charX=10;
charY=10;
//Draw char
function drawChar(){
draw.circle(charX, charY, 5, "black");
}
//Loop happens at 40 milliseconds
setInterval (loop, 40);
//loop that clears screen
function loop(){
draw.rectangle(0,0, window.innerWidth, window.innerHeight,"white");
drawChar();
}
//Move Character
document.addEventListener("keydown", moveChar);
function moveChar (e) {
if(e.keyCode ==37){
//Left arrow
charX=charX-50;
}
if(e.keyCode== 38){
//Up arrow
charY=charY-50;
}
if(e.keyCode == 39){
//right arrow
charX=charX+50;
}
if(e.keyCode == 40){
//down arrow
charY=charY +50;
}
//PART 1 DONE :-)
//PART 2: Walls
//map of maze
var maze= [
[0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,0],
[0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,1],
[0,0,1,1,1,0,0,1,1,0,0,1,0,0,0,0,1,0,0,1],
[0,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,0,1],
[0,0,1,0,1,1,0,1,0,0,0,1,1,1,0,0,1,0,0,0],
[0,0,1,1,0,1,1,0,0,0,0,0,0,1,0,0,1,1,1,1],
[0,0,0,1,1,0,1,1,1,1,1,1,0,0,0,0,0,1,0,1],
[0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,1],
];
//How can we display this graphically, with the 0 being a wall, and 1 being an empty space?
span {
white-space: pre;
display: inline-block;
width: 24px;
}
<script>
var maze = [
[0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1],
[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1],
[0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1],
[0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1],
];
maze.forEach(function(arr, index) {
arr.forEach(function(path, i) {
var span = document.createElement("span");
if (path === 0) {
span.textContent = " ";
span.style.backgroundColor = "#000";
}
if (path === 1) {
span.textContent = " ";
span.style.backgroundColor = "yellow";
}
if (path === 2) {
span.textContent = "end";
span.style.backgroundColor = "green";
span.style.color = "gold";
}
document.body.appendChild(span)
});
document.body.appendChild(document.createElement("br"))
})
</script>

HTML5 Canvas - Block side collisions on dynamic map

I'm making a platformer game in HTML5 Canvas and I have run into some collision problems. I've been experimenting with numerous collision algorithms but I can't seem to get any to work.
My question:
How can I get the blocks/darker grey squares to stop my ball from passing through it?
Some info about my code:
The map is dynamically generated
I have tried collision algorithms many times
Collision handling is done in the canMoveHere function and returns true or false to the moveAll function, where it is determined if the ball can move to the next square
My code on jsfiddle.net
My code download from Google Drive
My full code:
<html>
<head>
<canvas id ="gameCanvas" width = "500" height = "500" style = "border:1px solid black;"></canvas>
<script>
var canvas, canvasContext;
var framesPerSecond = 30;
var gravity = .2;
var leftKey = false;
var rightKey = false;
const TILE_H = 25;
const TILE_W = 25;
var map = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1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1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
];
var ball = {
`x:250`,
`y:250`,
`radius:10`,
color:"#ff9966",
`velocityX:5`,
`velocityY:1`,
`terminalVel:8`,
draw:function()
{
canvasContext.beginPath();
canvasContext.fillStyle = this.color;
canvasContext.arc(this.x, `this.y`, this.radius, 0, Math.PI * 2, false);
canvasContext.fill();
canvasContext.closePath();
}
};
document.addEventListener("keydown", function(evt)
{
if(evt.keyCode == 37)
{
leftKey = true;
}
if(evt.keyCode == 39)
{
rightKey = true;
}
});
document.addEventListener("keyup", function(evt)
{
if(evt.keyCode == 37)
{
leftKey = false;
}
if(evt.keyCode == 39)
{
rightKey = false;
}
});
window.onload = function()
{
canvas = document.getElementById("gameCanvas");
canvasContext = canvas.getContext("2d");
setInterval(function()
{
drawAll();
moveAll();
}, 1000/framesPerSecond);
}
var renderMap = function()
{
for(var eachRow=0; eachRow<20; eachRow++)
{
for(var eachCol=0; eachCol<20; eachCol++)
{
if(map[eachRow][eachCol] == 0)
{
canvasContext.fillStyle = "#a6a6a6";
canvasContext.fillRect(TILE_W*eachCol, TILE_H*eachRow, TILE_W, TILE_H);
}
if(map[eachRow][eachCol] == 1)
{
canvasContext.fillStyle = "#666666";
canvasContext.fillRect(TILE_W*eachCol, TILE_H*eachRow, TILE_W, TILE_H);
}
}
}
}
var drawAll = function()
{
canvasContext.clearRect(0, 0, canvas.width, canvas.height);
renderMap();
ball.draw();
}
var canMoveHere = function(col, row)
{
if(map[row][col] == 1)
{
return false;
}
else
{
return true;
}
}
var moveAll = function()
{
nextBallX = `ball.x` + ball.velocityX;
nextBallY = `ball.y` + ball.velocityY;
nextBallCol = Math.floor(nextBallX / TILE_W);
nextBallRow = Math.floor(nextBallY / TILE_H);
var canMove = canMoveHere(nextBallCol, nextBallRow);
ball.velocityY += gravity;
`ball.y` += ball.velocityY;
if(ball.velocityY >= ball.terminalVel)
{
ball.velocityY = ball.terminalVel;
}
if(canMove === false)
{
ball.velocityY *= -1;
}
if(leftKey)
{
`ball.x` -= ball.velocityX;
}
if(rightKey)
{
`ball.x` += ball.velocityX;
}
}
</script>
</head>
<body>
</body>
</html>
You can't just say "if the ball can or cannot move over certain tile", you have to tell the game how to respond when an obstacle is hit and that depends on two factors: current ball direction and shape of the obstacle.
I modified your canMoveHere function to evaluate that:
var directionChange = function(nextCol, nextRow)
{
var currentRow = Math.floor(ball.y / TILE_H);
var currentCol = Math.floor(ball.x / TILE_W);
var resultDirection = { x: 1, y: 1 };
if (map[nextRow][nextCol] == 1) {
if (map[nextRow][currentCol] == 1 &&
map[currentRow][nextCol] == 0) {
// horizontal obstacle
resultDirection.x = 1;
resultDirection.y = -1;
} else if (map[nextRow][currentCol] == 0 &&
map[currentRow][nextCol] == 1) {
// vertical obstacle
resultDirection.x = -1;
resultDirection.y = 1;
} else {
// corner obstacle
resultDirection.x = -1;
resultDirection.y = -1;
}
}
return resultDirection;
}
at this point we also modify the moveAll function accordingly
var moveAll = function()
{
nextBallX = ball.x + ball.velocityX;
nextBallY = ball.y + ball.velocityY;
nextBallCol = Math.floor(nextBallX / TILE_W);
nextBallRow = Math.floor(nextBallY / TILE_H);
let dir = directionChange(nextBallCol, nextBallRow);
ball.velocityY *= dir.y;
ball.velocityX *= dir.x;
ball.velocityY += gravity;
if(ball.velocityY >= ball.terminalVel)
{
ball.velocityY = ball.terminalVel;
}
ball.y += ball.velocityY;
if(leftKey) {
ball.x -= ball.velocityX;
}
if(rightKey) {
ball.x += ball.velocityX;
}
}
Now you just have to find a way to let the keys drive the ball smoothly, because changing the velocity using positive/negative values has an effect to the actual direction of the ball, because it will go to the opposite direction of the pressed key when values are negatives;
I tried using absolute values
if(leftKey) {
ball.x -= Math.abs(ball.velocityX);
}
if(rightKey) {
ball.x += Math.abs(ball.velocityX);
}
but as soon as the ball hits an obstacle, the pressed key will keep pushing the ball against the obstacle changing again the velocity and - for how it is built now - the ball will go through the walls.
Even though this isn't a bug-free solution, I hope this can help you on solving the main problem.

Javascript Conway's Game of Life Issues

I'm trying to make Conway's Game of Life in javascript. I made a function to count neighbors, and a function that produces the next generation of cells. However, I tried a test input, and the result isn't coming out right, and I can't find where the error is. Please help.
Here's the code:
(code attached)
/* Draws grid */
for (var i = 0; i < 15; i++) {
for (var j = 0; j < 15; j++) {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FFFFFF";
ctx.strokeStyle = "grey";
ctx.strokeRect(10 * j, 10 * i, 10, 10);
}
}
/* draws live cells */
function drawSquares(a) {
for (var i = 0; i < 15; i++) {
for (var j = 0; j < 15; j++) {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#000000";
if (a[i][j] === 1) {
ctx.fillRect(10 * j, 10 * i, 10, 10);
}
}
}
}/* Counts neighbors */
function neighborCount(a, i, j, height, width){
var lifes = 0;
var neighbors = [
[-1, 1],
[0, 1],
[1, 1],
[-1, 0],
[1, 0],
[-1, -1],
[0, -1],
[1, -1]
];
/* loops through a cell's neighbors */
for (var z = 0; z < 8; z++){
/*checks if the neighbor isn't off the grid*/
if ((i + neighbors[z][0]) >=0 && (i + neighbors[z][0]) < height && (j + neighbors[z][1]) >=0 && (j + neighbors[z][1]) < width){
/*checks if it's alive*/
if (a[i + neighbors[z][0]][j + neighbors[z][1]] === 1){
lifes++;
}
}
}
return lifes;
}
/* game of life */
function life(a) {
var n = a; /*new generation of life */
var lifes = 0; /*neighbor counter*/
var height = a.length;
var width = a[0].length;
/*loops through all cells*/
for (var i = 0; i < height; i++){
for (var j = 0; j < width; j++){
lifes = neighborCount(a, i, j, height, width);
/* kills alive cells */
if(a[i][j] === 1 && (lifes < 2 || lifes > 3)){
n[i][j] = 0;
}
/* brings dead cells to life */
else if (a[i][j] === 0 && lifes ===3){
n[i][j] = 1;
}
}
}
drawSquares(n);
return(n);
}
/* test input */
var a = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0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 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]; */
life(a);
<canvas id="myCanvas" width="150" height="150"></canvas>

Collision detection in javascript canvas tanks game

Here is the code, how would i go on about making the bullets fired (size 6x6 pixels) collide with the blocks currently on the map? I've looked at all sort of collision code but I can't seem to apply it to this particular code because of how the map is setup i'm guessing.
Desperately need a solution!
// inner variables
var canvas, context; // canvas and context objects
var imgBrick, imgSteel, imgWater, imgForest, imgTank; // images
var aMap; // map array
var oTank; // tank object
var bullets = [];
var iCellSize = 24; // cell wide
var iXCnt = 26; // amount of X cells
var iYCnt = 26; // amount of Y cells
// objects :
function Tank(x, y, w, h, image) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.i = 0;
this.image = image;
}
function Bullet(dir, bullX, bullY, bulltype) {
this.direct = dir;
this.bullX = bullX;
this.bullY = bullY;
this.bulltype = bulltype;
}
// functions
function clear() { // clear canvas function
context.clearRect(0, 0, canvas.width, canvas.height);
}
// Firing bullets and directions
function movebullets()
{
for (var i = 0; i < bullets.length; i++) {
if (bullets[i].direct==2)
{
bullets[i].bullY-=10;
}
else if (bullets[i].direct==3)
{
bullets[i].bullY+=10;
}
else if (bullets[i].direct==0)
{
bullets[i].bullX+=10;
}
else if (bullets[i].direct==1)
{
bullets[i].bullX-=10;
}
}
}
/*
function bulletCollision(){
var remove = false;
for(var i = 0; i < bullets.length; i++){
for(var j = 0; j < asteroids.length; j++){
if(bullets[i].y <= (asteroids[j].y + enemies[j].h) && bullets[i].x >= enemies[j].x && bullets[i].x <= (enemies[j].x + enemies[j].w)){
remove = true;
enemies[j].dead = true;
//score++;
//explosions.push(new Explosion((asteroids[j].x + (asteroids[j].w / 2)), (asteroids[j].y + (asteroids[j].h / 2 )), asteroids[j].w));
enemies.splice(j,1);
}
}
*/
function drawScene() { // main drawScene function
clear(); // clear canvas
// fill background
context.fillStyle = '#111';
context.fillRect(0, 0, canvas.width, canvas.height);
// save current context
context.save();
// walk through our array
for (var y = 0; y < iYCnt; y++) {
for (var x = 0; x < iXCnt; x++) {
switch (aMap[y][x]) {
case 0: // skip
break;
case 1: // draw brick block
context.drawImage(imgBrick, 0, 0, iCellSize, iCellSize, x*iCellSize, y*iCellSize, iCellSize, iCellSize);
break;
case 2: // draw steel block
context.drawImage(imgSteel, 0, 0, iCellSize, iCellSize, x*iCellSize, y*iCellSize, iCellSize, iCellSize);
break;
case 3: // draw forest block
context.drawImage(imgForest, 0, 0, iCellSize, iCellSize, x*iCellSize, y*iCellSize, iCellSize, iCellSize);
break;
case 4: // draw water block
context.drawImage(imgWater, 0, 0, iCellSize, iCellSize, x*iCellSize, y*iCellSize, iCellSize, iCellSize);
break;
}
}
}
// restore current context
context.restore();
// draw tank + bullets
context.drawImage(oTank.image, oTank.i*oTank.w, 0, oTank.w, oTank.h, oTank.x, oTank.y, oTank.w, oTank.h);
for (var i = 0; i < bullets.length; i++) {
context.drawImage(imgBullet, bullets[i].bullX, bullets[i].bullY);
}
}
// -------------------------------------------------------------
// initialization
$(function(){
canvas = document.getElementById('scene');
canvas.width = iXCnt * iCellSize;
canvas.height = iYCnt * iCellSize;
context = canvas.getContext('2d');
// main scene Map array
aMap = ([
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[2, 2, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 2, 2, 0, 0, 3, 3, 4, 4, 0, 0, 1, 1, 0, 0],
[2, 2, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 2, 2, 0, 0, 3, 3, 4, 4, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 2, 2, 0, 0, 3, 3, 4, 4, 0, 0, 2, 3, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 2, 2, 0, 0, 3, 3, 4, 4, 0, 0, 2, 3, 0, 0],
[0, 0, 0, 0, 0, 0, 2, 2, 3, 3, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 0, 0],
[0, 0, 0, 0, 0, 0, 2, 2, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0]
]);
// load images
imgBrick = new Image();
imgBrick.src = 'images/brick.png';
imgSteel = new Image();
imgSteel.src = 'images/steel.png';
imgWater = new Image();
imgWater.src = 'images/water.png';
imgForest = new Image();
imgForest.src = 'images/forest.png';
imgBullet = new Image();
imgBullet.src = 'images/bullet.png';
imgTank = new Image();
imgTank.src = 'images/tank.png';
oTank = new Tank(iCellSize*9, iCellSize*24, 48, 48, imgTank);
document.addEventListener('mousedown', function (event) {
bullets.push(new Bullet(oTank.i, oTank.x+24, oTank.y+24, 1));
(function(){
var sound = new Audio('bullet_shot.ogg');
sound.volume = 0.9;
sound.addEventListener('ended', function() { // loop the sound
}, false);
sound.play();
})();
});
$(window).keydown(function(event){ // keyboard alerts
switch (event.keyCode) {
case 87: // W key
oTank.i = 2;
// checking collisions
var iCurCelX = (2 * oTank.x) / 48;
var iCurCelY = (2 * oTank.y) / 48;
if (iCurCelY) {
var iTest1 = aMap[iCurCelY-1][iCurCelX];
var iTest2 = aMap[iCurCelY-1][iCurCelX+1];
if ((iTest1 == 0 || iTest1 == 3) && (iTest2 == 0 || iTest2 == 3)) {
oTank.y-=24;
if (oTank.y < 0) {
oTank.y = 0;
}
}
}
break;
case 83: // S key
oTank.i = 3;
// checking collisions
var iCurCelX = (2 * oTank.x) / 48;
var iCurCelY = (2 * oTank.y) / 48;
if (iCurCelY+2 < iYCnt) {
var iTest1 = aMap[iCurCelY+2][iCurCelX];
var iTest2 = aMap[iCurCelY+2][iCurCelX+1];
if ((iTest1 == 0 || iTest1 == 3) && (iTest2 == 0 || iTest2 == 3)) {
oTank.y+=24;
if (oTank.y > 576) { //iCellSize * (iYCnt-2)
oTank.y = 576;
}
}
}
break;
case 65: // A key
oTank.i = 1;
// checking collisions
var iCurCelX = (2 * oTank.x) / 48;
var iCurCelY = (2 * oTank.y) / 48;
var iTest1 = aMap[iCurCelY][iCurCelX-1];
var iTest2 = aMap[iCurCelY+1][iCurCelX-1];
if ((iTest1 == 0 || iTest1 == 3) && (iTest2 == 0 || iTest2 == 3)) {
oTank.x-=24;
if (oTank.x < 0) {
oTank.x = 0;
}
}
break;
case 68: // D key
oTank.i = 0;
// checking collisions
var iCurCelX = (2 * oTank.x) / 48;
var iCurCelY = (2 * oTank.y) / 48;
var iTest1 = aMap[iCurCelY][iCurCelX+2];
var iTest2 = aMap[iCurCelY+1][iCurCelX+2];
if ((iTest1 == 0 || iTest1 == 3) && (iTest2 == 0 || iTest2 == 3)) {
oTank.x+=24;
if (oTank.x > 576) { //iCellSize * (iXCnt-2)
oTank.x = 576;
}
}
break;
}
});
setInterval(drawScene, 40); // loop drawScene
setInterval(movebullets, 40);
});
you need to set the bullet size like this inside the for
for (var i = 0; i < bullets.length; i++) {
//6px width and height
context.drawImage(imgBullet, bullets[i].bullX, bullets[i].bullY,6,6);
}
and inside movebullets() you can call bulletCollision like this
function movebullets()
{
for (var i = 0; i < bullets.length; i++) {
if (bullets[i].direct==2)
{
bullets[i].bullY-=10;
}
else if (bullets[i].direct==3)
{
bullets[i].bullY+=10;
}
else if (bullets[i].direct==0)
{
bullets[i].bullX+=10;
}
else if (bullets[i].direct==1)
{
bullets[i].bullX-=10;
}
bulletCollision(i);
}
}
function bulletCollision(i){
//if the aMap value in the bullet position is not 0
if(aMap[parseInt(bullets[i].bullY/iCellSize)][parseInt(bullets[i].bullX/iCellSize)]!=0){
alert("Collision");//do something
bullets.splice(i, 1);//remove the current bullet
}
}

Categories