+ 1

[JS Canvas Question]How do I make the rectangle go the opposite way?

https://code.sololearn.com/W3V5evcI8Eux/?ref=app Every time I write my collisions, I end up leaving conflicting instructions. Just can't seem to get the object to [collide] then go the opposite way. Well just now I got an idea I can try: if ( o. X >= 0) { <Code to move along +x> (Another)if (o. X + w >= c. W){ <Code to move -x> } } But will that work or what's the best way to do it?

6th Jun 2022, 1:53 PM
pHANTOM|sTEELE
3 odpowiedzi
+ 5
The way i do it is: have a variable (v) Increment the x with said variable. If obj.x > screen.width, v = -v If obj.x < 0, v = -v v could be 1 for example. then, after a certain condition, v becomes -1 Or, if v =-1, after a certain condition it becomes 1. Here, i edited your function: function checkHit() { if(pc1.x >= 0) { pc1.x += pc1.wv; } if(pc1.x + pc1.w >= canv.width || pc1.x < 5) { pc1.wv = -pc1.wv } console.log(x); }
6th Jun 2022, 2:11 PM
🍇 Alex Tușinean 💜
🍇 Alex Tușinean 💜 - avatar
0
Well I actually got the obj to start bouncing back and forth. Now I'm trying to figure out how to use a math fl random to randomize the direction if say x < canv. W & x > 0. Idk we'll see how it goes!
6th Jun 2022, 2:19 PM
pHANTOM|sTEELE
0
You mean, start in a random direction? Pr bounce in a random direction?
7th Jun 2022, 3:53 AM
🍇 Alex Tușinean 💜
🍇 Alex Tușinean 💜 - avatar