0

I've been trying for ages to get this to work but I can't find anything. My game works in Chrome but not Firefox or IE. I have a function that registers the click position on a drawn box but I don't think that's the problem. I'm trying to register clicks on small moving objects which get deleted after being clicked. I was wondering if anyone could help me?

    //------------
//System Variables
//------------
var stage = document.getElementById("gameCanvas");
stage.width = STAGE_WIDTH;
stage.height = STAGE_HEIGHT;
var ctx = stage.getContext("2d");
ctx.fillStyle = "black";
ctx.font = GAME_FONTS;


//-----------------
//Browser Detection
//-----------------
navigator.sayswho= (function(){
    var N= navigator.appName, ua= navigator.userAgent, tem;
    var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
    if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
    M= M? [M[1], M[2]]: [N, navigator.appVersion, '-?'];
    return M;
})();
var browser;
if (navigator.sayswho[0] == "Firefox")
    browser="f";
else if (navigator.sayswho[0] == "Chrome")
    browser="c";
else if (navigator.sayswho[0] == "Safari")
    browser="s";
else  if (navigator.sayswho[0] == "Microsoft")
    browser="m";
else
    browser="f";

//Variables
var gameloop, mouseX, mouseY, isClicked, boxArray, score, rectcolor, xPos, yPos, endButton = {}, restartButton = {};
var AudioOn = true;
var ColorRectColor = 'white';
var colors = ['red', 'green', 'blue'];
var HasChangedColor = false;
var IsEnd = false;

//Init values
isClicked = false;
score = 0;

//Setup the Rectangles Array
boxArray = new Array();

//Set up game loop
gameloop = setInterval(update, TIME_PER_FRAME); 

//Listen for mouse click        
stage.addEventListener("mousedown", doMouseDown, false);
stage.addEventListener("touchstart", doMouseDown, false);

//Uses html audio source
sound = document.getElementById("audio");
sound2 = document.getElementById("audio2");


//Alters mouse interactions depending on browser
function doMouseDown(event)
{   
    if (browser == "f" || browser == "m")
    {
        mouseX = event.clientX - stage.offsetLeft + document.documentElement.scrollLeft;
        mouseY = event.clientY - stage.offsetTop + document.documentElement.scrollTop;

    }
    else //"s" or "c"
    {
        mouseX = event.clientX - stage.offsetLeft + document.body.scrollLeft;
        mouseY = event.clientY - stage.offsetTop + document.body.scrollTop;
    }
    isClicked = true;
}   

//------------
//Game Loop
//------------
function update()
{       
    //Clear Canvas
    ctx.fillStyle = "black";
    ctx.fillRect(0, 0, stage.width, stage.height);

    //If not the end of the game
    if(!IsEnd)
    {
        endButton.draw();

        //Check if we should generate a new Rectangle to drop down
        if (Math.random() < 0.04)
        {
            //Generate random colour
            rectcolor = colors[Math.floor(Math.random() * colors.length)];

            //Generate new box object randomly across the top of the screen and places it inside the array
            var newBox = new Object();
            newBox.x = Math.floor(Math.random()* 360);
            newBox.y = -10;
            boxArray.push(newBox);
        }

        //Update the position of the rectangles
        for (var i=boxArray.length - 10; i >= 0; i--)
        {
            //Fall down the y axis
            boxArray[i].y++;

            //If falls down screen a certain distance then delete from array
            if (boxArray[i].y > stage.height/1.3)
                boxArray.splice(i, 1);

            else
            {
                drawRect(boxArray[i].x,boxArray[i].y);

                if (isClicked)
                {
                    //Check for click collision
                    if (hitTestPoint(boxArray[i].x, boxArray[i].y, 45, 40, mouseX, mouseY))
                    {
                        //Check for colour match
                        if(rectcolor == ColorRectColor)
                        {

                            //Add to score and play sound
                            score++;
                            if(AudioOn){
                                sound.play();
                            }
                        }
                        else
                        {
                            //Minus score and play sound
                            score--;
                            if(AudioOn){
                                sound2.play();
                            }
                        }
                        boxArray.splice(i, 1);
                    }

                    //Check for end button click
                    else if(hitTestPoint(163, 755, 105, 60, mouseX, mouseY))
                    {
                        IsEnd = true;
                    }
                }
            }       
        }

        isClicked = false;

        //Update Text
        drawColorRect(60, 765);
        ctx.fillStyle = "white";
        ctx.fillText("Colour:", 8, 750);
        ctx.fillText("Score:", 270, 750);
        ctx.fillText(score, 320, 795);
        ctx.fillText("END", 169, 795);
    }

    //Restart screen
    else
    {
        //Draw restart button
        restartButton.draw();
        ctx.fillStyle = "white";
        ctx.font = "20px Arial, sans-serif";
        ctx.fillText("Reset Score", 160, 305);
        ctx.fillText("Game Over - You scored "+score+" points!", 60, 370);
        if(hitTestPoint(150, 285, 140, 35, mouseX, mouseY))
        {
            ctx.font = "bold 40px sans-serif";
            score = 0;
            IsEnd = false;

        }
    }
}


$(document).ready(function(){

  $("#audioimage").click(function(){
    if(AudioOn){
        AudioOn = false;
         $(this).attr('src', "images/noaudioLogo.png");
    }
    else{
        AudioOn = true;
         $(this).attr('src', "images/audioLogo.png");
    }
  });

});

function adjustStyle(width) {
    width = parseInt(width);
    if (width < 701) {
        $("#size-stylesheet").attr("href", "css/narrow.css");
    } else if ((width >= 701) && (width < 900)) {
        $("#size-stylesheet").attr("href", "css/medium.css");
    } else {
       $("#size-stylesheet").attr("href", "css/wide.css"); 
    }
}

$(function() {
    adjustStyle($(this).width());
    $(window).resize(function() {
        adjustStyle($(this).width());
    });
});

//End button properties
endButton ={
    draw: function()
    {
        ctx.beginPath();
        ctx.rect(163,755, 96, 50);
        ctx.fillStyle = 'black';
        ctx.strokeStyle = 'white';
        ctx.lineWidth=5;
        ctx.stroke();
        ctx.fill();
        ctx.closePath();
    }
}

//Restart button properties
restartButton={
    draw: function()
    {
        ctx.beginPath();
        ctx.rect(150,285, 130, 25);
        ctx.fillStyle = 'black';
        ctx.strokeStyle = 'white';
        ctx.lineWidth=5;
        ctx.stroke();
        ctx.fill();
        ctx.closePath();
    }
}

//Draw box function
function drawRect(xPos, yPos)
{
    //draw a square
    ctx.beginPath();
    ctx.rect(xPos,yPos, BOX_WIDTH, BOX_HEIGHT);
    ctx.fillStyle = rectcolor;
    ctx.fill();
    ctx.strokeStyle = 'white';
    ctx.stroke();
}

//Draw colour box function
function drawColorRect(xPos, yPos)
{
    //Change colour after set time
    if(!HasChangedColor)
    {
        HasChangedColor = true;
        setInterval(changeColor,5000);
    }
    ctx.beginPath();
    ctx.rect(xPos,yPos, BOX_WIDTH, BOX_HEIGHT);
    ctx.fillStyle = ColorRectColor;
    ctx.fill();
    ctx.strokeStyle = 'white';
    ctx.stroke();
}

//Change colour function
function changeColor()
{
    ColorRectColor = colors[Math.floor(Math.random() * colors.length)];
    HasChangedColor = false;
}

//Mouse click register function
function hitTestPoint(x1, y1, w1, h1, x2, y2)
{
    //x1, y1 = x and y coordinates of object 1
    //w1, h1 = width and height of object 1
    //x2, y2 = x and y coordinates of object 2 (usually midpt)
    if ((x1 <= x2 && x1+w1 >= x2) &&
        (y1 <= y2 && y1+h1 >= y2))
            return true;
    else
        return false;
}
  • I'm going to wager that the CLICK event is registering properly, but you aren't getting the co-ordinates back that you expect. However, by not posting your HTML and not posting a *MINIMAL* example for someone to look at, we can't tell. A large code dump like this, out of context, is almost useless. – Jeremy J Starcher May 12 '14 at 22:42
  • you might have a look at my answer here, which is fast and quite clean : http://stackoverflow.com/a/20061533/856501 Be sure NOT to do DOM access anywhere in your game after it started. ( document.someObj.someProp is slow as hell. ) – GameAlchemist May 13 '14 at 02:22

0 Answers0