+ 13

Color change with collision [SOLVED]

Iā€™m trying to make a collision code with circles. The primary objective is to change the color of the circles when they collide, but somehow it doesnā€™t work. I can see the collision detection functions, but the colors change only when the circles are next to each other in the array. Can someone please have a look to see what Iā€™m doing wrong? https://code.sololearn.com/WWaxVie9R6cT/?ref=app

25th Jun 2019, 6:41 PM
marjel101
marjel101 - avatar
11 Answers
+ 10
In the loop you are comparing each ball with all other balls. So you actually land in the else { balls[i].noChangeColor(); balls[j].noChangeColor(); } part all the time, and even if the balls changed color at some point they will change right back because likely no ball will ever collide with all other balls. Before the double loop you want a: for(let ball of balls) ball.noChangeColor(); to make them all green, and then just remove that `else` part. I hope that gets you a step closer.
25th Jun 2019, 8:18 PM
Schindlabua
Schindlabua - avatar
+ 11
šŸ¤” Strange they should both change color... Let me make the same with vanilla js.
25th Jun 2019, 8:43 PM
Haris
Haris - avatar
+ 9
Schindlabua Thanks, thatā€™s a great improvement! There is a color change with all collisions now, but why is only one of the circles changing and not both?
25th Jun 2019, 8:34 PM
marjel101
marjel101 - avatar
+ 9
Schindlabua I think you believed it right šŸ˜ƒ It seems to be working now. Thanks so much, iā€™ve been wrecking my brains over this all evening šŸ¤ÆšŸŒ¹šŸŒ¹šŸŒ·šŸŒ·
25th Jun 2019, 8:50 PM
marjel101
marjel101 - avatar
+ 9
A bit late to the party but I did it: https://code.sololearn.com/WD3qgT63kKGb/?ref=app
25th Jun 2019, 10:03 PM
Haris
Haris - avatar
+ 7
Thanks Haris ( exams ) that looks great. I see you basically used a similar solution as Schindlabua , by first setting the color, draw and then reset. I moved my initial setting a bit based on your example now. Thank you both for yet another lesson today šŸ˜ƒšŸŒ¹šŸŒ¹
25th Jun 2019, 10:29 PM
marjel101
marjel101 - avatar
+ 6
I'm not a 100% on that but I believe you want to `.show()` after you have calculated the collisions.
25th Jun 2019, 8:35 PM
Schindlabua
Schindlabua - avatar
+ 4
You're welcome :)
25th Jun 2019, 8:53 PM
Schindlabua
Schindlabua - avatar
+ 4
Jake Skutnik thank you, but this question is already solved šŸ˜Š I took the else statement out of the if else and used the noChangeColor() at another location. Itā€™s working now šŸ˜ƒ
26th Jun 2019, 5:44 PM
marjel101
marjel101 - avatar
+ 3
else { balls [i].noChangeColor(); balls[j].NoChangeColor(); }
26th Jun 2019, 5:17 PM
Jake Skutnik
Jake Skutnik - avatar
0
import turtle as t t.color ("green") t.circle (r)
26th Jun 2019, 6:46 PM
Mahdi