Hi,
I am having problems getting a accelerometer user calibration to work, I can’t figure out how to obtain x,y coordinates from the device to set a new default tilt position.
code as follows.
[lua]
local physics = require “physics”;
physics.start();
physics.setGravity(0, 0);
–calibration sphere
local calibrationTarget = display.newCircle(0, 0, 5);
calibrationTarget:setFillColor(255,255,255);
physics.addBody(calibrationTarget, “dynamic”, {density = 1, bounce = 1, friction = 0.2, radius = 5});
calibrationTarget.x = display.contentCenterX;
calibrationTarget.y = display.contentCenterY;
–Movement/tilt
local tiltSpeed = 30;
local motionx = 0;
local motiony = 0;
–variables for tilt offset
local caliVar = {yCalibration = 0 ,xCalibration = 0};
local function onTilt(event)
--tilt
motionx = tiltSpeed * (event.yGravity - caliVar.yCalibration);
motiony = tiltSpeed * (event.xGravity - caliVar.xCalibration);
end
local function moveCalibrationTarget(event)
– Move
calibrationTarget.x = calibrationTarget.x - motionx;
calibrationTarget.y = calibrationTarget.y - motiony;
--stop the sphere leaving the screen
if(calibrationTarget.x<0)then
calibrationTarget.x = 0;
end
if(calibrationTarget.x>display.contentWidth)then
calibrationTarget.x = display.contentWidth;
end
if(calibrationTarget.y<0)then
calibrationTarget.y = 0;
end
if(calibrationTarget.y>display.contentHeight)then
calibrationTarget.y = display.contentHeight;
end
end
local function calibrate(event)
--when device tapped
if event.phase == “began” then
print(“calibrate”);
--add offset values to offset variables
caliVar.xCalibration = event.xGravity; --sets xCalibration value to nil…
print("xCalibration = ", caliVar.xCalibration);
caliVar.yCalibration = event.yGravity; --sets yCalibration value to nil…
print("yCalibration = ", caliVar.yCalibration);
--centre sphere on screen
calibrationTarget.x = display.contentCenterX;
calibrationTarget.y = display.contentCenterY;
end
end
Runtime:addEventListener(“touch”, calibrate);
Runtime:addEventListener(“accelerometer”, onTilt);
Runtime:addEventListener(“enterFrame”, moveCalibrationTarget);
[/lua]
The code above will work fine on the simulator and simply give the caliVar variables a nil value, but on a device the program will crash once the onTilt function is called with this runtime error:
attempt to perform arithmetic on field ‘yCalibration’ <a nil value>
I got the calibration code for this from: http://stackoverflow.com/questions/6182224/how-to-calibrate-the-accelerometer-angle-based-on-how-the-users-is-holding-the-d
I haven’t been able to find a solution to obtaining the x and y data, any help with this would be appreciated.
Thank you