The code below is intended to be added as a new tab to a copy of the Physics Lab example project and TestBoa()
as the first test in the list of tests in the Main
tab’s setup()
function. It makes use of the linearDamping
property of a physics.body
, that is not currently documented in the in-app reference. As the test ‘turns off defaultGravity’, it is important that it is the first test.
An example of the test running is below:
--
-- Boa, a Physics Lab test
-- Add TestBoa() to tests = {TestBoa(), ...} list in Main setup()
--
TestBoa = class()
local HEAD, BODY, TAIL = 1, 2, 3
local size = 10 -- Sets the scale of the snake
function TestBoa:init()
self.title="Boa - Touch and drag head to move"
local linkPoints = {}
linkPoints[HEAD] = {
vec2(1, 2),
vec2(0.5, 4),
vec2(-0.5, 4),
vec2(-1, 2),
vec2(-1, -3),
vec2(0, -4),
vec2(1, -3)}
linkPoints[BODY] = {
vec2(1, 3),
vec2(0, 4),
vec2(-1, 3),
vec2(-1, -3),
vec2(0, -4),
vec2(1, -3)}
linkPoints[TAIL] = {
vec2(1, 3),
vec2(0, 4),
vec2(-1, 3),
vec2(-1, 2),
vec2(0, -4),
vec2(1, 2)}
for k, v in ipairs(linkPoints) do
for i = 1, #v do
v[i] = v[i] * size
end
end
self.createLink = function(centre, type)
local points = linkPoints[type]
local link = physics.body(POLYGON, unpack(points))
link.x = centre.x
link.y = centre.y
if type ~= HEAD then link.linearDamping = 1 end
debugDraw:addBody(link)
return link
end
end
function TestBoa:setup()
self.links = {}
self.joints = {}
local nLinks = 10 -- Sets the length of the snake
self.links[1] = self.createLink(vec2(WIDTH/2, HEIGHT * 4/5), HEAD)
for i = 2, nLinks do
local type = BODY
if i == nLinks then type = TAIL end
local n = #self.links
local ol = self.links[n]
local oc = ol.position
local nc = oc + vec2(0, -6 * size)
local nl = self.createLink(nc, type)
self.links[n + 1] = nl
local joint = physics.joint(REVOLUTE, nl, ol, (oc + nc) / 2)
debugDraw:addJoint(joint)
end
-- Turn off defaultGravity (if first test setup by Physics Lab)
physics.gravity(0, 0)
end
function TestBoa:cleanup()
self.links = nil
self.joints = nil
end
function TestBoa:draw()
local head = self.links[1]
local hPos = head.position
local hAng = head.angle
pushStyle()
pushMatrix()
translate(hPos.x, hPos.y)
rotate(hAng)
-- Draw a forked tongue
lineCapMode(ROUND)
stroke(255, 0, 0)
strokeWidth(10)
line(0, 4 * size, 0, 5 * size)
strokeWidth(7)
line(0, 5 * size, -0.3 * size, 5.5 * size)
line(0, 5 * size, 0.3 * size, 5.5 * size)
-- Draw two eyes
noStroke()
fill(255)
ellipse(-0.7 * size, 2 * size, 0.8 * size)
ellipse(0.7 * size, 2 * size, 0.8 * size)
popMatrix()
popStyle()
end
function TestBoa:touched(touch)
end