thanks, now another problem came up.
I want the gravity to activate itself after a 30degree phone tilt.
Works in every direction but not on the negative x axis (right side tilt)
Anyone knows a fix?
this is the code i made
-- Set up display and physics
local physics = require("physics")
physics.start()
-- Create a box object
local box = display.newRect(display.contentCenterX, 100, 50, 50)
box:setFillColor(1, 0.5, 0.5)
-- Enable physics for the box
physics.addBody(box, "dynamic", { density = 1.0, friction = 0.3, bounce = 0 })
-- Function to calculate angle in degrees from x and y gravity values
local function calculateTiltAngle(xGravity, yGravity)
return math.deg(math.atan2(yGravity, xGravity))
end
-- Function to handle accelerometer updates
local function onAccelerate(event)
local xGravity = event.xGravity
local yGravity = event.yGravity
-- Calculate tilt angle in degrees
local tiltAngle = calculateTiltAngle(xGravity, yGravity)
-- Apply gravity only if tilt angle is greater than 30 degrees or less than -30 degrees
if math.abs(tiltAngle) > 30 then
physics.setGravity(xGravity * 9.8, -yGravity * 9.8)
else
physics.setGravity(0, 0) -- No gravity if tilt angle is within -30 to 30 degrees
end
end
-- Set accelerometer interval and listen for changes
system.setAccelerometerInterval(60) -- Update interval in Hz
Runtime:addEventListener("accelerometer", onAccelerate)