C++ Fundamentals/ dapper-dasher

Hi there,

I need some assistance with understanding the collision detection section of dapper-dasher.

We create the range based for loop to represent certain aspects of the nebula hazards in this case the X and y positions and width and height.

It is done as follows:

for(AnimData nebula : nebulae){

Rectangle nebRec{

nebula.pos.x + pad,
nebula pos.y + pad,
nebula.rec.width - 2pad,
nebula.rec.height - 2
pad

}

}

The issue I am having is I don’t understand how this 2*pad works.

It’s supposed to draw a rectangle around the nebula for collision detection but how is this done because the value of pad is 20 so 2*pad =40.

Can explain this code please

Consider this sketch:

grafik

The nebula texture has a lot of space on each side of the actual nebula to allow for its irregular shape. This space is the pad. You don’t want the player to die for touching the pad, only for touching the inner part.

So you calculate the collision rect (red) like this:

  • Its upper left corner is obtained by going down and to the right by 1 pad from the image’s upper left corner.
  • Its size is obtained by subracting the pad from the overall image’s size two times for each direction, because it appears on top, bottom, left and right.

As I said, I might be understanding this completely wrong but pad = 20 pixels.

I understand that we located the upper left corner by adding 20 to X and 20 to y which puts the upper left corner by the actual nebula.

But I’m not getting how 2*pad subtracts pad from both sides.

The width of the whole nebula image is 100 px. The first 20 px is pad, the next 60 px is the width of the collision rect (but we don’t know this number yet), then there are 20 px of pad again. In other terms:
image width = pad + collision rect width + pad = 2 pad + collision rect width
Thus: collision rect width = image width - 2 pad

Same for height.

Maybe the confusion is that x and y are coordinates (changing with the movement of the nebula), while width and height remain the same (thus it could be argued that calculating them repeatedly, as we do, is not too elegant). They don’t move around. If you want to know where the bottom right corner of the rectangle is on the screen, you need to calculate x + width and y + height, for any rectangle given by x, y, width and height.

I believe Desmond and I already spoke about this in a duplicate question on Udemy, but I thought this 2-step demonstration was helpful in explaining why the 2*pad was needed for the right and bottom edges of the collision rectangle.

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms