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

2021/11/18

lists and objects?

Aaron-aid Aaron-aid

2021/11/18

#
i stored a object into a list but how do I add that object from the list to the world?
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;
import java.util.ArrayList;
/**
 * Write a description of class body here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class player extends Actor
{
    //player info
    int p_rotation = 0;
    int p_turnspeed = 3;
    int p_speed = 3;
    int p_weapon = 0;
    
    static List <Object> item = new ArrayList<Object>();
    static int p_skin = 1;
    /**
     * Act - do whatever the player 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.
        getWorld().showText(""+item.size(), 100, 100);
        playermovement();
        
    } 
    void playermovement()
    {
        if (Greenfoot.isKeyDown("D"))
        {
            p_rotation = p_rotation+p_turnspeed;
            setRotation(p_rotation);
        }
        if (Greenfoot.isKeyDown("A"))
        {
            p_rotation = p_rotation-p_turnspeed;
            setRotation(p_rotation);
        }
        if (Greenfoot.isKeyDown("W"))
        {
            move(p_speed);
        }
        if (Greenfoot.isKeyDown("S"))
        {
            move(-p_speed+2);
        }
    }
}
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class item here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class item extends Actor
{
    /**
     * Act - do whatever the item wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        if(isTouching(player.class))
        {
            getWorld().getObjects(player.class).get(0).item.add(this);
            getWorld().removeObject(this);
        }
    }    
}
danpost danpost

2021/11/18

#
Call the list items (with the "s" at the end). Declare it as
List<Actor>items = new ArrayList<Actor>();
Remove the collision code from the item class and put it in the player class:
Actor touched= getOneIntersectingObject(item.class);
if (touched != null)
{
    items.add(touched);
    getWorld().removeObject(touched);
}
Then, you can just use,
getWorld().addObject(items.get(n), x, y);
where the list is not empty and n is between 0, inclusive and the size of the list, exclusive; plus x and y are declared and given coordinate values where to place the actor.
You need to login to post a reply.