|
| 1 | +/* |
| 2 | + * Copyright 2020 The Terasology Foundation |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package org.destinationsol.systems; |
| 17 | + |
| 18 | +import org.destinationsol.components.Health; |
| 19 | +import org.destinationsol.entitysystem.ComponentSystem; |
| 20 | +import org.destinationsol.entitysystem.EventReceiver; |
| 21 | +import org.destinationsol.events.DamageEvent; |
| 22 | +import org.terasology.gestalt.entitysystem.entity.EntityRef; |
| 23 | +import org.terasology.gestalt.entitysystem.event.EventResult; |
| 24 | +import org.terasology.gestalt.entitysystem.event.ReceiveEvent; |
| 25 | + |
| 26 | +/** |
| 27 | + * When a damage event happens to an entity with a health component, this system reads the damage from that event and |
| 28 | + * lowers its health by that amount. If it would lower the health to less than zero, it's reduced to zero instead. If |
| 29 | + * the damage is a negative amount, nothing happens. |
| 30 | + */ |
| 31 | +public class DamageSystem implements EventReceiver { |
| 32 | + |
| 33 | + /** |
| 34 | + * Handles a damage event done to an entity with a Health component. |
| 35 | + * |
| 36 | + * @param event the damage event that is occurring |
| 37 | + * @param entity the entity that the damage is happening to |
| 38 | + * @return the event should be processed by other systems, if there are |
| 39 | + */ |
| 40 | + @ReceiveEvent(components = Health.class) |
| 41 | + public EventResult onDamage(DamageEvent event, EntityRef entity) { |
| 42 | + if (event.getDamage() <= 0) { |
| 43 | + return EventResult.CONTINUE; |
| 44 | + } |
| 45 | + if (entity.getComponent(Health.class).isPresent()) { |
| 46 | + Health health = entity.getComponent(Health.class).get(); |
| 47 | + int newHealthAmount = health.currentHealth - event.getDamage(); |
| 48 | + if (newHealthAmount < 0) { |
| 49 | + newHealthAmount = 0; |
| 50 | + } |
| 51 | + health.currentHealth = newHealthAmount; |
| 52 | + entity.setComponent(health); |
| 53 | + } |
| 54 | + return EventResult.CONTINUE; |
| 55 | + } |
| 56 | +} |
0 commit comments