2

I have the following code in my requestAnimationFrame loop:

    //move obstacles
    game.obstacles.forEach(function(obstacle, index) {
        obstacle.shape.left-=OBSTACLE_SPEED
        
        //if outside to the left of canvas remove element, 
        //splice: https://stackoverflow.com/questions/9882284/
        //index in foreach: https://stackoverflow.com/questions/10179815/
        if (obstacle.shape.left < 0-OBSTACLE_SIZE*2) {
            game.obstacles.splice(index, 1) //removes invisible obstacle
            console.log("obstacles.size: " + game.obstacles.length)
            addObstacle() //adds new obstacle
        }

        //check if player intersects with obstacle
        //console.log("intersects? " + obstacle.shape.intersectsWithObject(player.avatar))
        if (obstacle.shape.intersectsWithObject(player.avatar)) {
            console.log("YO ITS OVER!")
            alert("asdas")
        }

    })

obstacle.shape are fabricjs.Rect objects and player.avatar is a fabricjs.Circle object.

any idea why the obstacle.shape.intersectsWithObject(player.avatar) always returns false even though they are visibly clipping in the game?

player.avatar is also drawn by adjusting player.avatar.top or .left and I draw everything by calling canvas.renderAll()

    if (player.moving == true ) { //move player
        //console.log("moving")
        player.avatar.top+=player.dy
    }
    //console.log(player.avatar.top)
    canvas.renderAll()

I am basically trying to achieve the basic functionality of this game: https://www.youtube.com/watch?v=WtsMbQRViFE

jteichert
  • 527
  • 1
  • 4
  • 20
  • 1
    The only thing I your code that might cause some trouble is: `game.obstacles.splice(index, 1)`. What happens if you leave out the left boundary check completely (just for testing of course)? Can you post a working example of your code that clearly shows the issue? – obscure Mar 20 '21 at 12:08
  • I got it to work when using only circles also for the obstacles which is fine for now. What also helped with accuracy was calling ```setCoords()``` after moving objects on the canvas. – jteichert Mar 20 '21 at 17:48
  • 1
    Fabricjs is not made for games, there are many other libraries that are specifically made for html canvas games, try those. – Gitesh Sharma Mar 26 '21 at 15:32

0 Answers0