This ball goes through the rectangle rather than hitting it or bouncing it

Interesting question because as a very experienced programmer I can see many problems / issues with your code (apart from the collision detection) which occur frequently with novice programmers. So I would not be interested at hacking your code just to get it to work. It would be like trying to weld a patch over a hole in a rusty bucket - cover one hole only to make another hole elsewhere.

If you are interested I can show you how to create a simple sketch that does what you are looking for using good programming practice. It would involve looking more closely at structured programming and algorithm design especially the collision detection algorithm to produce more generic code.

By the time we were finished you will have learnt a lot about structured programming, algorithm design and have a good working program.

The downside is that it would take several days to do this in sufficient detail, so its up to you to decide what you want to get out of doing this.

3 Likes

Hi @quark, Sorry for the Late Reply. I think hacking my code just to get it to work is better. But could you also please tell me what other problems you have identified in this.

Good luck with that.

I will identify one - magic numbers - in this case you are using numbers directly to represent the box position and size for

  1. displaying the rectangle
  2. collision detection

It means that if you want to change the position or size of the rectangle then you have remember to modify the collision detection. Not only that look at this code …

  if (ballx <= mouseX+300 && bally > 880 && bally < 955) {
    xspeed = xspeed*-1;
  }

what is the meaning of 300, 880 and 955, anyone reading this code would have no idea. It is better to use named variables or named constants.

Other issues are related to program structure so it is not worth my time discussing them if all you want to do is hack the code you have.

Final words of advice - hacking code to get something to work does not beat having a good program design/structure and a clear understanding of the algorithms used.

Bonne chance :smiley:

Thank You for identifying all of these problems but can you actually help me hacking my codes.
Thank You

Just to remind you of what I said in a previous post

So am I allowed to open a new tread for solving this problem

That is a good idea as this one is very long so might put people off reading it but do not delete anything in this discussion :smiley: