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

2021/4/29

How to attach an actor to another actor?

1
2
ambrokato ambrokato

2021/4/29

#
Hello everyone, I am making a top-down shooter game. I can't figure out how to attach an actor( Gun) to my main character(Sprite) and have the gun follow the location of the main character.
danpost danpost

2021/4/29

#
ambrokato wrote...
I can't figure out how to attach an actor( Gun) to my main character(Sprite) and have the gun follow the location of the main character.
Essential stuff here:
import greenfoot.*;

public class Player extends Actor
{
    private Actor gun;
    
    public void act()
    {
        if (gun == null && isTouching(Gun.class) && Greenfoot.isKeyDown("g"))
        {
            gun = getOneIntersectingObject(Gun.class);
        }
        ...
        /** at end of method */
        if (gun != null && gun.getWorld() != null)
        {
            gun.setLocation(getX(), getY());
        }
    }
    ...
}
ambrokato ambrokato

2021/4/29

#
danpost wrote...
ambrokato wrote...
I can't figure out how to attach an actor( Gun) to my main character(Sprite) and have the gun follow the location of the main character.
Essential stuff here:
import greenfoot.*;

public class Player extends Actor
{
    private Actor gun;
    
    public void act()
    {
        if (gun == null && isTouching(Gun.class) && Greenfoot.isKeyDown("g"))
        {
            gun = getOneIntersectingObject(Gun.class);
        }
        ...
        /** at end of method */
        if (gun != null && gun.getWorld() != null)
        {
            gun.setLocation(getX(), getY());
        }
    }
    ...
}
Hey @danpost! I always see your comments in every discussion. I really appreciate you helping newbies like me. One more thing Dan, I want to add a total of 5 different weapons, each has its own classes. I want the player to able to switch between these weapons. Could you please help me code this feature. Thanks again Dan
danpost danpost

2021/4/29

#
ambrokato wrote...
I want to add a total of 5 different weapons, each has its own classes. I want the player to able to switch between these weapons.
You would then (instead of above) need the following bits:
// imports
import java.util.ArrayList;

// fields
private ArrayList<Actor> weapons = new ArrayList<Actor>();
private Actor drawnWeapon;
Add weapon to list when encountered. I will not guess how you want to choose which weapon to draw.
ambrokato ambrokato

2021/4/29

#
danpost wrote...
ambrokato wrote...
I want to add a total of 5 different weapons, each has its own classes. I want the player to able to switch between these weapons.
You would then (instead of above) need the following bits:
// imports
import java.util.ArrayList;

// fields
private ArrayList<Actor> weapons = new ArrayList<Actor>();
private Actor drawnWeapon;
Add weapon to list when encountered. I will not guess how you want to choose which weapon to draw.
Hey Dan how can I exactly code this? I'm not really sure how the ArrayList work. But I have 5 weapons Actor. For example, if I press "1" it will switch to pistol, "2" for a shotgun and so on.
danpost danpost

2021/4/29

#
ambrokato wrote...
Dan how can I exactly code this? I'm not really sure how the ArrayList work. But I have 5 weapons Actor. For example, if I press "1" it will switch to pistol, "2" for a shotgun and so on.
Can the player access any of the weapons at any time or do the weapons have to be picked up first?
ambrokato ambrokato

2021/4/29

#
danpost wrote...
ambrokato wrote...
Dan how can I exactly code this? I'm not really sure how the ArrayList work. But I have 5 weapons Actor. For example, if I press "1" it will switch to pistol, "2" for a shotgun and so on.
Can the player access any of the weapons at any time or do the weapons have to be picked up first?
I am thinking of two ways of obtaining weapons. One is an enemy will randomly spawn these weapons or I want to create a scenario like a shop where the player can buy the weapons.
danpost danpost

2021/4/29

#
ambrokato wrote...
an enemy will randomly spawn these weapons
A single field and one method will work for that:
private Actor weapon;

private void drawWeapon(int weaponNum)
{
    switch (weaponNum)
    {
        case 1 : weapon = new Gun(); break;
        case 2 : weapon = ???
        ...
    }
    getWorld().addObject(weapon, getX(), getY());
}

// in addedToWorld(World world) method (not in constructor)
drawWeapon(Greenfoot.getRandomNumber(5)+1);
or I want to create a scenario like a shop where the player can buy the weapons.
You may want to take a look at my Shop Support Class scenario.
danpost danpost

2021/4/29

#
It might be best to group your weapon classes by having them all extend an abstract Weapon class which can contain the shared codes of the weapons and default methods required for all weapons. Then line 1 can be:
private Weapon weapon;
and any actions can be done through the Weapon class.
ambrokato ambrokato

2021/4/29

#
WOW! that's perfect! thank you so much Dan! I will post and tag you once I'm done with the game! Thanks a lot!
ambrokato ambrokato

2021/5/8

#
danpost wrote...
It might be best to group your weapon classes by having them all extend an abstract Weapon class which can contain the shared codes of the weapons and default methods required for all weapons. Then line 1 can be:
private Weapon weapon;
and any actions can be done through the Weapon class.
Need your help one last time Dan, I thought I got it but nope. I created this Actor class to manage all of the different gun actors that I have. I know you said it's best to group my classes by having them all extend an abstract Weapon class but i didn't do it because no.1 I already have all gun actors coded individually and the second reason, I don't really know how to do that. So i took your other advice,
import lang.stride.*;
import java.util.*;
import greenfoot.*;
import java.util.ArrayList;
/**
 * 
 */
public class WeaponE extends Actor
{
    Bullet1 bullet1;
    private int timer;
    int damage;
    GreenfootImage weaponEquip;
    GreenfootImage Pistol;
    World currentWorld;
    public ArrayList<Actor>weapons = new ArrayList<Actor>();   // How do I add weapon actor here? what is the syntax that i need to use?
    public WeaponE(World world)
    {
        currentWorld = world;
        damage = 1;
        Pistol = new GreenfootImage("pistol.png");
    }

    /**
     * Act - do whatever the pistol wants to do. This method is called whenever the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act()
    {
        MouseInfo mouse = Greenfoot.getMouseInfo();
        CurrentWeapon();
        if(mouse != null)
        {
            Vector2D weaponToMouse = new Vector2D(mouse.getX()-getX(), mouse.getY()-getY());

            alignWithVector(weaponToMouse);
            int buttonNumber = mouse.getButton();
            if (timer > 0 ) timer --;
            if (timer == 0 && buttonNumber == 1)
            {
                timer = 30;
                bullet1 = new Bullet1();

                getWorld().addObject(bullet1, getX(), getY());
                bullet1.setRotation(getRotation());

            }

        }
    }

    public void alignWithVector(Vector2D v)
    {
        double adjacent = v.getX();
        double opposite = v.getY();

        double angleRadians = Math.atan2(opposite, adjacent);
        double angleDegrees = Math.toDegrees(angleRadians);

        setRotation((int) angleDegrees);
    }
    public void CurrentWeapon()
    {
        setImage(Pistol);
    }
    
}
### This the my Shop Class
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Shop here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Shop extends World
{
    Counter counter;
    MyWorld myWorld;
    World previousWorld;
    Back back = new Back();
    Buy buy;
    Buy buy1;
    Buy buy2;
    Buy buy3;
    Buy buy4;
    /**
     * Constructor for objects of class Shop.
     * 
     */
    public Shop(World pWorld)
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(800, 600, 1); 
        addObject(back,130,550);
        previousWorld = pWorld;

        getBackground().drawImage(new GreenfootImage("$5000", 20, Color.BLACK, null), 680, 80);
        getBackground().drawImage(new GreenfootImage("$3500", 20, Color.BLACK, null), 680, 200);
        getBackground().drawImage(new GreenfootImage("$500", 20, Color.BLACK, null), 680, 320);
        getBackground().drawImage(new GreenfootImage("+10hp, $500", 20, Color.BLACK, null), 660, 490);

        getBackground().drawImage(new GreenfootImage("Welcome hero! \n Come and spend your cash!", 20, Color.BLUE, null), 40, 300);

        prepare();
        //next();
    }

    public void act()
    {
        back.nextLevel(previousWorld);
        purchase();
    }

    /**
     * Prepare the world for the start of the program.
     * That is: create the initial objects and add them to the world.
     */
    private void prepare()
    {
        /*Buy*/ buy = new Buy();
        addObject(buy,693,535);     //Health potion  $500
        /*Buy*/ buy2 = new Buy();
        addObject(buy2,702,377);    // Ak47 $500
        /*Buy*/ buy3 = new Buy();
        addObject(buy3,703,249);    // MiniMachinegun $3500
        /*Buy*/ buy4 = new Buy();
        addObject(buy4,702,127);    // rpg $5000
    }
    public void purchase() // this is the method that buy the guns in the shop, not sure what to code here.
    {
        if(Greenfoot.mouseClicked(buy))
        {
            
        }
        else if(Greenfoot.mouseClicked(buy2))
        {
            
        }
         else if(Greenfoot.mouseClicked(buy3))
        {
            
        }
         else if(Greenfoot.mouseClicked(buy4))
        {
            
        }
    }
    

}
danpost danpost

2021/5/8

#
Line 16 could be as you have it, where later you add items like this:
weapons.add(new Pistol());
ambrokato ambrokato

2021/5/8

#
danpost wrote...
Line 16 could be as you have it, where later you add items like this:
weapons.add(new Pistol());
For example. Like this
 public void purchase() // this is the method that buy the guns in the shop, not sure what to code here.
    {
        if(Greenfoot.mouseClicked(buy))
        {
            WeaponE.weapons.add(new Pistol());
        }
        else if(Greenfoot.mouseClicked(buy2))
        {
             WeaponE.weapons.add(new Ak47());
        }
         else if(Greenfoot.mouseClicked(buy3))
        {
             WeaponE.weapons.add(new shotGun());
        }
         else if(Greenfoot.mouseClicked(buy4))
        {
             ....
        }
    }
     
 
}
then how do access this in the array?
danpost danpost

2021/5/8

#
ambrokato wrote...
then how do access this in the array?
Add in class with array:
// field
private int index = -1;

// method
public Actor getNext()
{
    if (weapons.isEmpty()) return null;
    index = (index+1)%weapons.size();
    return weapons.get(index);
}
ambrokato ambrokato

2021/5/9

#
danpost wrote...
ambrokato wrote...
then how do access this in the array?
Add in class with array:
// field
private int index = -1;

// method
public Actor getNext()
{
    if (weapons.isEmpty()) return null;
    index = (index+1)%weapons.size();
    return weapons.get(index);
}
Hey Dan this is what I have now. In my shop class. I created my array here and this is where I added the gun actors in the array. Now my problem I am not sure how to make this work. I want my character to start with a Pistol by default and then the player can spend the money to buy new guns.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.ArrayList;
/**
 * Write a description of class Shop here. 
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Shop extends World
{
    Counter counter;
    World previousWorld;
    Back back = new Back();
    Buy buy;
    Buy buy1;
    Buy buy2;
    Buy buy3;
    Buy buy4;
    HealthBar increaseHealth;
    public ArrayList<Actor>weapons = new ArrayList<Actor>();
    Pistol pistolGun = new Pistol();
    Ak47 ak47Gun = new Ak47();
    Rpg rpgGun = new Rpg();
    machineGun mGun = new machineGun();
    private int index = -1;
    /**
     * Constructor for objects of class Shop.
     * 
     */

    public Shop(World pWorld, HealthBar hp, Counter counter)
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(800, 600, 1); 
        addObject(back,130,550);
        previousWorld = pWorld;
        this.increaseHealth = hp;
        this.counter = counter;
        getBackground().drawImage(new GreenfootImage("$5000", 20, Color.BLACK, null), 680, 80);
        getBackground().drawImage(new GreenfootImage("$3500", 20, Color.BLACK, null), 680, 200);
        getBackground().drawImage(new GreenfootImage("$500", 20, Color.BLACK, null), 680, 320);
        getBackground().drawImage(new GreenfootImage("+10hp, $500", 20, Color.BLACK, null), 660, 490);

        getBackground().drawImage(new GreenfootImage("Welcome hero! \n Come and spend your cash!", 20, Color.BLUE, null), 40, 300);

        prepare();
        //next();
    }

    public Actor getNext()
    {
        if (weapons.isEmpty()) return null;
        index = (index+1)%weapons.size();
        return weapons.get(index);
    }
    public void act()
    {
        back.nextLevel(previousWorld);
        purchase();
    }

    /**
     * Prepare the world for the start of the program.
     * That is: create the initial objects and add them to the world.
     */
    private void prepare()
    {
        /*Buy*/ buy = new Buy();
        addObject(buy,693,535);     //Health potion  $500
        /*Buy*/ buy2 = new Buy();
        addObject(buy2,702,377);    // Ak47 $500
        /*Buy*/ buy3 = new Buy();
        addObject(buy3,703,249);    // MiniMachinegun $3500
        /*Buy*/ buy4 = new Buy();
        addObject(buy4,702,127);    // rpg $5000
    }

    public void purchase()
    {
        Message msg1 = new Message();
        Message msg2 = new Message();
        Message msg3 = new Message();
        Message msg4 = new Message();
        if(Greenfoot.mouseClicked(buy))
        {
            if(counter.money >= 500 && Greenfoot.mouseClicked(buy))
            {   
                this.increaseHealth.health+=10;
                counter.money-=500;
                msg2.setImage(new GreenfootImage("-500 ", 25, Color.RED, null, null));
                addObject(msg2, 650, 450);
                Greenfoot.delay(50);
                removeObject(msg2);
            }
            else if(counter.money < 500 && Greenfoot.mouseClicked(buy))
            {

                removeObject(msg1);
                msg2.setImage(new GreenfootImage("Not enough Money", 25, Color.RED, null, null));
                addObject(msg2, 650, 450);
                Greenfoot.delay(50);
                removeObject(msg2);
            }
        }
        if(Greenfoot.mouseClicked(buy2))
        {
            if(counter.money >= 500)
            {
                weapons.add(ak47Gun);
                counter.money-=500;
                msg3.setImage(new GreenfootImage("-500", 25, Color.RED, null, null));
                addObject(msg3, 650, 300);
                Greenfoot.delay(50);
                removeObject(msg3);
            }    
            else
            {
                msg3.setImage(new GreenfootImage("Not enough Money", 25, Color.RED, null, null));
                addObject(msg3, 650, 300);
                Greenfoot.delay(50);
                removeObject(msg3);
            }
        }   
        else if(Greenfoot.mouseClicked(buy3))
        {
            if(counter.money >= 3500)
            {
                weapons.add(mGun);
                counter.money -= 3500;
                msg4.setImage(new GreenfootImage("-3500", 25, Color.RED, null, null));
                addObject(msg4, 650, 180);
                Greenfoot.delay(50);
                removeObject(msg3);
            }
            else
            {
                weapons.add(mGun);
                msg4.setImage(new GreenfootImage("Not enough Money", 25, Color.RED, null, null));
                addObject(msg4, 650, 180);
                Greenfoot.delay(50);
                removeObject(msg3);
            }
        }
        else if(Greenfoot.mouseClicked(buy4))
        {
            if (counter.money >= 5000)
            {
                weapons.add(rpgGun);
                counter.money -= 5000;
                msg1.setImage(new GreenfootImage("-5000", 25, Color.RED, null, null));
                addObject(msg1, 650, 50);
                Greenfoot.delay(50);
                removeObject(msg1);
            }
            else
            {
                msg1.setImage(new GreenfootImage("Not enough Money", 25, Color.RED, null, null));
                addObject(msg1, 650, 50);
                Greenfoot.delay(50);
                removeObject(msg1);
            }
        }
    }

}
##### This is my Player class, I still have the first code that you give me. How should I code this part?
import lang.stride.*;
import java.util.*;
import greenfoot.*;


public class Player extends Actor
{
    private GreenfootImage teleport;
    //private ArrayList<Actor> weapons = new ArrayList<Actor>();
    //private Actor drawnWeapon;
    private Actor weapon;
    public int time =0;
    
    public Player()
    {
        teleport = new GreenfootImage("dash.png");
    }
    public void act()
    {
        time++;
        movement();
        Weapon1();
        hitByEnemy();
    }

    public void Weapon1()
    {
        
        if ( weapon == null && isTouching(Pistol.class))
        {
            weapon = getOneIntersectingObject(Pistol.class);
        }
        if (weapon !=null && weapon.getWorld() != null)
        {
            weapon.setLocation(getX(), getY());
        }

    }
    public void SwitchWeapons()
    {
        if(Greenfoot.isKeyDown("1"))
        {

        }
        else if(Greenfoot.isKeyDown("2"))
        {
            
        }
        else if(Greenfoot.isKeyDown("3"))
        {
            
        }
          else if(Greenfoot.isKeyDown("3"))
        {
            
        }
    }
#### THis is MyWorld, I have a code here that adds a gun to the world, The problem is that now there are more guns. and not sure how to make it work using the array.
import lang.stride.*;
import java.util.*;
import greenfoot.*;

/**
 * 
 */
public class MyWorld extends World
{
    int count = 0;
    int spawnSpeed = 20; // lower value for faster spawnspeed 
    int randomSpawn = Greenfoot.getRandomNumber(8);
    HealthBar healthbar = new HealthBar();
    //HealthBar healthbar;
    GameOver gameOver;
    public Player hero = new Player();
    Counter counter = new Counter();
    private machineGun mGun;
    Ghost ghost;
    Golem golem;
    Shop weaponX;
    Boss boss = new Boss(hero, counter);
    GreenfootSound gameplay = new GreenfootSound("GamePlay.mp3");
    GreenfootSound bossBattle = new GreenfootSound("BossBattle.mp3");
    /**
     * Constructor for objects of class MyWorld.
     */
    public MyWorld()
    {
        super(800, 600, 1);
        addObject(hero, 400, 300);
       //currentWeapon();
        addObject(healthbar, hero.getX()-5, hero.getY()-50);
        addObject(counter, 70, 35);
        counter.score = 0;
        counter.money = 0;
       
        golem.golemKilled = 0;
        ghost.ghostKilled = 0;
        gameplay.play();
        currentWeapon();
       
       //machineGun mGun = new machineGun();
       Pistol pistolGun = new Pistol();
       addObject(pistolGun , hero.getX(), hero.getY());
There are more replies on the next page.
1
2