github.com/df-mc/dragonfly@v0.9.13/server/entity/health.go (about) 1 package entity 2 3 import "sync" 4 5 // HealthManager handles the health of an entity. 6 type HealthManager struct { 7 mu sync.RWMutex 8 health float64 9 max float64 10 } 11 12 // NewHealthManager returns a new health manager with the health and max health provided. 13 func NewHealthManager(health, max float64) *HealthManager { 14 if health > max { 15 health = max 16 } 17 return &HealthManager{health: health, max: max} 18 } 19 20 // Health returns the current health of an entity. 21 func (m *HealthManager) Health() float64 { 22 m.mu.RLock() 23 defer m.mu.RUnlock() 24 return m.health 25 } 26 27 // AddHealth adds a given amount of health points to the player. If the health added to the current health 28 // exceeds the max, health will be set to the max. If the health is instead negative and results in a health 29 // lower than 0, the final health will be 0. 30 func (m *HealthManager) AddHealth(health float64) { 31 m.mu.Lock() 32 defer m.mu.Unlock() 33 34 l := m.health + health 35 if l < 0 { 36 l = 0 37 } else if l > m.max { 38 l = m.max 39 } 40 m.health = l 41 } 42 43 // MaxHealth returns the maximum health of the entity. 44 func (m *HealthManager) MaxHealth() float64 { 45 m.mu.RLock() 46 defer m.mu.RUnlock() 47 48 return m.max 49 } 50 51 // SetMaxHealth changes the max health of an entity to the maximum passed. If the maximum is set to 0 or 52 // lower, SetMaxHealth will default to a value of 1. 53 func (m *HealthManager) SetMaxHealth(max float64) { 54 if max <= 0 { 55 max = 1 56 } 57 m.mu.Lock() 58 defer m.mu.Unlock() 59 m.max = max 60 if m.health > max { 61 m.health = max 62 } 63 }