sosolimited / Entity-Component-Samples

Cinder block for EntityX and a brief ECS tutorial.
MIT License
99 stars 12 forks source link

EntityCreation crash when drag #35

Open zoujyjs opened 6 years ago

zoujyjs commented 6 years ago

The mouse drag entity has a DragTracker behavior which listens to a mouseUp event. In the event callback, the entity will destroy itself leaving the behavior component a destroyed vector while still iterating.

I think the destroy behavior should really be delayed to the end of the current frame. Because it has so many sideeffects.

  // Assign a drag behavior component.
  auto tracker = assignBehavior<DragTracker>(mouse_entity);

  // When drag ends, run our lambda to create a new dot.
  tracker->setMouseUpCallback([this, mouse_entity] (const vec2 &position, const vec2 &previous) mutable {
    auto dir = position - previous;

    createDot(position, dir, 49.0f);
    mouse_entity.destroy();
  });

void BehaviorSystem::mouseUp( const ci::app::MouseEvent &event )
{
  ComponentHandle<BehaviorComponent> behavior;
  for( auto __unused e : _entities.entities_with_components( behavior ) )
  {
    auto &behaviors = behavior->behaviors;
    for( auto &b : behaviors ) {
      b->mouseUp( event );
    }
  }
}