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

2022/9/14

How can I make my code only spawn one new object upon key press?

Calculator Calculator

2022/9/14

#
I want to spawn a GreenNote when "o" is pressed, it does that, but it spawns so many that the game freezes. How can I only spawn a single note each time "o" is pressed?
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * @author Calculator
 * @version 2
 */
public class GreenNote extends Actor
{
    public GreenNote() { 
        GreenfootImage image = getImage();
        image.scale(60,60);
        setImage(image);
    }
    /**
     * noteSpeed will make the notes move down quicker.
     * noteSpawn2 SHOULD spawn a note upon key press of "o"
     */
    public void act()
    {
          noteSpeed(5);
          noteSpawn2();
    }

    public void noteSpeed(int howFast)
    {
        setLocation(getX(), getY()+howFast);
    }
    public void noteSpawn2()
    {
        GreenNote greennote = new GreenNote();
        if(Greenfoot.isKeyDown("o")) {
            Greenfoot.delay(1);
            getWorld().addObject(greennote, 200, 0);
        }
    }
}


Spock47 Spock47

2022/9/16

#
Please see danpost's comment at https://www.greenfoot.org/topics/57369/0
Super_Hippo Super_Hippo

4 days ago

#
Another issue is that you most likely shouldn’t create a GreenNote object from inside the GreenNote class. The world should spawn the objects. Otherwise, each GreenNote object creates another object which can escalate quickly.
You need to login to post a reply.