Search code examples
luacoronasdkgame-physics

Corona SDK - Make a ball bounce based on touch


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.


Solution

  • 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")