Applying accelometer movement in corona - lua

I am using corona sdk to move a plane using tilt. But my game is in landscape. I am not sure where the problem is in my code. The movement seems to be weird. I understand the problem is because the game is in landscape. Someone help me out with the solution.
Here is the code that I used
function onTilt(event)
motionx = 20*event.xGravity
motiony = 20*event.yGravity
plane.x=plane.x+motionx
plane.y=plane.y-motiony
end
Runtime:addEventListener("accelerometer", onTilt)

What do you mean by weird movement, can you be more specific? Try adding motion.y to plane.y instead of subtracting it. That might be the cause of your weird movement.

You can use -
-- Create an object
local object = display.newImage("indicator.png")
object:setReferencePoint(display.CenterReferencePoint)
object.x = display.contentWidth * 0.5
object.y = display.contentWidth * 0.5 + 50
-- Accelerometer Events
local accObject = {}
local centerX = display.contentWidth * 0.5
function accObject:accelerometer(e)
object.x = centerX + (centerX * e.xGravity)
end
Runtime:addEventListener("accelerometer", accObject)
Please try to use the above method as per your requirement. I hope, it will help you.

Got the solution.... In fact the solution was simple... Thanks everybody.
motionx = 20 * event.yGravity
motiony = 20 * event.xGravity
plane.x=plane.x-motionx
plane.y=plane.y-motiony

Related

Corona SDK object follows "swipe" direction?

I'm trying to do something very simple as I'm new to Corona SDK, but I'm having a lot of issues with it.
What I'm trying to accomplish is when a user "swipes", "flings", "flicks" a certain area of the screen (an image set to half the screen) a ball in the middle of the screen moves in that direction at a set speed. No physics or anything special. So basically, if you swipe the image at an angle, the ball will move to that angle and eventually off the screen unless you "swipe" the ball again in a different direction.
What i have so far is:
physics.addBody( ball, "dynamic" )
function flick(event)
if event.phase == "moved" then
ball:applyForce( (ball.x) * 0.5, (ball.y) * 0.5, ball.x, ball.y )
end
end
Currently when you move the ball it just shoots in one direction (the 0.5) how would i get the direction "flung"?
I'm new to corona and still trying to figure out the touch events. Still a little confusing to me.
Any help and advice is appreciated! Thanks everyone!
You need to track where the touch starts and ends: this is the flick. The difference between start and end along x and y will give direction of motion of ball. If ball speed depends on how fast user flicked, you need to track time too. Also, I'm not sure why you are making the force proportional to the object's position: this means that if the object is at 0,0 there is no force, that's probably not what you want. You would just want a force proportional to the flick vector. The amount of time would determine the time. It would look something like this:
local flickStartTime = 0
local function touch(event)
if event.phase == "began" then
flickStartTime = system.timer()
elseif event.phase == "ended" then
local flickDuration = system.timer() - flickStartTime
if flickDuration <= 0 then return end -- ignore flick
local speedX = (event.xStart - event.x)/flickDuration
local speedY = (event.yStart - event.y)/flickDuration
local coef = 0.1 -- adjust this via "trial and error" so moves at "reasonable" speed
-- only react to flick if it was large enough
if math.abs(event.xStart - event.x) > 10 or math.abs(event.yStart - event.y) > 10 then
ball:applyForce( coef * speedX, coef * speedY, ball.x, ball.y )
end
end
end
However you said you don't want any physics, yet you apply force, do you mean you just want to set the velocity? Then instead of applyForce you would call setLinearVelocity(speedX, speedY)
local speedX = (event.xStart - event.x)/flickDuration
local speedY = (event.yStart - event.y)/flickDuration
local coef = 0.1 -- adjust this via "trial and error" so moves at "reasonable" speed
-- only react to flick if it was large enough
if math.abs(event.xStart - event.x) > 10 or math.abs(event.yStart - event.y) > 10 then
ball:setLinearVelocity( coef * speedX, coef * speedY )
end
By the looks of it, flick is a touch listener. You must filter the event that is passed on, and determine which direction the user swiped. Read more about touch listeners here
What you are interested in, is the xStart and yStart properties, and measure how much the user moved, something like this:
local function flick(event)
if event.phase == "moved" then
local diffX = event.xStart - event.x
local diffY = event.yStart - event.y
if math.abs(diffX) > 10 or math.abs(diffY) > 10 then
ball:applyForce( (ball.x) * diffX, (ball.y) * diffY, ball.x, ball.y )
end
end
end

Make moving a rectangle (Remove/Reappear) Corona SDK

Hi Everyone,
I would like know one thing :
I want to make this rectangle moving from the left side to the right side with physics and loop, and make it disappear when is out the leftscreen, and make reappear it in the right side,
This is what I've made in my code but I would like know if there is another easiest way to do it.
Is it better to use transition.to ?
Ps : My game is an endless runner game where the player jump from the floor to rectangles in the air
if someone have tutorial for this, I get it ! thank you
thanks every one for all
local physics = require( "physics" )
physics.start()
physics.setDrawMode( "hybrid")
local _x = display.contentCenterX
local _y = display.contentCenterY
local speed = 10
local GroupMur1 = display.newGroup()
local Mur1 = display.newRect(680,25,680,25)
Mur1.x = _x +900
Mur1.y = _y +80
physics.addBody(Mur1, "static")
GroupMur1:insert(Mur1)
local a =1
local function update ()
if(a==1)then updateMur1() end
if(a==2)then updateMur2() end
end
function updateMur1 ()
GroupMur1.x =GroupMur1.x - speed
if(GroupMur1.x < -2000) then
GroupMur1:remove(1)
a=2
end
end
function updateMur2()
GroupMur1:insert(Mur1)
physics.addBody(Mur1, "static")
GroupMur1.x = _x + 900
a=1
end
timer.performWithDelay(1, update, -1)
Well it's true that the transition.to is really useful and easy to use, but if you want to use physics, then use the applyLinearImpulse(), which is going to be easier if you want to use also collision detection. And once the rectangle is off screen, use the if and then function. It would be something like this:
if object.x > 500 then -- for example with a rectangle of 20 by 20
object.x = -20
end
To extend what #Fannick said, which should work by the way, the generic way to trigger this (for any object of any size) would be the code below. For this, I assume you have object.anchorX = 0 or object:setReferencePoint(display.CenterLeftReferencePoint) depending on your SDK version (the former is for v2 and the latter is for v1 - This link should help clear up differences)
--if the object is past the edge (screenOriginX used to scale for bigger devices)
if object.x > (display.contentWidth - display.screenOriginX) then
object.x = 0 + display.screenOriginX - object.contentWidth
end
If you have object.anchorX = 0.5 or object:setReferencePoint(display.CenterReferencePoint) (or haven't set either - both of these are the defaults) it would be:
if object.x > (display.contentWidth + (object.contentWidth/2) - display.screenOriginX) then
object.x = 0 + display.screenOriginX - (object.contentWidth/2)
end
For object.anchorX = 1 or object:setReferencePoint(display.CenterRightReferencePoint) it would be:
if object.x > (display.contentWidth + object.contentWidth - display.screenOriginX) then
object.x = 0 + display.screenOriginX
end
Hope you find the answer if you haven't already!
Cush
thanks both of you guy;
I've used the velocity to make the rectangle start to move and a collision to make 'em disappear
All your answers help me to understand better corona SDK !

Get updated location of object.x and object.y with Physics Engine

Hi I'm new to Corona SDK. I hope someone can help me out.
I have an object (called furry) dropping from the sky, using the physics engine of the Corona SDK.
When this object Furry is half way the screen I would like to play a sound effect (wee.mp3).
I'm trying to update furry.x and furry.y to control for the updated location. But I'm not sure how to do this as the physics engine updates the location based on gravity.
I hope the code below is sufficient to help me.
centerX = display.contentWidth * .5
centerY = display.contentHeight * .5
local furry = display.newImage("flurry.png")
furry.x = centerX-300
furry.y = centerY-1000
physics.addBody(furry, "dynamic", physicsData:get("flurry"))
if furry.x == centerX then
audio.play(wee)
end
So how can I get after the game has started the updated locations (x, y) of my object Furry?
you can use Runtime Listener enterFrame to detect the object location see the code below
physics = require("physics")
physics.start()
centerX = display.contentWidth * .5
centerY = display.contentHeight * .5
local function listener( event )
local furry = display.newCircle(10,10,10)
furry.x = math.random(1, display.contentWidth)
furry.y = 10
physics.addBody(furry, "dynamic")
local function removeObject()
if furry.y > centerY then
furry:removeSelf()
Runtime:removeEventListener("enterFrame", removeObject)
end
end
Runtime:addEventListener("enterFrame", removeObject)
end
timer.performWithDelay( 500, listener ,0)

How to fire a bullet in the direction of finger swipe in corona sdk

I am working on a game in corona. I want to fire a bullet when a user swipes their finger on an object. The further he swipes, the further the the bullet should go. I worked on this and on tap event the bullet is fired, there are two functions start projectile and game loop, start projectile is used to fire projectile and game loop is used to translate the weapon, but I can't understand how to aim for the target using finger swipe. Please give me any suggestions, thanks...
Code for what has been achieved so far is below
local function startprojectile(event)
gameIsActive=true
local firetimer
local getobj=event.target
local getxloc=getobj.x
local getyloc=getobj.y
local function firenow()
if gameIsActive=false then
timer.cancel(firetimer)
firetimer=nil
else
local bullet=display.newImageRect("object.png",50,60);
bullet.x=getxloc-50; bullet.y=getyloc-50
bullet.type=bullet1
physics.addBody(bullet,{isSensor=true})
weaponGroup:insert(bullet)
end
gameIsActive=false
end
firetimer.timer.performWithDelay(650,firenow)
end
local function gameloop()
local i
for i=weaponGroup.numChildren,1,-1 do
local weapon=weaponGroup[i]
if weapon ~=nil and weapon.x ~=nil
then
weapon:translate(-20,0)
end
end
You can get the angle that the bullet should be fired by using the built in lua function
startX, startY = player.x, player.y
dir = math.atan2(( swipeY - player.y ), ( swipeX - player.x ))
bulletDx = bullet.speed * math.cos(dir)
bulletDy = bullet.speed * math.sin(dir)
table.insert( bullet, { x = startX, y = startY, dx = bulletDx, dy = bulletDy } )
You can change the variable from swipe Y to whatever Corona uses (I don't code with it).
I'm assuming you know how to move the bullet, but if not,
for i, v in ipairs( bullet ) do
bullet.x = bullet.x + bullet.dx * dt
bullet.y = bullet.y + bullet.dy * dt
end

Make an object rotate to angle of tilt with accelerometer in CoronaSDK?

with my first game I have a doodle I control with the accelerometer. In many games I've seen that when the device is titled the object (in my case a doodle fish) rotate towards the tilt so it gives an illusion the "fish" swim down and if the device is tilted up and down the "fish" swims up and down.
How do I write that in lua when working with Corona SDK?
Here is my code for moving the doodle so far;
display.setStatusBar(display.HiddenStatusBar)
system.setAccelerometerInterval( 50 )
_W = display.contentWidth
_H = display.contentHeight
local bg = display.newImageRect("images/bg.png", 480, 320)
bg:setReferencePoint(display.CenterReferencePoint)
bg.x = _W/2
bg.y = _H/2
local player = display.newImageRect("images/doodle.png", 128, 64)
player:setReferencePoint(display.CenterReferencePoint)
player.x = _W/2
player.y = _H/2
-- Set up the Accelerometer values in Landscape
local motionX = 0
local motionY = 0
local function onAccelerate( event )
motionX = 10 * event.yGravity;
motionY = 10 * event.xGravity;
end
Runtime:addEventListener ("accelerometer", onAccelerate);
-- Make the player move on tilt.
local function movePlayer (event)
player.x = player.x + motionX;
player.y = player.y + motionY;
end
Runtime:addEventListener("enterFrame", movePlayer)
local function screenBoundaries (event)
-- Left side boundaries
if player.x < 0 + player.width/2 then
player.x = 0 + player.width/2
end
-- Right side boundaries
if player.x > display.contentWidth - player.width/2 then
player.x = display.contentWidth - player.width/2
end
-- Upper boundaries
if player.y < 0 + player.height/2 then
player.y = 0 + player.height/2
end
-- Lower boundaries
if player.y > display.contentHeight - player.height/2 then
player.y = display.contentHeight - player.height/2
end
end
Runtime:addEventListener("enterFrame", screenBoundaries)
EDIT;
I've tried to make the player rotate to tilt but it's not working, it doesn't return any errors when I run it in the simulator, what am I doing wrong?
Basically what I want to do is when the accelerometer y value increase/decrease the player(fish) swim up and down but I only want it to tilt moderately (0 to +/- 45 degrees) or what ever seems realistic. Perhaps 25 -35 degrees is optimal?
My math is not up to date so I apologize for that, can someone please help me with this?
display.setStatusBar(display.HiddenStatusBar)
system.setAccelerometerInterval( 50 )
_W = display.contentWidth
_H = display.contentHeight
local ceil = math.ceil
local pi = math.pi
local atan2 = math.atan2
local playerRotation
-- Put the doodle fish in the center if the screen.
local player = display.newImageRect("images/doodle.png", 128, 64)
player:setReferencePoint(display.CenterReferencePoint)
player.x = _W/2
player.y = _H/2
-- My rotation function, not sure how to do it right.
local function getPlayerRotationAngle(xGravity, yGravity)
angle = math.atan2(xGravity, yGravity)
angle = angle*(180/pi)
playerRotate = ceil(360 - angle(xGravity, yGravity))
return playerRotate
end
-- Set up the Accelerometer values in Landscape
local motionX = 0
local motionY = 0
local function onAccelerate( event )
motionX = 5 * event.yGravity;
motionY = 5 * event.xGravity;
-- Should I put the rotation here or down in the movePlayer function?
player.rotation = playerRotate(event.yGravity, event.xGravity);
end
Runtime:addEventListener ("accelerometer", onAccelerate);
-- Make the player move on tilt.
function movePlayer (event)
player.x = player.x + motionX
player.y = player.y + motionY
end
Runtime:addEventListener("enterFrame", movePlayer)
Your overall code looks good.
Several games I did use something similar.
What jumps out is you mentioning
I've tried to make the player rotate to tilt but it's not working, it doesn't return any errors when I run it in the simulator, what am I doing wrong?
Are you actually running the code on a device?
The Corona SDK simulator does not support simulation for the accelerometer so the event will never fire.
If you are running on the device, include the Crawl Space Library.
This will allow you to print() any form of data including tables.
Then add
print(event)
to your onAccelerate() function, hook your device up to your development machine and watch the console for the data you actually receive. (Assuming you're developing for iOS using a Mac, use iPhone Configuration Utility to get the data). Then debug from there.
Include
io.output():setvbuf("no")
at the beginning of your main.lua to disable console output caching on the device first. Otherwise the console output of your device will be buffered and hard to debug.

Resources