Search code examples
javadesign-patternslibgdx

Several enemy movements in game development


I am writing a simple shoot'em up game in Java using LibGDX as the main library. I would like that any enemy in the game could perform any sort of movement, regardless their type. The problem arises when trying to isolate the logic of the movements an AI from each Enemy class.

A more graphic example:

  1. Mov A: Linear, from top to bottom.
  2. Mov B: Chase player character
  3. Mov C: Show up, shoot and flee.

Enemies:

  1. Spider. Perform Mov A
  2. Another spider. Perform Mov B
  3. To sum up: Being able to assign moves regardless the enemy.

What would be the best approach?


Solution

  • Use an entity system library like https://github.com/libgdx/ashley or https://github.com/junkdog/artemis-odb.

    You would then create systems:

    1. LinearTopBottomMovementSystem
    2. ChasePlayerMovementSystem
    3. ShowUpSystem
    4. ShootSystem (you probably also want anBulletMovementSystem)
    5. FleeSystem

    Then create components:

    1. LinearTopBottomMovementComponent
    2. ChasePlayerMovementComponent
    3. ShowUpComponent
    4. ShootComponent
    5. FleeComponent

    When creating enemies (entities) you create:

    1. Spider entity with LinearTopBottomMovementComponent
    2. Another spider entity with ChasePlayerMovementComponent
    3. Spider entity with ShowUpComponent
    4. After ShowUpComponent is handled (by the ShowUpSystem), remove this component and add ShootComponent
    5. After ShootComponent is handled (by the ShootSystem), remove this component and add FleeComponent

    This allows you to create enemies with all possible component combinations and you can add multiple components to one entity.

    If you decide to add circle movement and permanent fire enemy. Just create CircleMovementComponent and PermanentFireComponent and corresponding systems.