3

我刚刚开始使用一个基本的 Corona SDK 项目,但遇到了一些障碍。我已经很好地制作了对象和菜单,甚至为游戏添加了重力,但我想知道是否有一种简单的方法可以在用户滑动屏幕时让对象移动,并且对象会朝那个大致方向移动。

任何帮助将不胜感激,我的对象的代码在下面

    -- 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)
4

1 回答 1

3

如果要实现具有线速度的可拖动对象,可以参考以下代码,只需复制代码并创建新项目

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)

希望这可以帮助

于 2013-07-11T00:50:11.550 回答