forked from gophergala2016/spacegophers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shot.go
61 lines (51 loc) · 1.58 KB
/
shot.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main
import (
"encoding/json"
"math"
"time"
"github.com/xtgo/uuid"
)
const (
// shot speed is the speed of the shot that is fired.
shotSpeed = thrustAcceleration * timestep * 80 * 5
// defaultShotLifetime is the lifetime (in sec) for each shot
defaultShotLifetime = 1 * time.Second
defaultLifeCycles = defaultShotLifetime / DefaultPhysicsLoopInterval
)
// NewShot returns a new shot from a given Gopher. The location is set to the
// middle of the gopher and is fired at the speed of the gopher plus the shot's
// own speed in the direction of the angle of the Gopher.
func NewShot(u *User, g Gopher) Shot {
posx := g.Position.X + math.Cos(g.Angle)*halfGopherSize
posy := g.Position.Y + math.Sin(g.Angle)*halfGopherSize
velx := g.Velocity.X + math.Cos(g.Angle)*shotSpeed
vely := g.Velocity.Y + math.Sin(g.Angle)*shotSpeed
return Shot{
ID: uuid.NewRandom().String(),
Gopher: g.UserID,
User: u,
Entity: NewEntity(thrustAcceleration, posx, posy, velx, vely, g.Angle),
Lifecycles: int64(defaultLifeCycles),
}
}
// Shot describes a projectile emmitted from a Gopher designed to destroy other
// Gopher's.
type Shot struct {
ID string `json:"i"`
Gopher string `json:"g"`
User *User `json:"-"`
Lifecycles int64 `json:"-"`
Entity
}
func (s Shot) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{
"i": s.ID,
"p": s.Position,
"a": Round(s.Angle*180.0/math.Pi) % 360,
"g": s.Gopher,
})
}
// IsAlive will return true if the shot is still active.
func (s *Shot) IsAlive() bool {
return s.Lifecycles > 0
}