This site requires JavaScript, please enable it in your browser!
Greenfoot back
AdiBak
AdiBak wrote ...

2019/4/26

Random Rotation

AdiBak AdiBak

2019/4/26

#
Hello, I'm trying to make a "kick-ups" game, where the player tries to keep a ball in the air without letting it fall on ground, by clicking on it, but I'm having trouble making the ball turn by some amount every kick, which I want to accomplish. Can someone please help? Thank you. Here's code for Ball class:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Ball here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Ball extends Actor
{
    private final int GRAV = 1;
    private int velocity;
    public Ball(){
        velocity = 0;
        getImage().scale(50, 50);
    }

    /**
     * Act - do whatever the Ball wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        // Add your action code here.
        
        if (Greenfoot.mouseClicked(this)){
            int amo = -30 + Greenfoot.getRandomNumber(70);
            turn(amo);
            jump();
        }
        fall();
    }    

    public void fall(){
        setLocation(getX(), getY() + velocity);
        if (getY() > getWorld().getHeight() - getImage().getHeight()/2){
            velocity = 0;
        } else {
            velocity += GRAV;
        }
    }

    public void jump(){

        velocity = -20;

    }
}
danpost danpost

2019/4/26

#
I am quite sure your ball is turning (rotating to different angles). However, velocity is only used for vertical movement and nowhere are you even trying to change the x-coordinate value returned by getX in your setLocation calls.
AdiBak AdiBak

2019/4/26

#
Can you please show me how I can do that?
danpost danpost

2019/4/26

#
AdiBak wrote...
Can you please show me how I can do that?
The simplest way is to add an int field for speed along the horizontal and add it to the getX in your setLocation call. Alter its value to some random number within some range of zero when click is detected (instead of turning).
AdiBak AdiBak

2019/4/26

#
Thanks, it worked!
You need to login to post a reply.