Skip to content Skip to sidebar Skip to footer

Adding Collision To Rectangles So Sprite Wont Go Through?

I am trying making a collecting game. It's still in a work in progress. What I am trying to accomplish is add collision detection to the rectangle on the canvas so the sprite won't

Solution 1:

The only thing you are missing is to save the coordinates of your rectangles somewhere. A good place for this would be an array. I see that you have created a function to draw all the rectangles under the image but as you can read here that canvas will not remember where the rectangles are.

So What you can do is to create a new array (lets call it wallsArr) and inside your drawWalls function you can just push your coordinates to that array so after all your drawWalls function will look something like this:

functiondrawWalls(){wallsArr.push({name:"wall1",x:105.3,y:-1,width:14.1,height:73.5});wallsArr.push({name:"wall2",x:366.5,y:-1,width:14.1,height:73.5});wallsArr.push({name:"wall3",x:367,y:173.2,width:120,height:14.1});wallsArr.push({name:"wall4",x:-1,y:173.2,width:120,height:14.1});wallsArr.push({name:"wall5",x:105.3,y:267.5,width:14.1,height:73.5})wallsArr.push({name:"wall6",x:366.5,y:267.5,width:14.1,height:73.5});}

you might want to rename the function to something else since it is not actually drawing anything and don't forget to call the function once like so: drawWalls()

To simulate a collision you might want to do a collision function like this one:

functioncollidingWith(object){
  console.log("you are colliding with:", object.name);
}

And then to detect the collition you would need to loop through the walls (or all the object you want to be able to collide with) on each move. So for example inside the moveCharacter function you could do:

wallsArr.forEach(wall=>{
  if( positionX + deltaX + SCALED_WIDTH > wall.x
    && positionX + deltaX < wall.x+wall.width
    && positionY + deltaY + SCALED_HEIGHT > wall.y
    && positionY + deltaY < wall.y+wall.height
  ){
    collidingWith(wall);
  }
})

Then you should be able to see what wall your character is colliding with at any time. Of course you can do this much more general if you want to be able to collide with the other objects there but hopefully you get the idea and can continue from here.

Good luck with the rest!

Post a Comment for "Adding Collision To Rectangles So Sprite Wont Go Through?"