Corona SDK - Make a ball bounce based on touch - lua

So I am trying to make a ball fall and when it is touched, I need it to bounce in the direction the ball is touched. Right now all I have it doing is going straight up, but if I were to tap on the edge of the ball, it needs to start heading in that direction but also up.
The game is a soccer keep ups game, you tap and the ball goes up, if it hits the ground, the score resets. Simple. But I cannot seem to find any examples on how to have the ball roll side to side as well as upwards.
local ball = display.newImageRect("soccerball.png", 112, 112)
ball.x = display.contentCenterX
ball.y = display.contentCenterY
physics.addBody(ball, "dynamic", {radius=50, bounce=0.3})
local function pushBall(event)
ball:applyLinearImpulse(0, -0.75, ball.x, ball.y)
tapCount = tapCount + 1
tapText.text = tapCount
end
ball:addEventListener("touch", pushBall)
Code above only allows the ball to go straight up. No roll.
Thank you for your help.

Try
function ball:touch( event )
local phase = event.phase
if ( phase == 'ended' ) then
local x, y = ball.x - event.x, ball.y - event.y
self:applyLinearImpulse( x / 30, -math.abs(y) / 30, self.x, self.y )
--tapCount = tapCount + 1
--tapText.text = tapCount
end
return true
end
ball:addEventListener("touch")

Related

corona and appwarp moving hero in multiplayer

I am trying to move my hero in a multiplayer setup to the left and right.
I have to squares to initiate move left and move right for a regular crircle on a ground.
I am using AppWarp to initate the multiplayer instance and that is working fine, however I am having trouble on how to communicate the moving of the circle.
Here is my lua:
-- When left arrow is touched, move character left
function left:touch()
motionx = -speed;
end
left:addEventListener("touch",left)
-- When right arrow is touched, move character right
function right:touch()
motionx = speed;
end
right:addEventListener("touch",right)
-- Move character
local function movePlayer (event)
appWarpClient.sendUpdatePeers(tostring(player.x))
end
Runtime:addEventListener("enterFrame", movePlayer)
-- Stop character movement when no arrow is pushed
local function stop (event)
if event.phase =="ended" then
motionx = 0;
end
The keyline here is
appWarpClient.sendUpdatePeers(tostring(player.x))
with this I send the current X position of my hero (the circle) and in my warplisteners I pick it up like so:
function onUpdatePeersReceived(update)
local func = string.gmatch(update, "%S+")
-- extract the sent values which are space delimited
--local id = tostring(func())
local x = func()
statusText.text = x
player.x = x + motionx
end
When I start the game on 2 clients I can start moving the ball but it is wobbeling back and forth between 62 units, wich i guess is my speed
speed = 6; -- Set Walking Speed
if I change this:
function onUpdatePeersReceived(update)
local func = string.gmatch(update, "%S+")
-- extract the sent values which are space delimited
--local id = tostring(func())
local x = func()
statusText.text = x
player.x = x + motionx
end
to this:
function onUpdatePeersReceived(update)
local func = string.gmatch(update, "%S+")
-- extract the sent values which are space delimited
--local id = tostring(func())
local x = func()
statusText.text = x
player.x = player.x + motionx
end
(last line before "end")
player.x = player.x + motionx
instead of
player.x = x + motionx
The coordinates gets updated but the hero only moves on one of the screens.
Any idea how to implement a better movement system that moves my hero on both clients at the same time?
Kind regards
edit:
Added if-else, it was pending between +-speed and 0 since the speed is 0 when hero is stopped.
if(motionx ~= "0") then
player.x = player.x + motionx
statusText.text = "motionx ~= 0"
elseif(motionx == "0") then
player.x = player.x
else
statusText.text ="Something went horribly wrong"
end

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

Lua Breakout Game Tutorial : Weird behavior of ball

I followed this tutorial to make a breakout game, but at some point, the ball keeps leaning on the top wall when the ball angle is too large ( too horizontal ). Is there any logic I can tune so that the ball can avoid this behavior?
Here is the screenshot :
The ball's related source code is:
local ballRadius = 10
ball = display.newCircle( display.contentWidth / 2, display.contentHeight / 2, ballRadius )
physics.addBody(ball, "dynamic", {friction=0, bounce = 1, radius=ballRadius})
It is some kind of weird. But I've done once like this...
Create 3 variables/flags:
local horizontalMotionFlag,yPos_1,yPos_2 = 0,0,0
Then:
wall.type = "LeftWall" -- to the LeftWall
-- and --
wall.type = "RightWall" -- to the RightWall
Add the following lines inside event.phase == "ended"
------------------------------------------------------------------------------------------
if(event.other.type == "LeftWall") then
yPos_1 = ball.y
if(horizontalMotionFlag==0)then
horizontalMotionFlag = 1
else
if(math.abs(yPos_1-yPos_2) < 50)then
print("CoHorizontal motion detected. Change angle...1")
horizontalMotionFlag = 0
ball:applyForce( 0, 1, ball.x, ball.y ) -- apply a small downward force
ball:applyForce( 0, 0, ball.x, ball.y ) -- resetting the force
-- You can also check the direction of ball and apply force to -1(upwards) also --
end
end
end
if(event.other.type == "RightWall") then
yPos_2 = ball.y
if(horizontalMotionFlag==0)then
horizontalMotionFlag = 1
else
if(math.abs(yPos_1-yPos_2) < 50)then
print("CoHorizontal motion detected. Change angle...")
horizontalMotionFlag = 0
ball:applyForce( 0, 1, ball.x, ball.y ) -- apply a small downward force
ball:applyForce( 0, 0, ball.x, ball.y ) -- resetting the force
-- You can also check the direction of ball and apply force to -1(upwards) also --
end
end
end
------------------------------------------------------------------------------------------
Then add the following line inside event.other.type == "destructible" and event.other.type == "bottomWall" :
horizontalMotionFlag = 0;
Keep Coding............. :)

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