Search code examples
javaimplementation2d-games

Best way to implement units in a small-scale RTS?


I am currently working on developing a small-scale 2D RTS in Java that will be unreliant on any non-standard libraries.

A crucial problem I can't answer properly is how to implement the units so each one of them functions independently, as is normal in an RTS.

I've thought of two ways:

1) Implement them as threads. Since threads, much like units, have a lifespan and operate independently, they should be a good fit.

Problem: How do I maintain other important aspects of a unit's AI, such as targeting and attacking enemies or rotating turrets for the idle animation while still moving?

I am considering giving each unit subthreads to handle this (again, since they should be independent yet concurrent), but I am worried that this is an inefficient approach. I am not constrained by computational limits in the program, but I want to know the best way of handling things for future development.

2) "Turns". Each units has a set of actions it should consider performing during every turn, and the turns are triggered by very fast TimerTasks that iterate through all existing units.

Problem: Might result in clunky code?

I am leaning towards the first approach, but before I dive into it, I'd like to know if I'm heading the right way, or if I'm more likely to shoot myself in the foot.

To sum up my issue: Should I use threads, timers or some other method to implement the units in a small RTS coded in Java? Any input would be appreciated.


Solution

  • Using separate thread for each entity is really, really bad idea - I think that the best approach should be adding entity (units, buildings etc.) list in game core. Each entity should be made from "blocks" - modules telling what can this entity do (entity properties). For example:

    1. Building+Harvester = mine
    2. Building+BuildingSite = building site
    3. Building+Constructor = Barracks
    4. Unit+Gatherer = resource gatherer
    5. Unit+Constructor+Gathener = Worker who can also build buildings

    Logic cycle should look like this:

    1. game loop is calling "update" method of logic core
    2. logic core is calling "update" method of each entity on list
    3. entity is calling "update" method of each property on list
    4. property is doing rest of the work

    Entities shouldn't be hardcoded, I would advise loading them from external files.