如何在Corona SDK中固定距离移动物体

我想在 x 轴上将对象移动固定距离。比如说我有一个对象精灵,已经放置在场景中。我的需求是将对象从 X 移动到一些 -X ,再从 -X 移动到 X。

function scrollBackgroundImages(self, event)
    if self.x < -477 then
        self.x = 480
    else
        self.x = self.x - self.speed
    end
end

backgroundImage1 = display.newImage("goldfish-background-01.png", 768, 1024)
backgroundImage1:setReferencePoint(display.BottomLeftReferencePoint)
backgroundImage1.x = 0
backgroundImage1.y = 320
backgroundImage1.speed = 1
screenGroup:insert(backgroundImage1)

carbSpritesheetData = { width=216, height=167, numFrames=3, sheetContentWidth=650, sheetContentHeight=167 }
mycrabSheet = graphics.newImageSheet( "crab-sprite.png", carbSpritesheetData )
crabSequenceData = {
    { name = "normalRun", start=1, count=3, time=800 }
}
crabMoving = display.newSprite( mycrabSheet, crabSequenceData )
crabMoving:play()
crabMoving:scale(0.3, 0.3)
crabMoving.x =_W/2
crabMoving.y = _H-55
crabMoving.speed = 1
physics.addBody(crabMoving, "static", {density = 0.1, bounce = 0.1, friction = 0.2, radius = 12})
screenGroup:insert(crabMoving)

crabMoving.enterFrame = scrollBackgroundImages
Runtime:addEventListener("enterFrame",crabMoving )
点赞
用户1979583
用户1979583
-- 创建背景
local backgroundImage1 = display.newImage("goldfish-background-01.png", 768, 1024)
backgroundImage1:setReferencePoint(display.BottomLeftReferencePoint)
backgroundImage1.x = 0
backgroundImage1.y = 320
screenGroup:insert(backgroundImage1)

-- 创建精灵
carbSpritesheetData = { width=216, height=167, numFrames=3, sheetContentWidth=650, sheetContentHeight=167 }
mycrabSheet = graphics.newImageSheet( "crab-sprite.png", carbSpritesheetData )
crabSequenceData = {
                    {name = "normalRun", start=1, count=3, time=800}
                   }
crabMoving = display.newSprite( mycrabSheet, crabSequenceData )
crabMoving:play()
crabMoving:scale(0.3, 0.3)
crabMoving.x =_W/2
crabMoving.y = _H-55
screenGroup:insert(crabMoving)

local speed = 1 -- 变量用于控制背景/精灵运动的速度

-- 创建一个函数来移动背景和精灵
local function scrollBackgroundImages()
   crabMoving.x = crabMoving.x-speed
   backgroundImage1.x = backgroundImage1.x - speed
   if(backgroundImage1.x< -477)then
       backgroundImage1.x = 480
       crabMoving.x = 480+_W/2
   end
end

Runtime:addEventListener("enterFrame",scrollBackgroundImages)
2013-05-24 06:46:17
用户1870706
用户1870706

有三种移动物体的方式:

  1. 物理方式,使用不同的方法添加力或冲量。
  2. 使用 transition.to() API 调用。http://docs.coronalabs.com/api/library/transition/to.html
  3. 使用 Runtime:addEventListener("enterFrame", moveMyObject) 函数移动物体,其中你需要提供"moveMyObject",然后它会逐步地移动你的物体一点点。
2013-05-27 01:05:00