com.badlogic.ashley.core.Entity Java Examples

The following examples show how to use com.badlogic.ashley.core.Entity. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Charm.java    From xibalba with MIT License 6 votes vote down vote up
@Override
public void act(Entity caster, Entity target) {
  if (ComponentMappers.charmed.has(target)) {
    return;
  }

  target.add(new CharmedComponent(life));

  if (ComponentMappers.player.has(target)) {
    WorldManager.log.add("effects.charmed.started", "You", "are");
  } else {
    AttributesComponent attributes = ComponentMappers.attributes.get(target);

    WorldManager.log.add("effects.charmed.started", attributes.name, "is");
  }
}
 
Example #2
Source File: CharmedSystem.java    From xibalba with MIT License 6 votes vote down vote up
@Override
protected void processEntity(Entity entity, float deltaTime) {
  CharmedComponent charmed = ComponentMappers.charmed.get(entity);

  if (charmed.counter == charmed.life) {
    entity.remove(CharmedComponent.class);

    boolean isPlayer = ComponentMappers.player.has(entity);
    AttributesComponent attributes = ComponentMappers.attributes.get(entity);

    WorldManager.log.add(
        "effects.charmed.stopped",
        (isPlayer ? "You" : attributes.name),
        (isPlayer ? "are" : "is")
    );
  } else {
    charmed.counter += 1;
  }
}
 
Example #3
Source File: GameSaver.java    From StockSimulator with GNU General Public License v2.0 6 votes vote down vote up
public String saveToJson() {
    gameState.stopThread();
    try {
        ImmutableArray<Entity> entities = gameState.getEntityEngine().getEntities();
        SavedGame savedGame = new SavedGame();
        for (Entity entity : entities) {
            List<ComponentContainer> componentContainers = new ArrayList<ComponentContainer>();
            for (Component c : entity.getComponents()) {
                componentContainers.add(new ComponentContainer(c));
            }
            EntityContainer entityContainer = new EntityContainer(entity.getId(), entity.getClass().getName(), componentContainers);
            savedGame.entitiesContainers.add(entityContainer);

        }

        return new GsonBuilder().enableComplexMapKeySerialization().create().toJson(savedGame);
    } catch (Exception e) {
        e.printStackTrace();
    }
    gameState.startThread();
    return "Failed";
}
 
Example #4
Source File: HudRenderer.java    From xibalba with MIT License 6 votes vote down vote up
private String createEntityOxygen(Entity entity) {
  AttributesComponent attributes = ComponentMappers.attributes.get(entity);

  String oxygenTextColor = attributes.oxygen < attributes.maxOxygen / 2 ? "[RED]" : "[CYAN]";
  String oxygenText = oxygenTextColor + attributes.oxygen
      + "[LIGHT_GRAY]/" + attributes.maxOxygen;
  StringBuilder oxygenBar = new StringBuilder("[LIGHT_GRAY]OX [[");

  for (int i = 0; i < MathUtils.floor(attributes.maxOxygen / 4); i++) {
    if (attributes.oxygen < (i * 4)) {
      oxygenBar.append("[DARK_GRAY]x");
    } else {
      oxygenBar.append("[CYAN]x");
    }
  }

  oxygenBar.append("[LIGHT_GRAY]]");

  return oxygenBar + " " + oxygenText;
}
 
Example #5
Source File: World.java    From ashley-superjumper with Apache License 2.0 6 votes vote down vote up
private void createSpring(float x, float y) {
	Entity entity = engine.createEntity();
	
	SpringComponent spring = engine.createComponent(SpringComponent.class);
	BoundsComponent bounds = engine.createComponent(BoundsComponent.class);
	TransformComponent position = engine.createComponent(TransformComponent.class);
	TextureComponent texture = engine.createComponent(TextureComponent.class);
	
	bounds.bounds.width = SpringComponent.WIDTH;
	bounds.bounds.height = SpringComponent.HEIGHT;
	
	position.pos.set(x, y, 2.0f);
	
	texture.region = Assets.spring;
	
	entity.add(spring);
	entity.add(bounds);
	entity.add(position);
	entity.add(texture);
	
	engine.addEntity(entity);
}
 
Example #6
Source File: Bleed.java    From xibalba with MIT License 6 votes vote down vote up
@Override
public void act(Entity caster, Entity target) {
  if (ComponentMappers.bleeding.has(target)) {
    return;
  }

  if (MathUtils.random() < chance / 100) {
    target.add(new BleedingComponent(damage, life));

    if (ComponentMappers.player.has(target)) {
      WorldManager.log.add("effects.bleeding.started", "You", "are");
    } else {
      AttributesComponent attributes = ComponentMappers.attributes.get(target);

      WorldManager.log.add("effects.bleeding.started", attributes.name, "is");
    }
  }
}
 
Example #7
Source File: EntityFactory.java    From xibalba with MIT License 6 votes vote down vote up
/**
 * Create exit entity.
 *
 * @param mapIndex Map to place it on
 * @return The exit entity
 */
public Entity createExit(int mapIndex) {
  Map map = WorldManager.world.getMap(mapIndex);

  int cellX;
  int cellY;

  do {
    cellX = MathUtils.random(0, map.width - 1);
    cellY = MathUtils.random(0, map.height - 1);
  } while (WorldManager.mapHelpers.isBlocked(mapIndex, new Vector2(cellX, cellY))
      && WorldManager.mapHelpers.getWallNeighbours(mapIndex, cellX, cellY) >= 4);

  Vector2 position = new Vector2(cellX, cellY);
  Entity entity = new Entity();
  entity.add(new ExitComponent());
  entity.add(new PositionComponent(position));

  entity.add(new VisualComponent(
      Main.asciiAtlas.createSprite("1403"), position
  ));

  return entity;
}
 
Example #8
Source File: WorldRenderer.java    From xibalba with MIT License 6 votes vote down vote up
private void renderItems() {
  ImmutableArray<Entity> entities =
      WorldManager.engine.getEntitiesFor(
          Family.all(ItemComponent.class, PositionComponent.class, VisualComponent.class).get()
      );

  for (Entity entity : entities) {
    PositionComponent position = ComponentMappers.position.get(entity);

    if (Main.tweenManager.getRunningTimelinesCount() == 0) {
      WorldManager.entityHelpers.updateSprite(entity, position.pos.x, position.pos.y);
    }

    if (WorldManager.entityHelpers.isVisible(entity)) {
      ComponentMappers.visual.get(entity).sprite.draw(batch);
    }
  }
}
 
Example #9
Source File: SquirrelSystem.java    From ashley-superjumper with Apache License 2.0 6 votes vote down vote up
@Override
public void processEntity(Entity entity, float deltaTime) {
	TransformComponent t = tm.get(entity);
	MovementComponent mov = mm.get(entity);
	
	if (t.pos.x < SquirrelComponent.WIDTH * 0.5f) {
		t.pos.x = SquirrelComponent.WIDTH * 0.5f;
		mov.velocity.x = SquirrelComponent.VELOCITY;
	}
	if (t.pos.x > World.WORLD_WIDTH - SquirrelComponent.WIDTH * 0.5f) {
		t.pos.x = World.WORLD_WIDTH - SquirrelComponent.WIDTH * 0.5f;
		mov.velocity.x = -SquirrelComponent.VELOCITY;
	}
	
	t.scale.x = mov.velocity.x < 0.0f ? Math.abs(t.scale.x) * -1.0f : Math.abs(t.scale.x);
}
 
Example #10
Source File: PillSystem.java    From Pacman_libGdx with MIT License 6 votes vote down vote up
@Override
protected void processEntity(Entity entity, float deltaTime) {

    PillComponent pill = pillM.get(entity);
    MovementComponent movement = movementM.get(entity);

    Body body = movement.body;
    if (pill.eaten) {
        if (pill.big) {
            GameManager.instance.addScore(500);
            GameManager.instance.assetManager.get("sounds/big_pill.ogg", Sound.class).play();
        } else {
            GameManager.instance.addScore(100);
            GameManager.instance.assetManager.get("sounds/pill.ogg", Sound.class).play();
        }

        body.getWorld().destroyBody(body);
        getEngine().removeEntity(entity);

        GameManager.instance.totalPills--;
    }

}
 
Example #11
Source File: MapHelpers.java    From xibalba with MIT License 6 votes vote down vote up
/**
 * Try to find an entity at x, y.
 *
 * @param cellX x
 * @param cellY y
 * @return Either the entity or null if none were found
 */
public Entity getEntityAt(float cellX, float cellY) {
  ImmutableArray<Entity> entities =
      WorldManager.engine.getEntitiesFor(
          Family.all(PositionComponent.class).exclude(
              DecorationComponent.class, LightComponent.class
          ).get()
      );

  for (Entity entity : entities) {
    PositionComponent entityPosition = ComponentMappers.position.get(entity);

    if (entityPosition.pos.x == cellX && entityPosition.pos.y == cellY) {
      return entity;
    }
  }

  return null;
}
 
Example #12
Source File: ItemHelpers.java    From xibalba with MIT License 6 votes vote down vote up
/**
 * Get a list of components from the entity's inventory for the given item.
 *
 * @param entity Who's inventory to check
 * @param item   The item who's components we're getting
 * @return A list of components
 */
public ArrayList<Entity> getComponentsForItem(Entity entity, Entity item) {
  ItemComponent itemDetails = ComponentMappers.item.get(item);
  InventoryComponent inventory = ComponentMappers.inventory.get(entity);
  ArrayList<Entity> components = new ArrayList<>();

  if (inventory != null) {
    for (ItemComponent.RequiredComponent requiredComponent : itemDetails.requiredComponents) {
      ItemComponent requiredComponentDetails = ComponentMappers.item.get(requiredComponent.item);

      for (Entity inventoryItem : inventory.items) {
        ItemComponent inventoryItemDetails = ComponentMappers.item.get(inventoryItem);

        if (requiredComponentDetails.key.equals(inventoryItemDetails.key)) {
          components.add(inventoryItem);
        }
      }
    }
  }

  return components;
}
 
Example #13
Source File: ItemHelpers.java    From xibalba with MIT License 6 votes vote down vote up
/**
 * Remove an item from inventory.
 *
 * @param entity Who's inventory
 * @param item   The item
 */
private void removeFromInventory(Entity entity, Entity item) {
  InventoryComponent inventory = ComponentMappers.inventory.get(entity);
  inventory.items.remove(item);

  AttributesComponent attributes = ComponentMappers.attributes.get(entity);

  if (getTotalWeight(entity) <= attributes.strength * 5
      && ComponentMappers.encumbered.has(entity)) {
    entity.remove(EncumberedComponent.class);

    if (ComponentMappers.player.has(entity)) {
      WorldManager.log.add("effects.encumbered.stopped");
    }
  }
}
 
Example #14
Source File: Poison.java    From xibalba with MIT License 6 votes vote down vote up
@Override
public void act(Entity caster, Entity target) {
  if (ComponentMappers.poisoned.has(target)) {
    return;
  }

  if (MathUtils.random() < chance / 100) {
    target.add(new PoisonedComponent(damage, life));

    if (ComponentMappers.player.has(target)) {
      WorldManager.log.add("effects.poisoned.started", "You", "are");
    } else {
      AttributesComponent attributes = ComponentMappers.attributes.get(target);

      WorldManager.log.add("effects.poisoned.started", attributes.name, "is");
    }
  }
}
 
Example #15
Source File: World.java    From ashley-superjumper with Apache License 2.0 5 votes vote down vote up
private void createCamera(Entity target) {
	Entity entity = engine.createEntity();
	
	CameraComponent camera = new CameraComponent();
	camera.camera = engine.getSystem(RenderingSystem.class).getCamera();
	camera.target = target;
	
	entity.add(camera);
	
	engine.addEntity(entity);
}
 
Example #16
Source File: WorldRenderer.java    From xibalba with MIT License 5 votes vote down vote up
private void renderPlayer() {
  ImmutableArray<Entity> entities =
      WorldManager.engine.getEntitiesFor(Family.all(PlayerComponent.class).get());

  if (entities.size() > 0) {
    Entity player = entities.first();

    if (Main.tweenManager.getRunningTimelinesCount() == 0) {
      PositionComponent position = ComponentMappers.position.get(player);
      WorldManager.entityHelpers.updateSprite(player, position.pos.x, position.pos.y);
    }

    ComponentMappers.visual.get(player).sprite.draw(batch);
  }
}
 
Example #17
Source File: WetSystem.java    From xibalba with MIT License 5 votes vote down vote up
@Override
protected void processEntity(Entity entity, float deltaTime) {
  WetComponent wet = ComponentMappers.wet.get(entity);
  PositionComponent position = ComponentMappers.position.get(entity);

  if (!WorldManager.mapHelpers.getCell(position.pos.x, position.pos.y).isWater()) {
    if (wet.counter == wet.life) {
      entity.remove(WetComponent.class);
    } else {
      WorldManager.mapHelpers.makeFloorWet(position.pos);

      wet.counter += 1;
    }
  }
}
 
Example #18
Source File: MarketSystem.java    From StockSimulator with GNU General Public License v2.0 5 votes vote down vote up
private void updatePlayerValues(ImmutableArray<Entity> entities) {
    ImmutableArray<Entity> players = engine.getEntitiesFor(playerFamily);
    for (Entity p:players) {
        int wallet_amount = p.getComponent(WalletComponent.class).balance;
        int investment_amount = p.getComponent(InventoryComponent.class).getInventoryValue(entities);
        p.getComponent(PriceHistoryComponent.class).registerPrice(new PriceComponent(investment_amount+wallet_amount),interval);
    }


}
 
Example #19
Source File: PlayerSystem.java    From Pacman_libGdx with MIT License 5 votes vote down vote up
@Override
protected void processEntity(Entity entity, float deltaTime) {
    PlayerComponent player = playerM.get(entity);
    StateComponent state = stateM.get(entity);
    MovementComponent movement = movementM.get(entity);
    Body body = movement.body;

    if (player.hp > 0) {
        if ((Gdx.input.isKeyPressed(Input.Keys.D) || Gdx.input.isKeyPressed(Input.Keys.RIGHT)) && checkMovable(body, MoveDir.RIGHT)) {
            body.applyLinearImpulse(tmpV1.set(movement.speed, 0).scl(body.getMass()), body.getWorldCenter(), true);

        } else if ((Gdx.input.isKeyPressed(Input.Keys.A) || Gdx.input.isKeyPressed(Input.Keys.LEFT)) && checkMovable(body, MoveDir.LEFT)) {
            body.applyLinearImpulse(tmpV1.set(-movement.speed, 0).scl(body.getMass()), body.getWorldCenter(), true);

        } else if ((Gdx.input.isKeyPressed(Input.Keys.W) || Gdx.input.isKeyPressed(Input.Keys.UP)) && checkMovable(body, MoveDir.UP)) {
            body.applyLinearImpulse(tmpV1.set(0, movement.speed).scl(body.getMass()), body.getWorldCenter(), true);

        } else if ((Gdx.input.isKeyPressed(Input.Keys.S) || Gdx.input.isKeyPressed(Input.Keys.DOWN))&& checkMovable(body, MoveDir.DOWN)) {
            body.applyLinearImpulse(tmpV1.set(0, -movement.speed).scl(body.getMass()), body.getWorldCenter(), true);

        }

        if (body.getLinearVelocity().len2() > movement.speed * movement.speed) {
            body.setLinearVelocity(body.getLinearVelocity().scl(movement.speed / body.getLinearVelocity().len()));
        }
    }

    // player is invincible for 3 seconds when spawning
    if (GameManager.instance.playerIsInvincible) {
        player.invincibleTimer += deltaTime;
        if (player.invincibleTimer >= 3.0f) {
            GameManager.instance.playerIsInvincible = false;
            player.invincibleTimer = 0;
        }
    }

    player.playerAgent.update(deltaTime);
    state.setState(player.currentState);
}
 
Example #20
Source File: AnimationSystem.java    From ashley-superjumper with Apache License 2.0 5 votes vote down vote up
@Override
public void processEntity(Entity entity, float deltaTime) {
	TextureComponent tex = tm.get(entity);
	AnimationComponent anim = am.get(entity);
	StateComponent state = sm.get(entity);
	
	Animation animation = anim.animations.get(state.get());
	
	if (animation != null) {
		tex.region = animation.getKeyFrame(state.time); 
	}
	
	state.time += deltaTime;
}
 
Example #21
Source File: MovementSystem.java    From ashley with Apache License 2.0 5 votes vote down vote up
@Override
public void processEntity (Entity entity, float deltaTime) {
	PositionComponent pos = pm.get(entity);
	MovementComponent mov = mm.get(entity);

	tmp.set(mov.accel).scl(deltaTime);
	mov.velocity.add(tmp);

	tmp.set(mov.velocity).scl(deltaTime);
	pos.pos.add(tmp.x, tmp.y, 0.0f);
}
 
Example #22
Source File: BobSystem.java    From ashley-superjumper with Apache License 2.0 5 votes vote down vote up
public void hitPlatform (Entity entity) {
	if (!family.matches(entity)) return;
	
	StateComponent state = sm.get(entity);
	MovementComponent mov = mm.get(entity);
	
	mov.velocity.y = BobComponent.JUMP_VELOCITY;
	state.set(BobComponent.STATE_JUMP);
}
 
Example #23
Source File: SortedIteratingSystemTest.java    From ashley with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void shouldIterateEntitiesWithCorrectFamily () {
	final Engine engine = new Engine();

	final Family family = Family.all(OrderComponent.class, ComponentB.class).get();
	final SortedIteratingSystemMock system = new SortedIteratingSystemMock(family);
	final Entity e = new Entity();

	engine.addSystem(system);
	engine.addEntity(e);

	// When entity has OrderComponent
	e.add(new OrderComponent("A", 0));
	engine.update(deltaTime);

	// When entity has OrderComponent and ComponentB
	e.add(new ComponentB());
	system.expectedNames.addLast("A");
	engine.update(deltaTime);

	// When entity has OrderComponent, ComponentB and ComponentC
	e.add(new ComponentC());
	system.expectedNames.addLast("A");
	engine.update(deltaTime);

	// When entity has ComponentB and ComponentC
	e.remove(OrderComponent.class);
	e.add(new ComponentC());
	engine.update(deltaTime);
}
 
Example #24
Source File: MapHelpers.java    From xibalba with MIT License 5 votes vote down vote up
/**
 * Get all entities in vision of the player.
 *
 * @return List of entities within player's vision
 */
ArrayList<Entity> getEnemiesInPlayerVision() {
  ArrayList<Entity> enemies = new ArrayList<>();

  PositionComponent position = ComponentMappers.position.get(WorldManager.player);
  AttributesComponent attributes = ComponentMappers.attributes.get(WorldManager.player);

  int positionX = (int) position.pos.x;
  int positionY = (int) position.pos.y;

  for (int x = positionX - attributes.vision; x < positionX + attributes.vision; x++) {
    for (int y = positionY - attributes.vision; y < positionY + attributes.vision; y++) {
      Entity enemy = getEnemyAt(x, y);

      if (enemy != null) {
        enemies.add(enemy);
      }
    }
  }

  enemies.sort((enemy1, enemy2) -> {
    PositionComponent enemy1Position = ComponentMappers.position.get(enemy1);
    PositionComponent enemy2Position = ComponentMappers.position.get(enemy2);

    return enemy1Position.pos.x > enemy2Position.pos.x
        && enemy1Position.pos.y > enemy2Position.pos.y
        ? -1 : 1;
  });

  return enemies;
}
 
Example #25
Source File: ItemHelpers.java    From xibalba with MIT License 5 votes vote down vote up
/**
 * Get the slot location of an item.
 *
 * @param entity The entity who's equipped the item
 * @param item   The item we want to check
 * @return Location of item
 */
public String getLocation(Entity entity, Entity item) {
  EquipmentComponent equipment = ComponentMappers.equipment.get(entity);

  for (Map.Entry<String, Entity> slot : equipment.slots.entrySet()) {
    if (slot.getValue() == item) {
      return slot.getKey();
    }
  }

  return null;
}
 
Example #26
Source File: SortedIteratingSystemTest.java    From ashley with Apache License 2.0 5 votes vote down vote up
@Override
public void processEntity (Entity entity, float deltaTime) {
	OrderComponent component = orderMapper.get(entity);
	assertNotNull(component);
	assertFalse(expectedNames.isEmpty());
	assertEquals(expectedNames.poll(), component.name);
}
 
Example #27
Source File: ItemHelpers.java    From xibalba with MIT License 5 votes vote down vote up
/**
 * Find out if an entity has the ammunition it needs.
 *
 * @param entity Who needs to know
 * @param type   Type of ammunition they're looking for
 * @return Whether or not they got it
 */
public boolean hasAmmunitionOfType(Entity entity, String type) {
  ArrayList<Entity> items = ComponentMappers.inventory.get(entity).items;

  for (Entity item : items) {
    AmmunitionComponent ammunition = ComponentMappers.ammunition.get(item);

    if (ammunition != null && Objects.equals(ammunition.type, type)) {
      return true;
    }
  }

  return false;
}
 
Example #28
Source File: World.java    From ashley-superjumper with Apache License 2.0 5 votes vote down vote up
private void createBackground() {
	Entity entity = engine.createEntity();
	
	BackgroundComponent background = engine.createComponent(BackgroundComponent.class);
	TransformComponent position = engine.createComponent(TransformComponent.class);
	TextureComponent texture = engine.createComponent(TextureComponent.class);
	
	texture.region = Assets.backgroundRegion;
	
	entity.add(background);
	entity.add(position);
	entity.add(texture);
	
	engine.addEntity(entity);
}
 
Example #29
Source File: EncumberedSystem.java    From xibalba with MIT License 5 votes vote down vote up
@Override
protected void processEntity(Entity entity, float deltaTime) {
  EncumberedComponent encumbered = ComponentMappers.encumbered.get(entity);

  if (encumbered.turnCounter == 2) {
    encumbered.turnCounter = 0;
  } else {
    encumbered.turnCounter += 1;
  }
}
 
Example #30
Source File: EntityDeleterSystem.java    From entity-system-benchmarks with Apache License 2.0 5 votes vote down vote up
protected void processSystem() {
		if (counter == 100) {

//			Entity e = entities.get(ids[index++]);
			Entity e = entities.get(0);
			
			engine.removeEntity(e);
			index = index % JmhSettings.ENTITY_COUNT;
			counter = 0;
		} else if (counter == 1) { // need to wait one round to reclaim entities
			createEntity();
		}
	}