-
Notifications
You must be signed in to change notification settings - Fork 0
/
ratchet_joint.go
89 lines (68 loc) · 1.67 KB
/
ratchet_joint.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package cm
import "math"
type RatchetJoint struct {
*Constraint
Angle, Phase, Ratchet float64
iSum, bias, jAcc float64
}
func NewRatchetJoint(a, b *Body, phase, ratchet float64) *Constraint {
joint := &RatchetJoint{
Phase: phase,
Ratchet: ratchet,
}
if b != nil {
joint.Angle = b.angle
}
if a != nil {
joint.Angle -= a.angle
}
joint.Constraint = NewConstraint(joint, a, b)
return joint.Constraint
}
func (joint *RatchetJoint) PreStep(dt float64) {
a := joint.bodyA
b := joint.bodyB
angle := joint.Angle
phase := joint.Phase
ratchet := joint.Ratchet
delta := b.angle - a.angle
diff := angle - delta
pdist := 0.0
if diff*ratchet > 0 {
pdist = diff
} else {
joint.Angle = math.Floor((delta-phase)/ratchet)*ratchet + phase
}
joint.iSum = 1.0 / (a.momentOfInertiaInverse + b.momentOfInertiaInverse)
maxBias := joint.maxBias
joint.bias = clamp(-biasCoef(joint.errorBias, dt)*pdist/dt, -maxBias, maxBias)
if joint.bias == 0 {
joint.jAcc = 0
}
}
func (joint *RatchetJoint) ApplyCachedImpulse(dtCoef float64) {
a := joint.bodyA
b := joint.bodyB
j := joint.jAcc * dtCoef
a.w -= j * a.momentOfInertiaInverse
b.w += j * b.momentOfInertiaInverse
}
func (joint *RatchetJoint) ApplyImpulse(dt float64) {
if joint.bias == 0 {
return
}
a := joint.bodyA
b := joint.bodyB
wr := b.w - a.w
ratchet := joint.Ratchet
jMax := joint.maxForce * dt
j := -(joint.bias + wr) * joint.iSum
jOld := joint.jAcc
joint.jAcc = clamp((jOld+j)*ratchet, 0, jMax*math.Abs(ratchet)) / ratchet
j = joint.jAcc - jOld
a.w -= j * a.momentOfInertiaInverse
b.w += j * b.momentOfInertiaInverse
}
func (joint *RatchetJoint) GetImpulse() float64 {
return math.Abs(joint.jAcc)
}