How to add a score and collision detection between fruit and myAvatar?

<html>
    <head>
    <script type='text/javascript' src='script.js'></script>
    <link rel='stylesheet' type='text/css' href='style.css'>
    <style>
    canvas {
    border: 1px solid #d3d3d3;
    margin-left: auto;
    margin-right: auto;
    }
    </style>
    </head>
    <body id="main1" background="Background.jpg" onload="startGame()">
    <p id="text1">TIME: </p><div id="timer"></div>
    <script type="text/javascript">
    function countdown (minutes){
        var seconds = 60;
        var mins = minutes;
        function tick(){
            var counter = document.getElementById("timer");
            var current_minutes = mins-1;
            seconds--;
            counter.innerHTML = "0" + current_minutes.toString() + ":" + (seconds < 10 ? "0":"") + String(seconds);
            if(seconds > 0){
                setTimeout(tick,1000);//time will countdown every 1 second
            }else{
                if(mins > 1){
                setTimeout(function(){countdown(mins-1);},1000);
                }
            }
        }
        tick();//to execute or run the function tick()
    }
    countdown(3);//declare the time in 3 minutes
    </script>
    <p id="score">SCORE: </p><div id="txtscore"></div>
    <script>
    //to display avatar and background when start game
    var myAvatar;
    var myBackground;
//  var score = 0;
//  document.getElementById("txtscore").innerHTML = score;
    function startGame() {
    myAvatar = new component(80, 80, "Avatar1.jpg", 240, 560, "image");
    myBackground = new component(560, 640, "Forest.jpg", 0 , 0 , "image");
    myGameArea.start();
    fruitFall();
    }
    var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 560;
        this.canvas.height = 640;
        console.log(this.canvas.width);
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
   //     this.frameNo = 0;
        this.interval = setInterval(updateGameArea, 5);// to repeat execution of function updateGameArea every 20 milliseconds
        //function for movement
        window.addEventListener("keydown", function(e){
            myGameArea.key = e.keyCode;
        })
        window.addEventListener("keyup", function(e){
            myGameArea.key = false;
        })
        },
        clear : function() {//to clear the game area from avatar so there is no duplicated avatar
            this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
        },
        stop : function() {
            clearInterval(this.interval);
        }
    //  console.log(this.canvas.width);
    }
//  console.log(this.canvas.width);
//declare the image
picture = new Array(5)
Image0 = new Image();
Image0.src = picture[0] = "Apple.jpg";
Image1 = new Image();
Image1.src = picture[1] = "Banana.jpg";
Image2 = new Image();
Image2.src = picture[2] = "Grape.jpg";
Image3 = new Image();
Image3.src = picture[3] = "Pineapple.jpg";
Image4 = new Image();
Image4.src = picture[4] = "Strawberry.jpg";
yPos = new Array();
xPos = new Array();
Speed = new Array();
var Stop=false;
    //render the picture
    for(i=0;i<picture.length;i++)
    {
        var x = Math.floor(Math.random()*picture.length);
        renderPic = picture[x];
        document.write('<img id ="pic'+ i +'" src="'+ renderPic +'"style="position:absolute;top:10px;left:397px;width:50px;height:50px">');
    console.log(picture.length);

    }
    winHeight = document.body.clientHeight;//height of the body
    winWidth = document.body.clientWidth;// width of the body
    //for the speed and the position of x and y of image
    //this.canvas.height = 640;
//  this.canvas.width = 560;
    for(i=0;i<picture.length;i++){
        yPos[i] = Math.round(Math.random()*winHeight);
        xPos[i] = Math.round(Math.random()*winWidth);
        Speed[i] = Math.random()*5 + 3;
    }
    //Falling the fruits
    function fruitFall(){
        if(Stop){
        clear();
        return;
        }
        var winHeight = document.body.clientHeight;
        //var winWidth = document.body.clientWidth-200;
        var score = 0;
    //var x = this.canvas.width - 100;
    //var y =this.canvas.height - 100;
        for(i=0;i<picture.length;i++){
            speedY = Speed[i]*Math.sin(90*Math.PI/180);
            yPos[i]+= speedY;
        //  if(Ypos[i] > ){
        //  score++;
        //  }
        //  document.getElementById("txtscore").innerHTML = score;
        //  if((Ypos[i] > winHeight - (myAvatar.height+20))&& (Xpos[i] <= myAvatar.x) && (Xpos[i] >= myAvatar.x)){
        //      score++;
        //  }
            if(yPos[i] > winHeight - 110){
                yPos[i] = 0; // back to 0 for Y position
                xPos[i] = Math.round(Math.random()*winWidth);
                Speed[i] = Math.random()*5 + 3;
            //  score++;
            }
        //  else if(Ypos[i] > this.canvas.height - myAvatar.width){
        //      score++;
        //  }
            else{
                document.getElementById("pic"+i).style.left = Math.min(winWidth,xPos[i])-200;
                document.getElementById("pic"+i).style.top = yPos[i];
            }
            document.getElementById("txtscore").innerHTML = score;
        }
        setTimeout('fruitFall()',20);//function fall will execute every 20 miliseconds
    }
    setTimeout("Stop=true",180000);
    //clear the image
    function clear(){
        for(i=0;i<picture.length;i++){
        document.getElementById("pic"+i).style.display = 'none';
        }
    }
    function component(width, height, color, x, y, type) {
        this.type = type;
            if (type == "image") {
                this.image = new Image();
                this.image.src = color;
            }
        this.width = width;
        this.height = height;
        this.speedX = 0;
        this.speedY = 0;    
        this.x = x;
        this.y = y;   
        this.update = function() {
            ctx = myGameArea.context;
            if (type == "image") {
                ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
            } else {
                ctx.fillStyle = color;
                ctx.fillRect(this.x, this.y, this.width, this.height);
            }
        }
        this.newPos = function() {
            this.x += this.speedX;
            this.y += this.speedY;    
        }
    }
/*  function isCollide(fruitIdx){
    var bWidth, bTop;
    var collide = false;
    if(window.getComputedStyle){
        bWidth = parseInt(getComputedStyle(myAvatar,null)["width"], 10);
        bTop = parseInt(getComputedStyle(myAvatar,null)["top"], 10);
    }
    else{
        bWidth = parseInt(myAvatar.currentStyle["width"],10);
        bTop = parseInt(myAvatar.currentStyle["top"], 10);
    }
    if(isNaN(fruitIdx) && fruitIdx >= 0 && fruitIdx < picture.length){
        var checkFruit = document.getElementById("pic"+fruitIdx);
    if(myAvatar.speedX <= xPos[fruitIdx] && (myAvatar.speedX+bWidth)>= xPos[fruitIdx] && (bTop-yPos[fruitIdx]) < parseInt(        checkFruit.style.height, 10)){
        console.log("collision: " +1);
        return true;
    }
    }else{
        for(var i = 0;i<picture.length;i++){
        var fruit = document.getElementById("pic"+i);
        if(myAvatar.speedX <= xPos[i] && (myAvatar.speedX+bWidth) >= xPos[i] && (bTop-yPos[i]) < -5){
        collide = true;
        console.log("Collision: "+i);
        }
        }
    }
    return collide;
    }*/
    function updateGameArea() {
        myGameArea.clear();
        myBackground.newPos();
        myBackground.update();
        myAvatar.speedX = 0;
    //  score = 0;
    //  for(i=0;i<picture.length;i++){
        //speedY = Speed[i]*Math.sin(90*Math.PI/180);
    //  Ypos[i] = Math.round(Math.random()*winHeight);
    //  Ypos[i]+= speedY;
        if(myGameArea.key == 37){
        isCollide();
        myAvatar.speedX = -2;
            if(myAvatar.x  < 0){
            myAvatar.x = 0;
            }
    //  isCollide();
        }//left button
        else if(myGameArea.key == 39){
        myAvatar.speedX = 2;
        isCollide();
            if(myAvatar.x  > 480){
            myAvatar.x = 480;
            }
        //isCollide();
        }//right button
        myAvatar.newPos();
        myAvatar.update();
    }
    </script>
    </body>
</html>

I think folk are downvoting because you are dumping code and not much else. Try something. Tell what line or function is giving you trouble.

Also, duplicate posts like yours at https://www.daniweb.com/programming/game-development/threads/504035/how-to-add-a-score-and-collision-detection-for-my-catching-game- can get you a downvote.

Maybe start on a smaller app that only changes the score when folk click a button. That way you build you skills and figure out how to keep score.

I think folk are downvoting because you are dumping code and not much else. Try something. Tell what line or function is giving you trouble.

Yes, think about it, OP. The people helping you have to put more effort into helping you than the amount of effort that you made constructing the post. There are other files that are involved here which you have not attached, so we can't "try out your code". Generally people won't open up a zip file and run the code in a situation like this, but if one of us was willing to do that, we would not be able to because you have not attached the zip file. You give us no hint of what the code is supposed to do, you give us not hint of your experience level, you do not tell us what you think the problem is, etc. We have to guess at all of this. When asking questions of strangers volunteering their time for no pay, you need to make it as easy as possible for them to figure out what the problem is and to test your code. You also need to make clear that you have put in effort. You have done neither.

Also, duplicate posts like yours at https://www.daniweb.com/programming/game-development/threads/504035/how-to-add-a-score-and-collision-detection-for-my-catching-game- can get you a downvote.

Also true. Suppose I spent 15 minutes or a half hour or however long it took trying to answer your question and then I found out that someone else had already answered it on some other thread or another forum. I would feel like you were wasting my time. Again, we are not paid to help and we all had to put in the work to learn how to code. We'll help out, but the key word here is "help". Again, you have to put in the bulk of the effort. I answered a C question this morning because the person asking it was stuck, but it was clear he had put in some effort.

I am confused in where, I must add a score and how to add a score. I already think it for 2 days but I still can't find the solution. I just want to know how to make a collision detection between myAvatar and fruit so when it collides it will be increase the score

Let me read your article "tags". I see " development game games gaming project " but you left off the language. Remember that reply about you having to put in the bulk of the effort?

Collision detection is a very done topic. I double checked with https://www.google.com/#q=collision%20detection%20javascript

Doing this from scratch means you have to read a lot and start small. Frankly I'd look into a 2d game engine but this is not something you do without investing months of work.

Collision detection can potentially be fairly easy depending on the game and the answer to "How good is good enough?" If you are looking at two circles in a two-dimensional world travelling at constant speed with no "forces" acting on them (i.e. no gravity, no acceleration, balls not spinning, etc. etc.), you can plot the center of each circle at a given time t. If the distance between the centers is less than the sum of their radii (plural of "radius". Wikipedia says you can use "radiuses" here. Anyway, you know what I mean :)), the two circles intersect, which means that they must have collided at some point.

At that point, to simplify things, just pretend they intersected at time t. Make it a 100% elastic collision and dust off the old Physics book and you can figure out the new direction of each ball fairly easily. If you recalculate everything and repaint everything 32 times per second, you can have a fairly cool "close enough" game without TOO MUCH effort. Add in a few walls that the circles can bounce off, add in some squares or triangles or rectangles or arcs, hexagons, etc. and your program becomes more complex, but still manageable if you stick with the easy geometric shapes. Add in INELASTIC collisions, add in rotating shapes, and trying to calculate exactly when the shapes collide and you have added non-trivial coding/calculating time. Add in more complex shapes which are a set of primitive shapes (i.e. a person with a circle for a head and rectangles for other body parts) and it's still doable without being a Physics whiz or spending months and months of time. Beyond THAT, go ahead and use one of the existing engines or prepare to make this your life's work.

Personally I've always enjoyed making games with very simplified graphics and writing the whole thing on my own. You can ALWAYS add more complexity, but just remember that you are oversimplifying everything. I started with one ball zipping around in a box, then added a ball, then added...

commented: This has balls. +9
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.