Collision Checking With JavaScript - javascript

I'm creating a game where the user wanders around a cemetery and collects stories from different graves. It's a classic top-down game. I'm building a script where if the user walks into a grave their movement stops, but I'm having trouble setting up collisions. I am using jQuery. Here is what I have so far:
var position = -1;
var $char = $('#char');
var keyCode = null;
var fired = false;
var $stones = $('.stones div');
var collision = null;
document.onkeydown = function(e) {
keyCode = e.which || e.keyCode;
if (!fired) {
position = -1;
fired = true;
switch (keyCode) {
case 38: position = 0; break; //up
case 40: position = 1; break; //down
case 37: position = 2; break; //left
case 39: position = 3; break; //right
}
walking();
stepping = setInterval(walking,125);
}
};
document.onkeyup = function(e) {
//standing
clearInterval(stepping);
stepping = 0;
fired = false;
};
function walking() {
$stones.each(function() { //check all the stones...
collision = collision($(this), $char, position); ...for collisions
if (collision) { //if any, then break loop
return false;
}
});
if (!collision) { //check if there was a collision
//if no collision, keep walking x direction
}
function collision($el, $charEl, position) {
var $el = $el[0].getBoundingClientRect();
var $charEl = $charEl[0].getBoundingClientRect();
var elBottom = parseInt($el.bottom);
var elRight = parseInt($el.right);
var elLeft = parseInt($el.left);
var elTop = parseInt($el.top);
var charBottom = parseInt($charEl.bottom);
var charRight = parseInt($charEl.right);
var charLeft = parseInt($charEl.left);
var charTop = parseInt($charEl.top);
//this is where I'm stuck
}
}
I've tried various different codes, but nothing seems to work. I keep having an issue where if I'm going forward and then I bump into a headstone and I turn around, I'm stuck. Here's an example code of what I mean:
if (position == 0 &&
!(elTop > charBottom ||
elBottom < charTop ||
elRight < charLeft + 1 ||
elLeft > charRight - 1)
) {
return true;
}
if (position == 1 &&
!(elTop > charBottom ||
elBottom < charTop ||
elRight < charLeft + 1 ||
elLeft > charRight - 1)
) {
return true;
}
return false;
I have looked this question and this question and this question and so far I'm not having any luck. Can somebody help me with the logic or supply an example code of what I need to do?
Thank you.

Your game is looking good man!
I recently wrote some collision detection and had the exact same problem. The issue is that once your coordinates are true of the case of the collision then they will always be true on any other movement.
You need to store the previous position your character was in and revert back to it OR perform the check before you change your characters coordinates.

I managed to find the following solution, thanks to stwitz' about idea, as well as this script: https://magently.com/blog/detecting-a-jquery-collision-part-iv/
var position = -1;
var $char = $('#char');
var keyCode = null;
var fired = false;
var stepSize = 32;
var $stones = $('.stones div');
//new
var cancelTop = cancelRight = cancelLeft = cancelBottom = false;
var charEl = $char[0].getBoundingClientRect();
var charLeft = parseInt(charEl.left);
var charRight = parseInt(charEl.right);
var charTop = parseInt(charEl.top);
var charBottom = parseInt(charEl.bottom);
function walking() {
if (position == 0 && !cancelTop) {
//if moving up & is safe to move up
} else if (position == 1 && !cancelBottom) {
//if moving down & is safe to move down
} else if (position == 2 && !cancelLeft) {
//if moving left and is safe to move left
} else if (position == 3 && !cancelRight) {
//if moving right and is safe to move right
}
cancelTop = cancelRight = cancelLeft = cancelBottom = false; //mark all as safe until we check
$stones.each(function() {
collision($(this));
});
}
document.onkeydown = function(e) {
keyCode = e.which || e.keyCode;
if (!fired) {
position = -1;
fired = true;
switch (keyCode) {
case 38: position = 0; break; //up
case 40: position = 1; break; //down
case 37: position = 2; break; //left
case 39: position = 3; break; //right
}
walking();
stepping = setInterval(walking,125);
}
};
document.onkeyup = function(e) {
//standing
clearInterval(stepping);
stepping = 0;
fired = false;
};
function collision($el) {
var el = $el[0].getBoundingClientRect();
var elBottom = parseInt(el.bottom);
var elRight = parseInt(el.right);
var elLeft = parseInt(el.left);
var elTop = parseInt(el.top);
if (
(elRight == charLeft) &&
(elBottom - stepSize >= charBottom && charBottom >= elTop + stepSize)
) {
cancelLeft = true;
return true;
}
if (
(elLeft == charRight) &&
(elBottom - stepSize >= charBottom && charBottom >= elTop + stepSize)
) {
cancelRight = true;
return true;
}
if (
(elTop + stepSize > charBottom) &&
(elTop <= charBottom) &&
(elLeft < charRight) &&
(elRight > charLeft)
)
{
cancelBottom = true;
return true;
}
if (
(elBottom - stepSize < charTop) &&
(elBottom >= charTop) &&
(elLeft < charRight) &&
(elRight > charLeft)
)
{
cancelTop = true;
return true;
}
return false;
}

Related

Why when I press two keys simultaneously and stop pressing one, the other stops working?

I am working with keyboard events in Javascript. My goal is to be able to move images on a canvas with the keyboard arrows, but there is a problem: when I press two keys simultaneously and then release one of them, the key I left pressed does not work, it crashes and therefore the image It does not move. I'm already using the keyup and keydown events and I managed to find a way to detect when two keys are pressed at the same time, however I can't solve this problem. Can anyone help me? Thank you.
this is what i tried
function keyPressed(event) {
keysPressed[event.key] = true;
switch(event.key) {
case 'ArrowLeft':
playerPetSelected.speedX = -5;
break;
case 'ArrowRight':
playerPetSelected.speedX = 5;
break;
case 'ArrowDown':
playerPetSelected.speedY = 5;
break;
case 'ArrowUp':
playerPetSelected.speedY = -5;
break;
}
if (keysPressed['ArrowLeft'] && event.key == 'ArrowDown') {
playerPetSelected.speedX = -3.5;
playerPetSelected.speedY = 3.5;
}
if (keysPressed['ArrowDown'] && event.key == 'ArrowLeft') {
playerPetSelected.speedY = 3.5;
playerPetSelected.speedX = -3.5;
}
if (keysPressed['ArrowLeft'] && event.key == 'ArrowUp') {
playerPetSelected.speedX = -3.5;
playerPetSelected.speedY = -3.5;
}
if (keysPressed['ArrowUp'] && event.key == 'ArrowLeft') {
playerPetSelected.speedY = -3.5;
playerPetSelected.speedX = -3.5;
}
if (keysPressed['ArrowUp'] && event.key == 'ArrowRight') {
playerPetSelected.speedY = -3.5;
playerPetSelected.speedX = 3.5;
}
if (keysPressed['ArrowRight'] && event.key == 'ArrowUp') {
playerPetSelected.speedX = 3.5;
playerPetSelected.speedY = -3.5;
}
if (keysPressed['ArrowDown'] && event.key == 'ArrowRight') {
playerPetSelected.speedY = 3.5;
playerPetSelected.speedX = 3.5;
}
if (keysPressed['ArrowRight'] && event.key == 'ArrowDown') {
playerPetSelected.speedX = 3.5;
playerPetSelected.speedY = 3.5;
}
}
function stopMovement(event) {
keysPressed[event.key] = false;
playerPetSelected.speedX = 0;
playerPetSelected.speedY = 0;
}
The parts where I modify the 'playerPetSelected' object are so that the images can be moved on the canvas.
I was hoping I wouldn't have this problem anymore because here I was able to find a way to detect when two keys are pressed at the same time, but it only helped me to manipulate the speed of movement on the canvas when two keys are pressed simultaneously.
Here is how I would do it... Using an object for the speed in x/y. Look how the conditions are easier to read. That handles all possible arrow combinations.
window.addEventListener("keydown", keyPressed)
window.addEventListener("keyup", keyUnpressed)
let keysPressed = {}
function keyPressed(event) {
keysPressed[event.key] = true
getActiveKeys()
}
function keyUnpressed(event) {
keysPressed[event.key] = false
getActiveKeys()
}
function getActiveKeys() {
const activeKeys = Object.keys(keysPressed).map((key) => keysPressed[key] ? key : null).filter((key) => key)
const speed = {
x: 0,
y: 0
}
if(keysPressed["ArrowUp"]){
speed.y = 5
}
if(keysPressed["ArrowDown"]){
speed.y = -5
}
if(keysPressed["ArrowLeft"]){
speed.x = -5
}
if(keysPressed["ArrowRight"]){
speed.x = 5
}
// Gas and break conditions
if(keysPressed["ArrowUp"] && keysPressed["ArrowDown"]){
speed.y = 0
}
if(keysPressed["ArrowLeft"] && keysPressed["ArrowRight"]){
speed.x = 0
}
// Diagonal condition
if(speed.x && speed.y){
speed.x *= 0.7
speed.y *= 0.7
}
document.querySelector("#activeKeys").innerText = JSON.stringify(activeKeys)
document.querySelector("#xSpeed").innerText = speed.x
document.querySelector("#ySpeed").innerText = speed.y
}
<div>Keys pressed: <span id="activeKeys">[]</span></div>
<div>Speed X: <span id="xSpeed">0</span></div>
<div>Speed Y: <span id="ySpeed">0</span></div>
Run that snippet in full page mode, else the page will scroll. Or look at CodePen

Disable keyboard in javascript

I'm trying to figure out how to make the keyboard get disabled after the score equals five. with everything else I'm fine. I got everything else done that I need to get done I'm just having issues with the keyboard, if I could get some help on this it would greatly be appreciated. this is just giving me a hard time so I thought I would get some help.
//Arrow key codes
var UP = 38;
var DOWN = 40;
var RIGHT = 39;
var LEFT = 37;
//Directions
var moveUp = false;
var moveDown = false;
var moveRight = false;
var moveLeft = false;
//Add keyboard listeners
window.addEventListener("keydown", function(event)
{
switch(event.keyCode)
{
case UP:
moveUp = true;
break;
case DOWN:
moveDown = true;
break;
case LEFT:
moveLeft = true;
break;
case RIGHT:
moveRight = true;
break;
}
}, false);
window.addEventListener("keyup", function(event)
{
switch(event.keyCode)
{
case UP:
moveUp = false;
break;
case DOWN:
moveDown = false;
break;
case LEFT:
moveLeft = false;
break;
case RIGHT:
moveRight = false;
break;
}
}, false);
function loadHandler()
{
update();
}
function update()
{
//The animation loop
requestAnimationFrame(update, canvas);
//Up
if(moveUp && !moveDown)
{
cat.vy = -5;
}
//Down
if(moveDown && !moveUp)
{
cat.vy = 5;
}
//Left
if(moveLeft && !moveRight)
{
cat.vx = -5;
}
//Right
if(moveRight && !moveLeft)
{
cat.vx = 5;
}
//Set the cat's velocity to zero if none of the keys are being pressed
if(!moveUp && !moveDown)
{
cat.vy = 0;
}
if(!moveLeft && !moveRight)
{
cat.vx = 0;
}
//Move the cat
cat.x += cat.vx;
cat.y += cat.vy;
//Check for a collision between the cat and the monster
//and change the monster's score when they collide
if(hitTestRectangle(cat, monster) && score < 5)
{
if(!collisionHasOccured)
{
score++;
collisionHasOccured = true;
}
}
else
{
collisionHasOccured = false;
}
if(score === 5)
{
message = " - Game Over!";
}
//Render the sprites
render();
}
function hitTestRectangle(r1, r2)
{
//A variable to determine whether there's a collision
var hit = false;
//Calculate the distance vector
var vx = r1.centerX() - r2.centerX();
var vy = r1.centerY() - r2.centerY();
//Figure out the combined half-widths and half-heights
var combinedHalfWidths = r1.halfWidth() + r2.halfWidth();
var combinedHalfHeights = r1.halfHeight() + r2.halfHeight();
//Check for a collision on the x axis
if(Math.abs(vx) < combinedHalfWidths)
{
//A collision might be occuring.
//Check for a collision on the y axis
if(Math.abs(vy) < combinedHalfHeights)
{
//There's definitely a collision happening
hit = true;
}
else
{
//There's no collision on the y axis
hit = false;
}
}
else
{
//There's no collision on the x axis
hit = false;
}
return hit;
}
function render(event)
{
drawingSurface.clearRect(0, 0, canvas.width, canvas.height);
if(sprites.length !== 0)
{
for(var i = 0; i < sprites.length; i++)
{
var sprite = sprites[i];
drawingSurface.drawImage
(
image,
sprite.sourceX, sprite.sourceY,
sprite.sourceWidth, sprite.sourceHeight,
Math.floor(sprite.x), Math.floor(sprite.y),
sprite.width, sprite.height
);
}
}
drawingSurface.fillText(score + message, monster.x, monster.y - 40);
}
</script>
You just need to add an if statement to your event listeners. ( IF score == 5 ) then don't do anything. You can place the code right above the switch statements.
EDIT
#JasonEnts:
window.addEventListener("keydown", function(event)
{ if (score < 5) {
switch(event.keyCode)
{
case UP:
moveUp = true;
break;
case DOWN:
moveDown = true;
break;
case LEFT:
moveLeft = true;
break;
case RIGHT:
moveRight = true;
break;
}
}
}, false);

having problems understanding a tutorial on one page scroll-vanilla JS- no libraries

I was looking into one of the only few full page scroll codes which I have found so far, and wanted to somehow get the idea of what I should do by reversing the engineering but I'm noob and not good at understanding it pretty well, I don't understand it well and I get stock at every line, can you please explain to me what the guy has done? Whats the basics of what he is doing ..variables and functions and what they are in this case and why we need them? A summary on what is going on.
this is the link to the code
https://codepen.io/igstudio/pen/pbYOab
this is the JS code
(function() {
"use strict";
/*[pan and well CSS scrolls]*/
var pnls = document.querySelectorAll('.panel').length,
scdir, hold = false;
function _scrollY(obj) {
var slength, plength, pan, step = 100,
vh = window.innerHeight / 100,
vmin = Math.min(window.innerHeight, window.innerWidth) / 100;
if ((this !== undefined && this.id === 'well') || (obj !== undefined && obj.id === 'well')) {
pan = this || obj;
plength = parseInt(pan.offsetHeight / vh);
}
if (pan === undefined) {
return;
}
plength = plength || parseInt(pan.offsetHeight / vmin);
slength = parseInt(pan.style.transform.replace('translateY(', ''));
if (scdir === 'up' && Math.abs(slength) < (plength - plength / pnls)) {
slength = slength - step;
} else if (scdir === 'down' && slength < 0) {
slength = slength + step;
} else if (scdir === 'top') {
slength = 0;
}
if (hold === false) {
hold = true;
pan.style.transform = 'translateY(' + slength + 'vh)';
setTimeout(function() {
hold = false;
}, 1000);
}
console.log(scdir + ':' + slength + ':' + plength + ':' + (plength - plength / pnls));
}
/*[swipe detection on touchscreen devices]*/
function _swipe(obj) {
var swdir,
sX,
sY,
dX,
dY,
threshold = 100,
/*[min distance traveled to be considered swipe]*/
slack = 50,
/*[max distance allowed at the same time in perpendicular direction]*/
alT = 500,
/*[max time allowed to travel that distance]*/
elT, /*[elapsed time]*/
stT; /*[start time]*/
obj.addEventListener('touchstart', function(e) {
var tchs = e.changedTouches[0];
swdir = 'none';
sX = tchs.pageX;
sY = tchs.pageY;
stT = new Date().getTime();
//e.preventDefault();
}, false);
obj.addEventListener('touchmove', function(e) {
e.preventDefault(); /*[prevent scrolling when inside DIV]*/
}, false);
obj.addEventListener('touchend', function(e) {
var tchs = e.changedTouches[0];
dX = tchs.pageX - sX;
dY = tchs.pageY - sY;
elT = new Date().getTime() - stT;
if (elT <= alT) {
if (Math.abs(dX) >= threshold && Math.abs(dY) <= slack) {
swdir = (dX < 0) ? 'left' : 'right';
} else if (Math.abs(dY) >= threshold && Math.abs(dX) <= slack) {
swdir = (dY < 0) ? 'up' : 'down';
}
if (obj.id === 'well') {
if (swdir === 'up') {
scdir = swdir;
_scrollY(obj);
} else if (swdir === 'down' && obj.style.transform !== 'translateY(0)') {
scdir = swdir;
_scrollY(obj);
}
e.stopPropagation();
}
}
}, false);
}
/*[assignments]*/
var well = document.getElementById('well');
well.style.transform = 'translateY(0)';
well.addEventListener('wheel', function(e) {
if (e.deltaY < 0) {
scdir = 'down';
}
if (e.deltaY > 0) {
scdir = 'up';
}
e.stopPropagation();
});
well.addEventListener('wheel', _scrollY);
_swipe(well);
var tops = document.querySelectorAll('.top');
for (var i = 0; i < tops.length; i++) {
tops[i].addEventListener('click', function() {
scdir = 'top';
_scrollY(well);
});
}
})();
Thanks.

Checking if two points are touching in a hex grid

Some time ago I wrote this fun grid that is offset to look like a hexagonal grid. I added a feature to check if any two points are touching. I thought it was brilliant until I finally found a bug and am not sure how to correct it.
If you press (1,4) and (2,5) you will see that they are "touching" but they shouldn't be. What logic am I missing in the function isTouchingHex?
Found bugs so far..
(1,4) & (2,5)
(2,2) & (3,3)
(0,0) & (1,1)
CodePen
var $point1 = $('#point1');
var $point2 = $('#point2');
var $dx = $('#dx');
var $dy = $('#dy');
var $isTouching = $('#isTouching');
var $table = $('#hexTable');
var table = [];
var rows = 10;
var cols = 5;
var point1 = null;
var point2 = null;
var clickedCount = 0;
for (let y = 0; y < rows; y++) {
var $tr = $('<div class="hexagonRow"></div>')
var row = [];
for (let x = 0; x < cols; x++) {
var $col = $('<div class="hexagon"><div class="hexagonText">' + x + ',' + y + '</div></div>');
$col.click(function() {
if (clickPoint(x, y))
$(this).toggleClass('clicked');
});
$tr.append($col);
row.push(y);
}
$table.append($tr);
table.push(row);
}
function clickPoint(x, y) {
var clicked = true;
if (point1 && point1[0] === x && point1[1] === y) {
point1 = null;
clickedCount--;
} else if (point2 && point2[0] === x && point2[1] === y) {
point2 = null;
clickedCount--;
} else if (!point1 && clickedCount < 3) {
point1 = [x, y];
clickedCount++;
} else if (!point2 && clickedCount < 3) {
point2 = [x, y];
clickedCount++;
} else {
clicked = false;
}
updateDisplay();
return clicked;
}
function updateDisplay() {
if (point1)
$point1.html(point1[0] + ',' + point1[1])
else
$point1.html('');
if (point2)
$point2.html(point2[0] + ',' + point2[1])
else
$point2.html('');
if (point1 && point2) {
var touching = isTouchingHex(point1[0], point1[1], point2[0], point2[1]) ? 'true' : 'false';
$isTouching.html(touching)
} else {
$isTouching.html('');
}
}
function isTouchingHex(x1, y1, x2, y2) {
var deltaX = x1 - x2;
var deltaY = y1 - y2;
$dx.html(deltaX);
$dy.html(deltaY);
// check same x
if (deltaX === 0) {
switch (deltaY) {
// check bottom left
case -1:
// check bottom
case -2:
// check top right
case 1:
// check above
case 2:
return true;
break;
}
} else if (deltaX === 1) {
switch (deltaY) {
// check bottom left
case -1:
// check top left
case 1:
return true;
break;
}
}else if (deltaX === -1) {
switch (deltaY) {
// check bottom right
case -1:
return true;
break;
}
}
return false;
}

Hit detection between 2 moving objects in CreateJS

We are using createJS and right now I am struggling with a hit test.
I get this error:
"ss.js:203 Uncaught TypeError: Cannot read property 'x' of undefined
at hitTest (ss.js:203)
at doCollisionChecking (ss.js:215)
at heartBeat (ss.js:238)
at Function.b._dispatchEvent (createjs-2015.11.26.min.js:12)
at Function.b.dispatchEvent (createjs-2015.11.26.min.js:12)
at Function.a._tick (createjs-2015.11.26.min.js:12)
at a._handleTimeout (createjs-2015.11.26.min.js:12)"
I think the problem has to the with the 2 objects x position, but one is a player controlled character and the other object have random x value.
All the hit test example i found always consist of a static object and a moving, but this time they are both moving and i have no idea what to do.
var stage, hero, queue, circle, coin;
var coins = [];
var Score, tekst1, tekst2;
var speed = 3;
var keys = {
u: false,
d: false,
l: false,
r: false
};
var settings = {
heroSpeed: 15
};
function preload() {
"use strict";
stage = new createjs.Stage("ss");
queue = new createjs.LoadQueue(true);
queue.installPlugin(createjs.Sound);
queue.loadManifest([
{
id: 'Vacuum',
src: "img/Vacuum.png"
},
{
id: 'Dust',
src: "img/dust.png"
},
{
id: 'Pickup',
src: "sounds/pickup.mp3"
},
{
id: 'Suger',
src: "sounds/suger.wav"
},
]);
queue.addEventListener('progress', function () {
console.log("hi mom, preloading");
});
queue.addEventListener('complete', setup);
}
function setup() {
"use strict";
window.addEventListener('keyup', fingerUp);
window.addEventListener('keydown', fingerDown);
circle = new createjs.Bitmap("img/Vacuum.png");
circle.width = 40;
circle.height = 90;
stage.addChild(circle);
circle.y = 570;
circle.x = 460;
Score = new createjs.Text("0", "25px Impact", "white");
Score.x = 900;
Score.y = 680;
Score.textBaseline = "alphabetic";
stage.addChild(Score);
tekst1 = new createjs.Text("Score", "25px Impact", "white");
tekst1.x = 740;
tekst1.y = 680;
tekst1.textBaseline = "alphabetic";
stage.addChild(tekst1);
tekst2 = new createjs.Text("Bombs fallin", "40px Impact", "white");
tekst2.x = 10;
tekst2.y = 50;
tekst2.textBaseline = "alphabetic";
stage.addChild(tekst2);
createjs.Ticker.setFPS(30);
createjs.Ticker.addEventListener('tick', heartBeat)
}
function addCoins() {
coin = new createjs.Bitmap("img/dust.png");
coin.x = Math.random() * 900;
coin.width = 36;
coin.height = 50;
coins.push(coin);
stage.addChild(coin);
}
function moveCoins() {
for (var i = 0; i < coins.length; i++) {
coins[i].y += speed;
}
for (var j = 0; j < coins.length; j++) {
if (coins[j].y > 650) {
console.log("hejsa");
stage.removeChild(coins[j]);
coins.splice(j, 1);
}
}
}
function maybeAddCoin() {
var rand = Math.random() * 500;
if (rand < 5) {
addCoins();
}
}
function fingerUp(e) {
"use strict";
//createjs.Sound.stop("Suger")
switch (e.keyCode) {
case 37:
keys.l = false;
break;
case 38:
keys.u = false;
break;
case 39:
keys.r = false;
break;
case 40:
keys.d = false;
break;
}
}
function fingerDown(e) {
"use strict";
switch (e.keyCode) {
case 37:
keys.l = true;
break;
case 38:
keys.u = true;
break;
case 39:
keys.r = true;
break;
case 40:
keys.d = true;
break;
}
}
function moveSlime() {
"use strict";
if (keys.l) {
circle.x -= settings.heroSpeed;
if (circle.x < 0) {
circle.x = 0;
}
if (circle.currentDirection != "left") {
circle.currentDirection = "left";
//createjs.Sound.play("Suger");
keys.u = false;
keys.r = false;
keys.d = false;
}
}
if (keys.r) {
circle.x += settings.heroSpeed;
if (circle.x > 960) {
circle.x = 960;
}
if (circle.currentDirection != "right") {
circle.currentDirection = "right";
//createjs.Sound.play("Suger")
keys.u = false;
keys.l = false;
keys.d = false;
}
}
}
function hitTest(rect1, rect2) {
if (rect1.x >= rect2.x + rect2.width || rect1.x + rect1.width <= rect2.x ||
rect1.y >= rect2.y + rect2.height || rect1.y + rect1.height <= rect2.y)
{
return false;
}
return true;
}
function doCollisionChecking() {
for (var k = coins.length - 1; k >= 0; k--) {
if (hitTest(circle, coin[k])) {
console.log("ramt");
}
}
}
function scoreTimer() {
//Score.text = parseInt(Score.text + 10);
}
function heartBeat(e) {
"use strict";
doCollisionChecking()
maybeAddCoin()
//addCoins()
moveCoins()
scoreTimer()
moveSlime()
stage.update(e);
}
window.addEventListener('load', preload);
Clearly one of your elements is undefined (either circle or coins[k]). I would start with figuring out which one.
Open your debugger.
Turn on "Pause on Exceptions" and re-run your code. When the error happens, your debugger will pause and you can inspect your code
Determine what is undefined. This should shed some light on what is causing the error
One important thing I noticed is that you are looking for rect.width when collision checking. EaselJS elements don't have a width property, so you should instead use getBounds(), which will work with Bitmaps once they are loaded.
// Example
var bounds = rect.getBounds();
var w = bounds.width, h = bounds.height;
Hope that helps!
Here's the problem:
function doCollisionChecking() {
for (var k = coins.length - 1; k >= 0; k--) {
if (hitTest(circle,
coin[k] // your array is coins, not coin
)) {
console.log("ramt");
}
}
}
It might help you in the future to pass arguments through the function instead of relying on global objects. They help you by keeping modifications to your data on tight track. With global variables, anything can modify coins from anywhere and you won't be able to tell what function it is if you have 50+ different functions editing that variable.

Categories