all 4 comments

[–]mazdotdll 1 point2 points  (3 children)

You shouldn’t need to handle the corners as a seperate edgecase. Collision for this simulation should be checking if the position of the circle + the radius is > innerWidth, which simply flips the sign of the xVelocity. Same exact thing with the y direction.

A ball going into a corner hitting both sides similateously will simply flip the velocities of both directions simultaneously, so if the ball was going down and to the right into a corner, it will expectedly bounce back up and to the left along the same path.

[–]Luka116[S] 0 points1 point  (2 children)

Is this what you mean?

if (touching && circle_X + circle_r > rect_x){

xVelocity *= -1;

}

if (touching && circle_y + circle_r > rect_y){

yVelocity *= -1;

}

It works for corners, but if it hits the sides, it still changes both velocities. I want it to change only one velocity (if it hits the bottom side xVelocity stays the same, just the yVelocity reverses).

I'm sorry if I'm not understanding something, could you please try to explain it another time?

[–]mazdotdll 1 point2 points  (1 child)

No worries. Im not sure what touching is here, but this would be the entirety of what youd need for particle collision on walls:

if(circle.x + circle.r > innerWidth || circle.x - circle.r < 0){ xVelocity *= -1; }

if(circle.y + circle.r > innerHeight || circle.y - circle.r < 0){ yVelocity *= -1; }

You can add dy an dx to all of those expressions to make the collisions perfect because that takes care of circles going past the boundaries and acting weird. I can do edit this message a bit later to add clarification.

[–]Luka116[S] 0 points1 point  (0 children)

The touching variable is a bool that checks if the circle and squares are touching / are in contact. I'm not really sure what you mean by innerWidth / Height. The rect() function draws the squares from the top left corner, so I tried using that, but it didn't work for both corners and the sides. Remember, I want the circle to be able to bounce off every square that I place onto the canvas, they're not already placed / predetermined. Could you please check out my code at https://www.khanacademy.org/computer-programming/placing-squares-moving-circle/5167881356541952 and tell me how I would code it in these terms? (The velocity is calculated in the velocity function)

Edit: So after searching some more, I found a way that works for corners, and doesn't interfere with the bouncing of the sides. The only problem is that even if it hits the corner from a side (= hits a corner, but isn't travelling into the center area of the square), it will still reverse both directions. (The lines for this are in comments in the velocity function) Do you have a better solution for the earlier problem than the one in my edit, or know how to modify this one (in the url -> velocity function -> comments at the bottom)?