I am making a simple click the ball game called popThatBall, I have used classes to create the ball and push it multiple times to an array using a for loop.
I am wanting to make it so the ball bounces out from the middle in different directions, rather than following the same directions. I have tried to write a solution to my problem using random and iterating through an array of positive and negative numbers (which is what I was told I should try), but it all follows the same direction and goes to the bottom right hand corner, which is what I don't understand.
Here is a gif of what is currently happening:
Here is the move() function currently being called when the ball is being created:
Also here is the posRange and negRange array used to cycle through random numbers
let posRange = [1,2,3,4,5,7,8,9]
let negRange = [6,7,8,9,10,11,12]
move() {
// checking if the ball is still in its start postion
if (this.center) {
// push the ball out with the directon (speed) that matches the range
this.speedX = random(posRange)
// again with Y direction
this.speedY = random(negRange)
// move ball across X axis
this.x = this.x + this.speedX;
// move ball across Y axis
this.y = this.y + this.speedY;
// the ball is no longer in the center
// reset speed variables to orginal values.
this.speedX = this.speeds[0]
this.speedY = this.speeds[1]
this.center = false;
}else if(!this.center){
this.x = this.x + this.speedX;
this.y = this.y + this.speedY;
}
This may not be relevant but will include the gm_createBalls which is called during the draw function.
function gm_activateBalls(){
for (let i = 0; i < Balls.length; i++) {
Balls[i].show()
Balls[i].move()
}
}
Your random()
function to initialize the speed values only returns positive values. You could, for example, use this.speedX = random(-1, 1)
to choose any random value between -1 and 1 and thus also allow for "negative" speeds (ie, some of your balls initially going to the left).
Use a function similar to this:
this.speedX *= random(-1,1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.