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

2015/10/4

dodgeball game

devoncnp devoncnp

2015/10/4

#
need help with dodgeball game. i need it so the character can pick up the ball, and throw it to its left whenever a button is pressed.
import greenfoot.*;

/**
 * Write a description of class Char1 here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Char1 extends Mover
{
    
    
    private int balls;
    private int direction;
    
    public Char1()
    {
        balls = 0;
    }
    
    public void act() 
    {
        movement();
        checkCollision();
    }    
    public void movement()
    {
        if (Greenfoot.isKeyDown("left"))
        {
            move(-2);
        }
        if (Greenfoot.isKeyDown("right"))
        {
            move(2);
        }
        if (Greenfoot.isKeyDown("up"))
        {
            setLocation(getX(), getY()-2);
        }
        if (Greenfoot.isKeyDown("down"))
        {
           setLocation(getX(), getY()+2);
        }
   }
   
}
ElNo ElNo

2015/10/9

#
Hi, I used your code and added the two Methods checkCollision() and throwBall(). You will need a new Subclass of Actor (Ball) for it to work.
import greenfoot.*;
 
/**
 * Write a description of class Char1 here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Char1 extends Mover
{
     
     
    private int balls;
    private int direction;
     
    public Char1()
    {
        balls = 0;
    }
     
    public void act() 
    {
        movement();
        checkCollision();
        throwBall();
    }    
    public void movement()
    {
        if (Greenfoot.isKeyDown("left"))
        {
            move(-2);
        }
        if (Greenfoot.isKeyDown("right"))
        {
            move(2);
        }
        if (Greenfoot.isKeyDown("up"))
        {
            setLocation(getX(), getY()-2);
        }
        if (Greenfoot.isKeyDown("down"))
        {
           setLocation(getX(), getY()+2);
        }
   }
    
   public void checkCollision()
   {
       if(isTouching(Ball.class))
       {
           balls++;
           removeTouching(Ball.class);
       }
    }
    
    public void throwBall()
    {
        if (Greenfoot.isKeyDown("space") && balls > 0)
        {
            balls--;
            getWorld().addObject(new Ball(), getX()-50, getY());            
        }
    }
}
You need to login to post a reply.