0
votes

For my 2D Top-down shooter i want to combine my character (subclass of Image/Actor) and the weapon (TextureRegion or Actor?) he is holding just for optical reason. My character inside holds a Hero object, which represents his logiacl part, like his weapons, his selected weapon and his speed. The weapons he holds are also only the logical part, so no graphics in there. How should i add this weapon to the player? Should i use a Group and the player and the weapon are part of that group? Or should the player draw the weapon in his draw method, depending on his own position? But then i would have to keep the weapon texture inside the player and load the one which is matching to the weapon the hero object is currently holding. What would be the best way?

1

1 Answers

4
votes

Should i use a Group and the player and the weapon are part of that group?

Yes, that's the correct approach.

A Group is part of a Stage and whenever the group is moved, all members (Actors) of that group move with it. It also acts like a new, local coordinate system. You could actually make your Player class a group instead of putting it in a group. The weapon itself will then be added to your player-group and its position should be fixed. Fixed means, that it will only be set once, to a small offset which will be added to the player-group position.

Splitting up the weapon and the player makes sense, because when shooting you might want the weapon to "shake" a little bit, but your player should not do that.

In pseudo code your given scenario might look like this:

class Hero extends Actor {
    // update logic in act()
    // render sprite in draw() depending on the this.getX()/getY()
}

class Weapon extends Actor {
    // update logic in act()
    // render sprite in draw() depending on the this.getX()/getY()
}

class Character extends Group {
    private Hero hero;
    private Weapon weapon;

    public Character(Hero hero, Weapon weapon) {
        this.hero = hero;
        this.weapon = weapon;
        addActor(hero);
        addActor(weapon);
        weapon.setPosition(10f, 0f); // small offset to the right
    }
}

Moving the whole character would now work by using character.setPosition(). But as I said: Since the hero would probably execute the logic, you should get rid of your Character and make Hero a Group and add the weapon to it. Otherwise your hero needs a reference to the character-group to be able to move. That would also make switching weapons much easier. The logic-hero could then do that himself and doesn't need to manage the character group.