0
\$\begingroup\$

I'm trying to make an object (ball) fall into position Y and when the ball collides with the base. The sprite changes and along with the change I want the speed of the fall to change according to the sprite

public void create () {
    circleBall = new Circle();
    rectangleBase = new Rectangle();
    ball = new Texture("ball.png"); 
}

public void render () {
    spriteBatch.begin();
    fallBall();
    rand();
    spriteBatch.end();
}

void fallBall(){
    fallSpeed++;
    if(posYBall > 0){
        posYBall -= fallSpeed * 2 / 2;
    }
}

void rand(){
    int rand1 = random.nextInt(15 - 1) + 1;
    int rand2 = random.nextInt(10 - 1) + 1;
    int rand3 = random.nextInt((55 - 35) + 1) + 35;
    collisionBallBase(rand1, rand2, rand3);
}

void collisionBallBase(int rand1, int rand2, int rand3){
    if(Intersector.overlaps(circleBall, rectangleBase)){
        if(rand1 <= 5){
            ball = new Texture("ball.png");
        }else if(rand1 <= 10){
            ball = new Texture("ballb.png");
        }else{
            ball = new Texture("ballc.png");
        }

        if(rand2 >= 5){
            ballDirection = 4;
        }else{
            ballDirection = -4;
        }
        fallSpeed = -rand3;
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Just multiply fallSpeed with a variable that get's changed to some other random value every time your condition is met. You need to generate a random float that varies between, for example, 0.5 and 1.5. \$\endgroup\$ – VaTTeRGeR Feb 20 '19 at 10:30
0
\$\begingroup\$

Instead of calling the rand function in a render, you can call the function when your action happened.

If you want to have a ball with a random speed on creation time do it on the constructor.

If you want the ball to have a random speeds every time for each activity such a collision, set it in the 'on event' function.

If you really want to call a function in a render function then try something like this

boolean collided = false

somefunctionto
if(collided){
   set_random_speed_to_a_ball(..);
   collided = false;
}

render(){
   if(collisionhappend){
   collided = true;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.