Search code examples
game-physicscoronasdk

Attempting to have an object move in the direction user swipes the screen: Corona SDK


I've just started with a basic Corona SDK project, and I have hit a bit of a roadblock. I have made objects and menus fine, and even added gravity to the game, but I was wondering if there was a simple method to have an object move when the user swiped the screen, and the object would move in that general direction.

Any help would be much appreciated, the code for my object is down below

    -- make a Chameleon 
local Chameleon = display.newImageRect( "Chameleon.png", 70, 70 )
Chameleon.x= 50
Chameleon.y= 440
    physics.addBody(Chameleon, "dynamic", {density=.1, bounce=.1, friction=.2, radius=12})

function touchScreen(event)
  -- print("touch")
end

Runtime:addEventListener("touch", touchScreen)

Solution

  • you can refer to the below code if you want to achieve draggable object with linear velocity just copy the code and make new project

    local physics = require( "physics" )
    physics.start()
    
    local Rect = display.newRect(30,30,30,30)
    Rect:setFillColor(255,0,0)
    
    local flooring = display.newRect(0,display.contentHeight/1.1, display.contentWidth, 10)
        physics.addBody(Rect,"dynamic")
        physics.addBody(flooring,"static")
    
        local activateDash = false
        local bx = 0
        local by = 0
    
        heroTouch = function(event)
            if Rect then
                if event.phase == "began" then
                    bx = event.x
                    by = event.y
                elseif event.phase == "moved" then
                    activateDash = true
                elseif event.phase == "ended" then
                    if activateDash then
                        if _G.gX == 0 and _G.gY ~= 0 then
                            Rect:setLinearVelocity(event.x-bx,0)
                        elseif _G.gX ~= 0 and _G.gY == 0 then
                            Rect:setLinearVelocity(0,event.y-by)
                        else
                            Rect:setLinearVelocity(event.x-bx,event.y-by)
                        end
                        activateDash = false
                    end
                end
            end
        end
    Runtime:addEventListener("touch",heroTouch)
    

    hope this can help