Skip to content

Commit

Permalink
shape: Add support for setting mass/density on Shapes (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
usedbytes authored Oct 18, 2020
1 parent 8b35e35 commit 9264fe3
Show file tree
Hide file tree
Showing 3 changed files with 122 additions and 0 deletions.
52 changes: 52 additions & 0 deletions body_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package cp

import (
"testing"
)

func TestBodyMassFromShapes(t *testing.T) {
body := NewBody(0, 0)
circle := NewCircle(body, 5, Vector{0, 0})
circle2 := NewCircle(body, 5, Vector{0, 0})

mass := 10.0
circle.SetMass(mass)
body.AddShape(circle)

if body.Mass() != mass {
t.Fail()
}

circle2.SetMass(mass)
body.AddShape(circle2)

if body.Mass() != mass * 2 {
t.Fail()
}
}

func TestBodyCoGFromShapes(t *testing.T) {
body := NewBody(0, 0)
circle := NewCircle(body, 5, Vector{0, 0})
circle2 := NewCircle(body, 5, Vector{10, 0})

mass := 10.0

circle.SetMass(mass)
body.AddShape(circle)

circle2.SetMass(mass)
body.AddShape(circle2)

cog := body.CenterOfGravity()
if cog.X != 5.0 || cog.Y != 0.0 {
t.Fail()
}

body.RemoveShape(circle)
cog = body.CenterOfGravity()
if cog.X != 10.0 || cog.Y != 0.0 {
t.Fail()
}

}
31 changes: 31 additions & 0 deletions shape.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,37 @@ func (s *Shape) MassInfo() *ShapeMassInfo {
return s.massInfo
}

func (s *Shape) Mass() float64 {
return s.massInfo.m
}

func (s *Shape) SetMass(mass float64) {
s.body.Activate()

s.massInfo.m = mass
s.body.AccumulateMassFromShapes()
}

func (s *Shape) Density() float64 {
return s.massInfo.m / s.massInfo.area
}

func (s *Shape) SetDensity(density float64) {
s.SetMass(density * s.massInfo.area)
}

func (s *Shape) Moment() float64 {
return s.massInfo.m * s.massInfo.i
}

func (s *Shape) Area() float64 {
return s.massInfo.area
}

func (s *Shape) CenterOfGravity() Vector {
return s.massInfo.cog
}

func (s *Shape) HashId() HashValue {
return s.hashid
}
Expand Down
39 changes: 39 additions & 0 deletions shape_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package cp

import (
"math"
"testing"
)

func TestShapeMass(t *testing.T) {
body := NewBody(0, 0)
circle := NewCircle(body, 5, Vector{0, 0})

mass := 10.0
circle.SetMass(mass)
body.AddShape(circle)

if circle.Mass() != mass {
t.Fail()
}
}

func TestShapeCircleArea(t *testing.T) {
body := NewBody(0, 0)
circle := NewCircle(body, 2, Vector{0, 0})

if circle.Area() != 4 * math.Pi {
t.Fail()
}
}

func TestShapeCircleDensity(t *testing.T) {
body := NewBody(0, 0)
circle := NewCircle(body, 1, Vector{0, 0})

circle.SetMass(math.Pi)

if circle.Density() != 1.0 {
t.Fail()
}
}

0 comments on commit 9264fe3

Please sign in to comment.