How to add border collision JavaScript? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to add border collision JavaScript?

I have made a simple canvas with a red square that can be controlled and moved using buttons and translation, however I want to add collision with the border of the canvas so that you cannot move any further when touching the borders. Is this possible and if so how can it be done in my code I’ve included below? https://code.sololearn.com/WmHHQeq1wgR5/?ref=app Thank you

23rd Jun 2021, 9:30 PM
Alex
Alex - avatar
2 Answers
+ 1
Hi Alex What you’ll need to do is get the width of half the square and subtract it from the the current position like: Pseudocode: If(Xposistion - half_width_square <= 0) { Don’t move }
23rd Jun 2021, 9:53 PM
Ollie Q
Ollie Q - avatar
+ 1
Alex added "border collision" and made changes to make your code responsive, as well as working in any context (sololearn app / website or standalone file): https://code.sololearn.com/W2FZtC6mVVwf/?ref=app
24th Jun 2021, 4:48 PM
visph
visph - avatar