Search code examples
javascriptarrayswidthcollisioncreatejs

calling object.width is returning NaN in JavaScript


I am currently working on a game that has to do with a rocket ship moving around and objects(circles) are falling from the top. The goal of this game is to not hit the objects as they are falling down the screen. I am running into problems when writing my collision algorithm.

I have declared var hit = false; at the top of my code I have also put all of the circles into an array called projectiles.

I believe that I have the logic correct but I discovered that when calling either p.width or ship.width it returns NaN. I have tried using offsetWidth and that didn't work either. I am wondering how else to go about getting the width of my objects

The else statement at the bottom is just to check if .width is returning the correct number. Once I get it to work it will be removed and replaced with the final parts of the collision algorithm.

function checkCollision()
{

    for (i = 0; i < projectiles.length; i++) {
        var p = projectiles[i];
        if((p.x + p.width) < ship.x)
        {
            hit = false;
        }
        else if(p.x > (ship.x + ship.width))
        {
            hit = false;
        }
        else if(p.y > (ship.y + ship.height))
        {
            hit = false;
        }
        else if((p.y + p.height) < ship.y)
        {
            hit = false;
        }
        else {
            console.log(ship.x + ship.width);
        }

Solution

  • In the documentation for createjs.Bitmap there do not exist properties for .width and .height. Instead access it's .image (HTMLImageElement) property which have defined width and height properties: ship.image.width and ship.image.height.