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

2022/1/12

I'm trying to add a "superbody", please help?

SportingLife7 SportingLife7

2022/1/12

#
I'm trying to add a superbody class into my scenario. I want to make it interact with the bodies from the body class (they are interacting with gravity), and I want to add it in when the key "z" is pressed and remove it when "x" is pressed and be able control the movement with the arrow keys. ANY help is truly appreciated or guidance to how to do it ? Space Class
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;
/**
 * Space. The final frontier. 
 * 
 * @author Michael Kolling
 * @version 1.0
 */
public class Space extends World
{
    private String[] soundFiles =
        {"3c", "3d", "3e", "3f", "3g", "3a", "3b", "4c", "4d","4e", "4f", "4g"};
    /**
     * Create space.
     */
    public Space()
    {    
        super(960, 620, 1);
        makeObstacles();
        //randomBodies (5); // uncomment to start with 5 random bodies when world iniiated
        // Uncomment one of the following method calls if you want the objects created automatically:

        //sunAndPlanet();
        //sunAndTwoPlanets();
        //sunPlanetMoon();
    }

    /**
     * implements our action methods in our world
     */
    public void act()
    {
        checkKeys();
        addPlanetsWithMouse();
    }

    /**
     * Set up the universe with a sun and a planet.
     */
    public void sunAndPlanet()
    {
        removeAllObjects();
        addObject (new Body (50, 240.0, new Vector(270, 0.03), new Color(255, 216, 0)), 460, 270);
        addObject (new Body (20, 4.2, new Vector(90, 2.2), new Color(0, 124, 196)), 695, 260);
    }

    /**
     * Set up the universe with a sun and two planets.
     */
    public void sunAndTwoPlanets()
    {
        removeAllObjects();
        addObject (new Body (50, 240.0, new Vector(270, 0.0), new Color(255, 216, 0)), 460, 310);
        addObject (new Body (20, 4.2, new Vector(90, 2.2), new Color(0, 124, 196)), 695, 300);
        addObject (new Body (24, 4.6, new Vector(270, 1.8), new Color(248, 160, 86)), 180, 290);
    }

    /**
     * Set up the universe with a sun, a planet, and a moon.
     */
    public void sunPlanetMoon()
    {
        removeAllObjects();
        addObject (new Body (50, 240.0, new Vector(270, 0.0), new Color(255, 216, 0)), 460, 270);
        addObject (new Body (20, 4.2, new Vector(90, 2.2), new Color(0, 124, 196)), 720, 260);
        addObject (new Body (5, 0.8, new Vector(90, 3.25), new Color(240, 220, 96)), 748, 260);
    }

    /**
     * It will create the obtacles in the world.
     */
    public void makeObstacles()
    {
        int i = 0;
        for (i = 0; i < soundFiles.length; i++) 
        {
            //addObject (new Obstacle (soundFiles [i] + ".wav"), 150 + i*60, 310);
            // this one(above)is specifically for the middle row requirement
            addObject (new Obstacle (soundFiles [i] + ".wav"), 100 + i*70, 5);//horizontal
            addObject (new Obstacle (soundFiles [i] + ".wav"), 100 + i*70, 615);//horizontal
            addObject (new Obstacle (soundFiles [i] + ".wav"), 15 + 10, i*55);//vertical walls
            addObject (new Obstacle (soundFiles [i] + ".wav"), 925 + 10, i*55);//vertical walls
        }
    }

    /**
     * this method generates random bodies in our world
     */
    public void randomBodies (int n)
    {

        removeObjects(getObjects(Body.class));
        for (int i = 0; i < n; i++)
        {

            int s = 20 + Greenfoot.getRandomNumber(30);
            double m = Greenfoot.getRandomNumber(75)+10;
            double speed = Greenfoot.getRandomNumber(40) / 25;
            int d = Greenfoot.getRandomNumber(360);
            int x = Greenfoot.getRandomNumber(getWidth());
            int y = Greenfoot.getRandomNumber(getHeight());
            int r =  Greenfoot.getRandomNumber(255);
            int g =  Greenfoot.getRandomNumber(255);
            int b =  Greenfoot.getRandomNumber(255);
            addObject (new Body (s, m, new Vector(d, speed), new Color(r, g, b)), x, y);

        }
    }

    /**
     * keys press method for generating the number of bodies in the world
     */
    public void checkKeys()
    {
        // find a way like in the piano code, to ameliorate this, maybe with a counter
        // that we can increase the # of random bodies without having to write these 
        // 12 lines of code! THIS IS CAUSING LAGGING IN THE PROGRAM!! FIX BEFORE CONTINUING!
        String key = Greenfoot.getKey();
        if (key == null) return;
        int index = "0123456789".indexOf(key);
        if (index < 0) return;
        randomBodies(index);
        if (Greenfoot.isKeyDown("z"))
        {

            // int s = 20 + Greenfoot.getRandomNumber(30);
            // double m = Greenfoot.getRandomNumber(75)+10;
            // double speed = Greenfoot.getRandomNumber(40) / 25;
            // int d = Greenfoot.getRandomNumber(360);
             //int x = Greenfoot.getRandomNumber(getWidth()/2);
             //int y = Greenfoot.getRandomNumber(getHeight()/2);
            //addObject(new SuperBody);
        }
        if (Greenfoot.isKeyDown("x"))
        {
            removeObjects (getObjects(SuperBody.class));
        }
        //i edited the below out for the reduction of lagging in the program (YAY!)
        // if (Greenfoot.isKeyDown("1"))
        // {
        // randomBodies(1);
        // }
        // else if (Greenfoot.isKeyDown("2")) 
        // {
        // randomBodies(2);
        // }
        // else if (Greenfoot.isKeyDown("3")) 
        // {
        // randomBodies(3);
        // }
        // else if (Greenfoot.isKeyDown("4")) 
        // {
        // randomBodies(4);
        // }
        // else if (Greenfoot.isKeyDown("5")) 
        // {
        // randomBodies(5);
        // }
        // else if (Greenfoot.isKeyDown("6")) 
        // {
        // randomBodies(6);
        // }
        // else if (Greenfoot.isKeyDown("7")) 
        // {
        // randomBodies(7);
        // }
        // else if (Greenfoot.isKeyDown("8"))
        // {
        // randomBodies(8);
        // }
        // else if (Greenfoot.isKeyDown("9"))
        // {
        // randomBodies(9);
        // }
        // else if (Greenfoot.isKeyDown("0")) 
        // {
        // removeObjects (getObjects(Body.class));
        // //or you can write...
        // //randomBodies(0);
    }

    /**
     * 
     */
    private void addPlanetsWithMouse()
    {
        // MouseInfo mouse = Greenfoot.getMouseInfo();
        if(Greenfoot.mouseClicked(null))
        {
            MouseInfo mouse = Greenfoot.getMouseInfo();
            if (mouse.getButton() == 1)
            {
                //   Body body = new Body (Greenfoot.getRandomNumber(41));
                //   addObject (body, mouse.getX(), mouse.getY());
                int s = 20 + Greenfoot.getRandomNumber(30);
                double m = Greenfoot.getRandomNumber(75)+10;
                double speed = Greenfoot.getRandomNumber(40) / 25;
                int d = Greenfoot.getRandomNumber(360);
                int x = (mouse.getX());
                int y = (mouse.getY());
                // int x = Greenfoot.getRandomNumber(mouse.getX()); i edited out the random Number thing and the
                // int y = Greenfoot.getRandomNumber(mouse.getY()); ball started generating at the mouse point
                int r =  Greenfoot.getRandomNumber(255);
                int g =  Greenfoot.getRandomNumber(255);
                int b =  Greenfoot.getRandomNumber(255);
                addObject (new Body (s, m, new Vector(d, speed), new Color(r, g, b)), x, y);

                // Bodies++;
            }
            Actor body = mouse.getActor();
            if (mouse.getButton() == 3)
            {
                //if (body!= null && body.getClass() == Body.class)
                // line above was not working, I edited out for the line below
                if (body != null && (body instanceof Body))
                {
                    removeObject(body);
                }
            }
        }

    }
    /**
     * Remove all objects currently in the world.
     */
    private void removeAllObjects()
    {
        removeObjects (getObjects(Actor.class));
    }

}
SuperBody class:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;
/**
 * Write a description of class SuperBody here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class SuperBody extends SmoothMover
{
    private static final double GRAVITY = 5.8;
    private static final Color defaultColor = new Color(255, 216, 0);
    //public double mass;
    //private int size;
    /**
     * Act - do whatever the SuperBody wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        move();
        //applyForces();
        
    } 
    // public SuperBody(int size, double mass, Vector movement)
    // {
        // this.size = size;
        // this.mass = mass;
        // addForce(movement);
    // }
    // /**
     // * Return the mass of this body.
     // */
    // public double getMass()
    // {
        // return mass;
    // }
    // /**
     // * 
     // */
    // private void applyForces()
    // {
       // List<Body> bodies = getWorld().getObjects(Body.class);
       
       // for (Body body : bodies)
       // {
           // if (body!= null)
           // {
               // applyGravity (body);
            // }
        // }
    // }
    // /**
     // * apply the gravity force of a given body to this one
     // */
    // private void applyGravity(Body other)
    // {
        // double dx = other.getExactX() - this.getExactX();
        // double dy = other.getExactY() - this.getExactY();
        // Vector force = new Vector (dx,dy);
        // double distance = Math.sqrt (dx * dx + dy * dy);
        // double strength = GRAVITY * this.mass * other.mass / (distance * distance);
        // double acceleration = strength / this.mass;
        // force.setLength (acceleration);
        // addForce (force);
    // }
}
Body class:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;

/**
 * A 'Body' is any kind of object in space that has a mass. It could be a star, or a planet, 
 * or anything else that floats around in space.
 * 
 * @author Michael Kolling 
 * @version 0.1
 */
public class Body extends SmoothMover
{
    // constants
    private static final double GRAVITY = 5.8;
    private static final Color defaultColor = new Color(255, 216, 0);
    
    // fields
    private double mass;
    //make above public for all out
    private int size;
    
    /**
     * Construct a Body with default size, mass, movement and color.
     */
    public Body()
    {
        this (20, 300, new Vector(0, 1.0), defaultColor);
    }
    
    /**
     * Construct a Body with a specified size, mass, movement and color.
     */
    public Body(int size, double mass, Vector movement, Color color)
    {
        this.size = size;
        this.mass = mass;
        addForce(movement);
        GreenfootImage image = new GreenfootImage (size, size);
        image.setColor (color);
        image.fillOval (0, 0, size-1, size-1);
        setImage (image);
    }
    
    /**
     * Act. That is: apply  the gravitation forces from
     * all other bodies around, and then move.
     */
    public void act() 
    {
        move();
        applyForces();
        bounceAtEdge();
    }
    /**
     * Return the mass of this body.
     */
    public double getMass()
    {
        return mass;
    }
    /**
     * 
     */
    private void applyForces()
    {
       List<Body> bodies = getWorld().getObjects(Body.class);
       
       for (Body body : bodies)
       {
           if (body!= this)
           {
               applyGravity (body);
            }
        }
    }
    /**
     * apply the gravity force of a given body to this one
     */
    private void applyGravity(Body other)
    {
        double dx = other.getExactX() - this.getExactX();
        double dy = other.getExactY() - this.getExactY();
        Vector force = new Vector (dx,dy);
        double distance = Math.sqrt (dx * dx + dy * dy);
        double strength = GRAVITY * this.mass * other.mass / (distance * distance);
        double acceleration = strength / this.mass;
        force.setLength (acceleration);
        addForce (force);
    }
    /**
     * Check whether we have hit the edge of the universe, If so, bounce of it (our border)
     */
    private void bounceAtEdge()
    {
       if (getX() == 0 || getX () == getWorld().getWidth()-1)
       {
         setLocation((double)getX(), (double)getY());
         getMovement().revertHorizontal();
         accelerate(0.9);
         changeColor();
       }
       else if (getY() == 0 || getY () == getWorld().getHeight()-1)
       {
           setLocation((double)getX(), (double)getY());
           getMovement().revertVertical();
           accelerate(0.9);
           changeColor();
       }
    }
    /**
     * changes color of bodies in world //when it hits wall
     */
    private void changeColor()
    {
       
        int x = Greenfoot.getRandomNumber(255);
        int y = Greenfoot.getRandomNumber(255);
        int z = Greenfoot.getRandomNumber(255);
        GreenfootImage image = new GreenfootImage (size-1, size-1);
        image.setColor (new Color(x,y,z));
        image.fillOval (0, 0, size-1, size-1);
        setImage (image);
    }
}
danpost danpost

2022/1/12

#
To allow more possible keys to be detected in your checkKeys method, you will need to change lines 121 and 122 of the Space class codes to the following:
if (index >= 0) randomBodies(index);
or
if (index >= 0)
{
    randomBidies(index);
}
That will allow further code below it to execute. That "further" code should use:
if ("z".equals(key))
and
if ("x".equals(key))
-- that is, you should not be using "Greenfoot.isKeyDown" there.
SportingLife7 SportingLife7

2022/1/13

#
Thank you @danpost, I ended up creating a new method in my space class called SuperControl() where I put in the key strokes to control the superbody class, would this work too? SuperControl() method in space class:
/**
     * 
     */
    public void SuperControl()
    {
        if (Greenfoot.isKeyDown("z"))
        {

            // int s = 20 + Greenfoot.getRandomNumber(30);
            // double m = Greenfoot.getRandomNumber(75)+10;
            // double speed = Greenfoot.getRandomNumber(40) / 25;
            // int d = Greenfoot.getRandomNumber(360);
             //int x = Greenfoot.getRandomNumber(getWidth()/2);
             //int y = Greenfoot.getRandomNumber(getHeight()/2);
            //addObject(new SuperBody);
        }
        if (Greenfoot.isKeyDown("x"))
        {
            removeObjects (getObjects(SuperBody.class));
        }
    }
danpost danpost

2022/1/13

#
SportingLife7 wrote...
would this work too? << Code Omitted >>
No -- that will not work. Mainly because using 'isKeyDown' will end up to be a true condition for multiple act steps in a row, causing multiple SuperBody objects to be created when "z" is pressed. And, on the other hand, you cannot use 'getKey' more than once per act step. Best is to keep ALL detection of game control keystrokes in one method.
SportingLife7 SportingLife7

2022/1/13

#
oh okay, that makes sense. Thank you. :) is there anyway that you could help me out with applying gravity to the Superbody to allow it to interact by gravity with the other bodies generated?
danpost danpost

2022/1/13

#
SportingLife7 wrote...
is there anyway that you could help me out with applying gravity to the Superbody to allow it to interact by gravity with the other bodies generated?
I think that all you need to do is have the SuperBody class extend the Body class. It will inherit all the fields and methods (including act) to have it interact with other bodies. Only thing needed in the class is a constructor that calls the Body constructor with all relevant data (size, mass, movement and color).
SportingLife7 SportingLife7

2022/1/14

#
thank you @danpost, that makes sense. Thank you for your help :)
You need to login to post a reply.