In my second assignment I try to create a random moving circle at a constant speed using things we have learnt in the previous lecture.
The first difficulty I met is to achieve randomness. I first wanted to use things like “xpos += random(-10,10)”. However, this statement lets the ball moves randomly within a range and thus failed to remain the constant speed. So I used the Pythagorean theorem instead, since in the cartesian coordinates “(xspeed)^2 + (yspeed)^2 = (speed)^2”.
But a new problem came. In this sense xspeed and yspeed are both positive since I used the expression “yspeed = sqrt(speed^2 – xspeed^2)”. But a in a random movement the circle should be able to go to any direction. So I introduced a new random variable xrandom ranging from -1 to 1. If xrandom is negative, the x coordinate decreases and if it is positive, x increases. Similar is the case of y coordinate. And with this method randomness is ensured.
However, after I finished this I realized using polar coordinates instead of cartesian coordinates is a better idea. As the angle θ ranges from -π to π, sinθ and cosθ range from -r to r. Thus there is no need to introduce a new variable to guarantee randomness.
Another problem is to constrain the circle inside the canvas. I didn’t know of the function constrain() so I used several if statements to achieve this. Then I merged these statements with the ones to ensure randomness.
Lastly I tried to extract the random moving circle as a function. I set the diameter and the speed of the circle as parameters. I may add some buttons or sliders to control the speed and diameters.
(Click any key to start the movement.)