Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import eca.component;
- import eca.entity;
- import std.stdio : writefln;
- import std.conv : to;
- import core.time;
- void main()
- {
- //Create an updater, which will update 30 times per second
- auto updater = Updater();
- //Create list of entities
- auto entities = [
- new Entity(
- new PositionComponent(0,10),
- new MovementComponent(),
- new PhysicsComponent()
- ),
- new Entity(
- new PositionComponent(10, 41),
- new GraphicsComponent(),
- ),
- ];
- //Loop for 5 seconds
- MonoTime time = MonoTime.currTime();
- while(MonoTime.currTime() < time + 5.seconds)
- {
- //Loop through all entities as fast as possible
- foreach(entity; entities)
- {
- //TODO: Is there a better way to handle rendering?
- //Check if a graphics component is present, then render
- if(entity.hasComponent!GraphicsComponent)
- {
- (entity.getComponent!GraphicsComponent).update(entity);
- }
- //Update according to how much time has passed
- foreach(update; 0 .. updater.getUpdates())
- {
- entity.update(); //This is where the magic happens
- }
- }
- }
- }
- class PositionComponent : Component
- {
- this(float x, float y)
- {
- this.x = x;
- this.y = y;
- }
- float x, y;
- }
- //Custom components
- class MovementComponent : Component
- {
- override void update(Entity entity)
- {
- if(entity.hasComponent!PositionComponent)
- {
- auto pos = entity.getComponent!PositionComponent;
- pos.x += xvel;
- pos.y += yvel;
- }
- }
- float xvel, yvel;
- }
- class PhysicsComponent : Component
- {
- immutable gravity = 5; //Arbitrary number
- override void update(Entity entity)
- {
- if(entity.hasComponent!(PositionComponent, MovementComponent))
- {
- auto mov = entity.getComponent!MovementComponent;
- mov.yvel -= gravity;
- }
- }
- }
- class GraphicsComponent : Component
- {
- override void update(Entity entity)
- {
- /+ code for rendering to screen +/
- }
- }
- ///Misc, used for ticking 30 times per second.
- struct Updater
- {
- double getUpdates()
- {
- /* Kudos to Yepoleb who helped me with this */
- MonoTime newtime = MonoTime.currTime();
- Duration duration = newtime - _lasttime;
- double durationmsec = duration.total!"nsecs" / (10.0 ^^ 6);
- _lasttime = newtime;
- _msecs += durationmsec;
- int updates = cast(int)(_msecs / _interval);
- _msecs -= updates * _interval;
- return updates;
- }
- void resetUpdates()
- {
- _lasttime = MonoTime.currTime();
- }
- private MonoTime _lasttime;
- private double _msecs = 0, _interval = 1000/30;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement