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

2015/11/16

Removing an object of a class closest to a specific class

cactusButt cactusButt

2015/11/16

#
Basically I'm trying to make something like guitar hero, and what I want to happen is when let's say the left key is pressed, the closest and only the closest left arrow dropping (I've noticed that there will be instances wherein more than one left arrow will be dropping) will have its y-coordinate checked for accuracy for scoring, and removed. The thing is, for the love of God, I can't figure out how to achieve this without unnecessarily overcomplicating anything. I have a gist of how to check for accuracy, but I don't know how to check for just the closest object. Perhaps getObjectsInRange but I don't really know how to use it. An explanation would be helpful, yes, thanks. The only code I have so far is just for the falling of the arrows in designated x-coordinates, so I won't add any code on here. And please dumb down the explanation, I just started Greenfoot, I'm a high school student, and this is just for a project, ahaha thanks! :)
danpost danpost

2015/11/16

#
EDIT: Wait, I just noticed you said closest to a specific class. Give me a minute to compose. You would have to use 'getObjectsInRange' multiple times, decreasing the range until only one (or none) are within the range; then, increment the range and remove any one that is returned. This way of doing it, however, is quite CPU extensive. Better would probably be to just list all objects of that type in the world; then compute the distance of each from the specific class and remove the closest.
cactusButt cactusButt

2015/11/16

#
May I see a sample of how getObjectsInRange is used? Also, how could I go about listing all of the objects to get their distance? I never actually named the spawning objects individually when I added them into the world(since they were added randomly), would I have to do that? Or is it possible to call for just the objects presently in the world without having named them initially?
Super_Hippo Super_Hippo

2015/11/16

#
Let's say you have an Arrow class with the variable 'type'. 0=up, 1=right, 2=down, 3=left.
int closestDistance = 10000;
Arrow closestObject = null;
//for every Arrow object in 200 range
for (Object obj : getObjectsInRange(200, Arrow.class))
//OR just every object
for (Object obj : getWorld().getObjects(Arrow.class))
{
    Arrow a = (Arrow) obj;
    
    //if 'type' isn't public, you need a getter-method
    if (a.type != 3) continue; //only left arrows
    //pythagoras
    int thisDistance = Math.sqrt( Math.pow(getX()-a.getX(),2) + Math.pow(getY()-a.getY(),2) );
    if (thisDistance < closestDistance)
    {
        closestDistance = thisDistance;
        closestObject = a;
    }
}
if (closestObject != null) getWorld().removeObject(closestObject);
danpost danpost

2015/11/16

#
cactusButt wrote...
I never actually named the spawning objects individually when I added them into the world(since they were added randomly), would I have to do that? Or is it possible to call for just the objects presently in the world without having named them initially?
The World class keeps track of them; so, you do not need to name them individually. There is a World class method, 'getObjects' that returns the list object containing all of the objects of a specific class in the world. You can iterate through them and retain the closest object and distance that you come across.
cactusButt cactusButt

2015/11/17

#
Thank you both! I got it to remove the dropping arrow upon pressing the left arrow key, however, it seems to be removing every instance of that class instead of just the closest object.. The pythagoras code returned an error, something about lossy to double int, and well since I am only working on the Y-axis, I decided to just simplify it, perhaps that is where my error took place? This is the code for the left arrow dropper (I made a different class per dropper since I don't feel too confident with my knowledge of greenfoot yet to condense stuff).
import greenfoot.*;

/**
 * Write a description of class CDLeft here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class CDLeft extends CDDroppers
{
    private boolean justPressed = false;
    private boolean execute = false;
    private int fade = 7;
    public CDLeft()
    {
        GreenfootImage variableName = getImage();
        variableName.scale(100, 81);
        setImage(variableName);

    }

    /**
     * Act - do whatever the CDLeft 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.
        //3000, 2400, 1200, 0
        if (execute == false)
        {
            if (GATCCheerDance.cdTimer > 3000)
            {
                if (CDLeft.class != null)
                {
                    setLocation(getX(), getY()+2);
                }
            }
            if (GATCCheerDance.cdTimer >= 2400 && GATCCheerDance.cdTimer < 3000)
            {
                if (CDLeft.class != null)
                {
                    setLocation(getX(), getY()+3);
                }
            }
            if (GATCCheerDance.cdTimer >= 1200 && GATCCheerDance.cdTimer < 2400)
            {
                if (CDLeft.class != null)
                {
                    setLocation(getX(), getY()+4);
                }
            }
            if (GATCCheerDance.cdTimer < 1200)
            {
                if (CDLeft.class != null)
                {
                    setLocation(getX(), getY()+5);
                }
            }
        }
        if (isAtEdge())
        {
            getWorld().removeObject(this);
        }

        //when space is pressed
        if (CDLeft.class != null)
        {
            if (Greenfoot.isKeyDown("Left") && justPressed == false && execute == false) 
            {
                checkSinglePress();
                justPressed = true;
                execute = true;
                // above prevents holding down of keys

                //below codes for the checking of distance manually
                //perfect y is 530

            }
            if (execute == true)
            {
                checkDistance();
            }
        }
    }    

    public void checkSinglePress()
    {
        if (!Greenfoot.isKeyDown("Left") && justPressed == true)
        {
            justPressed = false;
        }
    }

    public void checkDistance()
    {
        if (CDLeft.class != null)
        {
            int closestDistance = 10000;
            CDLeft closestObject = null;

            for (Object obj : getWorld().getObjects(CDLeft.class))
            {
                CDLeft a = (CDLeft) obj;
                int thisDistance = getY() - a.getY();
                if (thisDistance < closestDistance)
                {
                    closestDistance = thisDistance;
                    closestObject = a;
                }

            }
            if (closestObject != null)
            {
                setImage("cd1_clicked.png");
                GreenfootImage clicked = getImage();
                clicked.scale(100, 81);
                setImage(clicked);
                fade--;
                if (fade <= 0)
                {
                    getWorld().removeObject(closestObject);
                    execute = false;
                    fade = 7;
                }
            }
        }
    }
}    
I don't know if it'll help but here's the code for the world class as well
import greenfoot.*;

/**
 * Write a description of class GATCCheerDance here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class GATCCheerDance extends MiniGames
{
    public static int cheerMove;
    public static int cdTimer;
    public static int dropperCount;
    public static int currentCount;
    private int position;
    private int lastDrop;
    public static int cdrealtime = cdTimer/60;

    /**
     * Constructor for objects of class GATCCheerDance.
     * 
     */
    public GATCCheerDance()
    {

        prepare();
    }

    /**
     * Prepare the world for the start of the program. That is: create the initial
     * objects and add them to the world.
     */
    private void prepare()
    {
        Base1 base1 = new Base1();
        addObject(base1, 100, 530);

        Base2 base2 = new Base2();
        addObject(base2, 300, 530);

        Base3 base3 = new Base3();
        addObject(base3, 500, 530);

        Base4 base4 = new Base4();
        addObject(base4, 700, 530);

        if (EventMaster.cdLevel == 1)
        {
            cdTimer = (1*3600);
            dropperCount = 2*60;
        }
        if (EventMaster.cdLevel == 2)
        {
            cdTimer = (2*3600);
            dropperCount = (3*60);
        }
        if (EventMaster.cdLevel == 3)
        {
            cdTimer = (3*3600);
            dropperCount = (4*60);
        }
        if (EventMaster.cdLevel == 4)
        {
            cdTimer = (4*3600);
            dropperCount = (4*60);
        }
    }

    public void act()
    {
        // 1 = left
        // 2 = up
        // 3 = down
        // 4 = right

        // 5 = left + right
        // 6 = left + down
        // 7 = right + down
        // 8 = up + down

        cdTimer--;
        cdrealtime = cdTimer/60;
        if (cdTimer != 0 && currentCount != dropperCount)
        {
            if (EventMaster.cdLevel == 1)
            {
                if (cdTimer > 3000 && cdTimer % 60 == 0)
                {
                    position = Greenfoot.getRandomNumber(4);
                    if (position == 0 && lastDrop != 0)
                    {
                        addObject(new CDLeft(), 100, 10);
                        currentCount += 1;
                        lastDrop = 0;
                    }
                    if (position == 1 && lastDrop != 1)
                    {
                        addObject(new CDUp(), 300, 10);
                        currentCount += 1;
                        lastDrop = 1;
                    }
                    if (position == 2 && lastDrop != 2)
                    {
                        addObject(new CDDown(), 500, 10);
                        currentCount += 1;
                        lastDrop = 2;
                    }
                    if (position == 3 && lastDrop != 3)
                    {
                        addObject(new CDRight(), 700, 10);
                        currentCount += 1;
                        lastDrop = 3;
                    }
                }

                if (cdTimer < 3000 && cdTimer > 2400 && cdTimer % 60 == 0)
                {
                    position = Greenfoot.getRandomNumber(8);
                    if (position == 0 && lastDrop != 0)
                    {
                        addObject(new CDLeft(), 100, 10);
                        currentCount += 1;
                        lastDrop = 0;
                    }
                    if (position == 1 && lastDrop != 1)
                    {
                        addObject(new CDUp(), 300, 10);
                        currentCount += 1;
                        lastDrop = 1;
                    }
                    if (position == 2 && lastDrop != 2)
                    {
                        addObject(new CDDown(), 500, 10);
                        currentCount += 1;
                        lastDrop = 2;
                    }
                    if (position == 3 && lastDrop != 3)
                    {
                        addObject(new CDRight(), 700, 10);
                        currentCount += 1;
                        lastDrop = 3;
                    }

                    if (position == 4 && lastDrop != 4)
                    {
                        addObject(new CDLeft(), 100, 10);
                        addObject(new CDRight(), 700, 10);
                        currentCount += 2;
                        lastDrop = 4;
                    }
                    if (position == 5 && lastDrop != 5)
                    {
                        addObject(new CDLeft(), 100, 10);
                        addObject(new CDDown(), 500, 10);
                        currentCount += 2;
                        lastDrop = 5;
                    }
                    if (position == 6 && lastDrop != 6)
                    {
                        addObject(new CDRight(), 700, 10);
                        addObject(new CDDown(), 500, 10);
                        currentCount += 2;
                        lastDrop = 6;
                    }
                    if (position == 7 && lastDrop != 7)
                    {
                        addObject(new CDUp(), 300, 10);
                        addObject(new CDDown(), 500, 10);
                        currentCount += 2;
                        lastDrop = 7;
                    }

                }

                if (cdTimer < 2400 && cdTimer > 1200 && cdTimer % 45 == 0)
                {
                    position = Greenfoot.getRandomNumber(8);
                    if (position == 0 && lastDrop != 0)
                    {
                        addObject(new CDLeft(), 100, 10);
                        currentCount += 1;
                        lastDrop = 0;
                    }
                    if (position == 1 && lastDrop != 1)
                    {
                        addObject(new CDUp(), 300, 10);
                        currentCount += 1;
                        lastDrop = 1;
                    }
                    if (position == 2 && lastDrop != 2)
                    {
                        addObject(new CDDown(), 500, 10);
                        currentCount += 1;
                        lastDrop = 2;
                    }
                    if (position == 3 && lastDrop != 3)
                    {
                        addObject(new CDRight(), 700, 10);
                        currentCount += 1;
                        lastDrop = 3;
                    }

                    if (position == 4 && lastDrop != 4)
                    {
                        addObject(new CDLeft(), 100, 10);
                        addObject(new CDRight(), 700, 10);
                        currentCount += 2;
                        lastDrop = 4;
                    }
                    if (position == 5 && lastDrop != 5)
                    {
                        addObject(new CDLeft(), 100, 10);
                        addObject(new CDDown(), 500, 10);
                        currentCount += 2;
                        lastDrop = 5;
                    }
                    if (position == 6 && lastDrop != 6)
                    {
                        addObject(new CDRight(), 700, 10);
                        addObject(new CDDown(), 500, 10);
                        currentCount += 2;
                        lastDrop = 6;
                    }
                    if (position == 7 && lastDrop != 7)
                    {
                        addObject(new CDUp(), 300, 10);
                        addObject(new CDDown(), 500, 10);
                        currentCount += 2;
                        lastDrop = 7;
                    }
                }

                if (cdTimer < 1200 && cdTimer > 0 && cdTimer % 45 == 0)
                {
                    position = Greenfoot.getRandomNumber(8);
                    if (position == 0 && lastDrop != 0)
                    {
                        addObject(new CDLeft(), 100, 10);
                        currentCount += 1;
                        lastDrop = 0;
                    }
                    if (position == 1 && lastDrop != 1)
                    {
                        addObject(new CDUp(), 300, 10);
                        currentCount += 1;
                        lastDrop = 1;
                    }
                    if (position == 2 && lastDrop != 2)
                    {
                        addObject(new CDDown(), 500, 10);
                        currentCount += 1;
                        lastDrop = 2;
                    }
                    if (position == 3 && lastDrop != 3)
                    {
                        addObject(new CDRight(), 700, 10);
                        currentCount += 1;
                        lastDrop = 3;
                    }

                    if (position == 4 && lastDrop != 4)
                    {
                        addObject(new CDLeft(), 100, 10);
                        addObject(new CDRight(), 700, 10);
                        currentCount += 2;
                        lastDrop = 4;
                    }
                    if (position == 5 && lastDrop != 5)
                    {
                        addObject(new CDLeft(), 100, 10);
                        addObject(new CDDown(), 500, 10);
                        currentCount += 2;
                        lastDrop = 5;
                    }
                    if (position == 6 && lastDrop != 6)
                    {
                        addObject(new CDRight(), 700, 10);
                        addObject(new CDDown(), 500, 10);
                        currentCount += 2;
                        lastDrop = 6;
                    }
                    if (position == 7 && lastDrop != 7)
                    {
                        addObject(new CDUp(), 300, 10);
                        addObject(new CDDown(), 500, 10);
                        currentCount += 2;
                        lastDrop = 7;
                    }
                }

            }

            if (EventMaster.cdLevel == 2)
            {

            }

            if (EventMaster.cdLevel == 3)
            {

            }

            if (EventMaster.cdLevel == 4)
            {

            }
        }

    }
}

Thanks in advanced!
Super_Hippo Super_Hippo

2015/11/17

#
Yes, you are right, 'thisDistance' and 'closestDistance' should be 'double' and not 'int'. What is this?
if (CDLeft.class != null)
How can a class be 'null'?
cactusButt cactusButt

2015/11/18

#
I have no idea what I am doing tbh, what should be in place of that string?
danpost danpost

2015/11/18

#
cactusButt wrote...
I have no idea what I am doing tbh, what should be in place of that string?
Actually, it should just be removed (the 'if' statement itself -- not the block of code that is executed if the returned value is true). The block of code for that 'if' statement will always execute as the condition will always return a true value. A class is never null as the two possibilities are whether there is a class with that name or not and, if no class with that name exists, the compiler will complain about referring to it at all during compilation.
Royalblue64 Royalblue64

2015/11/19

#
I think people have been making this a lot more complicated than it needs to be, which is good for you, cactusbutt =) From what I can tell, the "Bases" (Base1, Base2, Base3, Base4) are the boxes that sit at the bottom of the screen and are the things you're trying to get the arrow as close to as possible. Assuming this is the case, there should only be a single Base class which contains the following:
import greenfoot.*;

public class Base
{
	private boolean holding;
	private int distance;
	private int score;
	
	public Base()
	{
		holding = false;
		distance = 0;
		score = 0;
	}
	
	public void act()
	{
		checkForInput();
	}
	
	private void checkForInput()
	{
		if (Greenfoot.isKeyDown("Left"))
		{
			if (!holding)
			{
				checkForArrow();
				holding = true;
			}
		}
		else
		{
			holding = false;
		}
	}
	
	private void checkForArrow()
	{
		CDDroppers touching = getOneIntersectingObject(CDDroppers.class);
		
		if (touching != null && !touching.getFading())
		{
			distance = Math.abs(getY() - touching.getY());
			updateScore();
			
			touching.setFading(true);
		}
	}
	
	//This method is intended to initiate whatever action
	//you want to result from an arrow being scored.
	private void updateScore()
	{
		score += distance;
		distance = 0;
	}
}
Then the following code should be the contents of the CDDroppers class (NOT the CDLeft class--this code condenses the arrows into one):
import greenfoot.*;

public class CDDroppers
{
	private GreenfootImage myImage;
	
	private boolean fading;
	private int fallSpeed;
	private int fade;
	
	public CDDroppers(GreenfootImage image)
	{
		myImage = image;
		setImage(myImage);
		
		fading = false;
		fallSpeed = 2;
		fade = 7;
	}
	
	public void act()
	{
		fall();
		checkFade();
	}
	
	//This is simply a matter of convenience and ease
	private int getTimer()
	{
		return GATCCheerDance.cdTimer;
	}
	
	private void updateFallSpeed()
	{
		if (getTimer() <= 1200)
		{
			fallSpeed = 5;
		}
		else if (getTimer() <= 2400)
		{
			fallSpeed = 4;
		}
		else if (getTimer() <= 3000)
		{
			fallSpeed = 3;
		}
		else
		{
			fallSpeed = 2;
		}
	}
	
	private void fall()
	{
		updateFallSpeed();
		
		setLocation(getX(), getY() + fallSpeed);
	}
	
	private void checkFade()
	{
		if (fade == 0)
		{
			getWorld().removeObject(this);
		}
		
		if (fading)
		{
			myImage.setTransparency(32 * fade);
			setImage(myImage);
			
			fade--;
		}
	}
	
	public boolean getFading()
	{
		return fading;
	}
	
	public void setFading(boolean newFading)
	{
		fading = newFading;
	}
}
I hope this helps, obviously feel free to respond with any questions!
You need to login to post a reply.