Hello. i have an assignment where i need to have a ball that when starting needs to go either left OR right.
my first thought was to give my “speed” variable at the setup “= random (-3 ||+3)”. But it still starts att different values between -3 and +3 as well as only being able to go one direction when i try to run the code.
How about 3 * (1-2*Math.floor(2 * Math.random()))? Math.floor(2 * Math.random()) returns 0 or 1. 1-2*random can be 1 or -1 then. Multiply by 3 and you are done.
Math.random() gives a random float in 0…1 (1 excluded). Multiplying by 2 gives a value in the range of 0…2, so for example 0.3, 1.34, 0.76, 1.76.
The floor function removes the part after the decimal point (at least for positive input values), making it 0 or 1.