When experimenting with the Gravity functions in Codea, I thought it would be nice to make some sort of controller where the gravity is used to trigger certain actions.
GravityControl = class()
GravityControl.null={name="NULL",gravity=vec3(0,0,0)}
GravityControl.upright={name="UPRIGHT",gravity=vec3(0,-1,0)}
GravityControl.upsidedown={name="UPSIDEDOWN",gravity=vec3(0,1,0)}
GravityControl.back={name="BACK",gravity=vec3(0,0,-1)}
GravityControl.front={name="FRONT",gravity=vec3(0,0,1)}
GravityControl.left={name="LEFT",gravity=vec3(-1,0,0)}
GravityControl.right={name="RIGHT",gravity=vec3(1,0,0)}
GravityControl.pollingInterval=0.25
function GravityControl:init(restState, actionState, action)
self.currentState=self.null
self.probability=0
self.restState=restState
self.actionState=actionState
self.action=action
self.devicePositions={
self.upright,
self.upsidedown,
self.back,
self.front,
self.left,
self.right
}
end
function GravityControl:start()
tween.delay(GravityControl.pollingInterval, function() self:update() end)
end
function GravityControl:guessState()
local minDistance=9999
local bestMatch=self.null
for i,p in pairs(self.devicePositions) do
local currentDistance=Gravity:dist(p.gravity)
if currentDistance<minDistance then
minDistance=currentDistance
bestMatch=p
end
end
return bestMatch,minDistance
end
function GravityControl:getPosition()
return self.currentState.name, 1-self.probability
end
function GravityControl:update()
self.currentState,self.probability=self:guessState()
if (self.currentState==self.actionState) and (self.previousState==self.restState) then
self:action()
end
self.previousState=self.currentState
self:start()
end