monovania/system/input_fire.go

79 lines
1.7 KiB
Go
Raw Permalink Normal View History

2021-11-16 18:38:24 +00:00
package system
import (
"math"
"time"
"code.rocketnine.space/tslocum/gohan"
"code.rocketnine.space/tslocum/monovania/component"
2021-12-08 05:11:47 +00:00
"code.rocketnine.space/tslocum/monovania/entity"
2021-11-16 18:38:24 +00:00
"github.com/hajimehoshi/ebiten/v2"
)
func angle(x1, y1, x2, y2 float64) float64 {
return math.Atan2(y1-y2, x1-x2)
}
type fireWeaponSystem struct {
player gohan.Entity
}
func NewFireWeaponSystem(player gohan.Entity) *fireWeaponSystem {
return &fireWeaponSystem{
player: player,
}
}
2021-12-08 05:11:47 +00:00
func (_ *fireWeaponSystem) Needs() []gohan.ComponentID {
return []gohan.ComponentID{
component.PositionComponentID,
2021-12-15 06:22:57 +00:00
component.SpriteComponentID,
2021-12-08 05:11:47 +00:00
component.WeaponComponentID,
}
}
2021-11-16 18:38:24 +00:00
2021-12-08 05:11:47 +00:00
func (_ *fireWeaponSystem) Uses() []gohan.ComponentID {
return nil
2021-11-16 18:38:24 +00:00
}
2021-12-15 06:22:57 +00:00
func (s *fireWeaponSystem) fire(weapon *component.WeaponComponent, position *component.PositionComponent, sprite *component.SpriteComponent, fireAngle float64) {
2021-11-16 18:38:24 +00:00
if time.Since(weapon.LastFire) < weapon.FireRate {
return
}
weapon.LastFire = time.Now()
speedX := math.Cos(fireAngle) * -weapon.BulletSpeed
speedY := math.Sin(fireAngle) * -weapon.BulletSpeed
2021-12-15 06:22:57 +00:00
offsetX := 8.0
if sprite.HorizontalFlip {
offsetX = -24
}
const bulletOffsetY = -5
bullet := entity.NewBullet(position.X+offsetX, position.Y+bulletOffsetY, speedX, speedY)
2021-11-16 18:38:24 +00:00
_ = bullet
}
2021-12-08 05:11:47 +00:00
func (s *fireWeaponSystem) Update(ctx *gohan.Context) error {
weapon := component.Weapon(ctx)
2021-12-15 06:22:57 +00:00
if !weapon.Equipped {
2021-11-16 18:38:24 +00:00
return nil
}
2021-12-15 06:22:57 +00:00
if ebiten.IsKeyPressed(ebiten.KeyL) {
position := component.Position(ctx)
sprite := component.Sprite(ctx)
fireAngle := math.Pi
if sprite.HorizontalFlip {
fireAngle = 0
}
s.fire(weapon, position, sprite, fireAngle)
2021-11-16 18:38:24 +00:00
}
return nil
}
2021-12-08 05:11:47 +00:00
func (_ *fireWeaponSystem) Draw(_ *gohan.Context, _ *ebiten.Image) error {
2021-11-16 18:38:24 +00:00
return gohan.ErrSystemWithoutDraw
}