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

2024/5/17

Object Does Not Appear Automatically

hiiiimlynn hiiiimlynn

2024/5/17

#
Hello all. I have been following a tutorial to make a simple shooting game. All works well except the projectiles! I have doubled checked that I've copied the code correctly and I wasn't able to spot any mistakes. If I right click on class `Defense` > `newDefnse()` and drag&drop the object on scene it works as it should and I get no errors. But it just won't appear on it own. Does anyone know why? Note: I haven't added anything related to the `Defense` class in `MyWorld` (which I've named `Valley` so I won't include that code). Actor `Defense`:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class Defense extends Actor
{
    public void act()
    {
        moveDefense();
        removeFromWorld(); // needs to be added LAST
    }
    
    public void moveDefense()
    {
        setLocation(getX(), getY() - 5);
        // the int controls speed
    }
    
    public void removeFromWorld()
    {        
        if (getY() == 0)
        // if obj touches top of the world
        {
            getWorld().removeObject(this);
        }
    }
}
Actor `Bee`:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class Bee extends Actor
{
    boolean canDefend = true;
    
    public Bee()
    {
        setRotation(270); // default is 0 -> right 
    }
    
    public void act()
    {
        fly();
    }
    
    public void fly()
    {
        if (Greenfoot.isKeyDown("right"))
        {
            setLocation(getX()+5, getY());
            // we want to move right-left 
            //so we're changing *only the x axis*
            // we add 5 because x is 0 on the left side (and at the top)
        }
        
        if (Greenfoot.isKeyDown("left"))
        {
            setLocation(getX()-5, getY());
            // we subtract 5 because we're getting closer 
            // to 0 on the left side
        }
    }
    
    public void myDefense()
    {
        if (Greenfoot.isKeyDown("space") && canDefend == true)
        {
            getWorld().addObject(new Defense(), getX(), getY());
            // we want the projectile to have the x value of the player
            // and we want it to begin from the tip of the bee
            // so the y must be slight diffrent (closer to the top aka 0)
            canDefend = false;
        }
        else if (!Greenfoot.isKeyDown("space"))
        {
            canDefend = true;
        }
    }
}
Super_Hippo Super_Hippo

2024/5/17

#
The ‘myDefense’ method is never executed.
hiiiimlynn hiiiimlynn

2024/5/18

#
Super_Hippo wrote...
The ‘myDefense’ method is never executed.
oh my gosh you are right! i feel so silly. thank you so much for your time.
You need to login to post a reply.