2013-11-15 92 views
0

我正在嘗試模擬太陽周圍行星旋轉的應用程序。 我希望當應用程序啓動時,行星停止。當我第一次按太陽時,行星開始旋轉,當我第二次按時,行星停止。 我也希望如果我做一個向上滑動,行星開始旋轉得更快,當我做一個向下滑動時,行星減速。Corona SDK - 點擊並觸摸單個對象上的事件,對象旋轉

這裏是我做了什麼:

-- Sun 
local sun = display.newImage ("Sole.png") 
sun.x = display.contentCenterX 
sun.y = display.contentCenterY 

-- First Planet 
local group1 = display.newGroup() 
p1 = display.newImage("P1(2).png") 
group1:insert(p1) 
group1.x = sole.x 
group1.y = sole.y 
p1.x = 270 
p1.y = 0 

-- Second Planet 

local group2 = display.newGroup() 
p2 = display.newImage("P2.png") 
group2:insert(p2) 
group2.x = sole.x 
group2.y = sole.y 
p2.x = -270 
p2.y = 0 

local function increaseSpeed(event) 

    group1.rotation = group1.rotation + 1 
    group2.rotation = group2.rotation + 1 

end 

local function decreaseSpeed(event) 

    group1.rotation = group1.rotation - 1 
    group2.rotation = group2.rotation - 1 

end 

-- * State 1: The planets begins to rotate 

function state1(event) 
    print("state1") 
    sun.enterFrame = increaseSpeed 
    Runtime:addEventListener("enterFrame", sun) 
    sun:removeEventListener("tap", state1)    
    timer.performWithDelay(1, addListener2)     
    sun:addEventListener("touch", swipe) 
    return true 
end 

-- * State 2: The planets stops 

function state2(event) 
    print("state2") 
    sole:removeEventListener("touch", swipe) 
    Runtime:addEventListener("enterFrame")        
    sun:removeEventListener("tap", state2)    
    timer.performWithDelay(1, addListener1)     
    return true 
end 

function addListener2() 
    sun:addEventListener("tap", state2) 
end 

function addListener1() 
    sun:addEventListener("tap", state1) 
end 

-- Swipe function 

local beginX 
local beginY 
local endX 
local endY 

local xDistance 
local yDistance 

function checkSwipeDirection() 

    xDistance = math.abs(endX - beginX) 
    yDistance = math.abs(endY - beginY) 

    if xDistance > yDistance then 
      if beginX > endX then 
        print("swipe left") 
      else 
        print("swipe right") 
      end 
    else 
      if beginY > endY then 
        print("swipe up") 
        timer.performWithDelay(10, increaseSpeed ,0) 
      else 
        print("swipe down") 
        timer.performWithDelay(10, decreaseSpeed ,0) 
      end 
    end 

end 

function swipe(event) 
    if event.phase == "began" then 
      beginX = event.x 
      beginY = event.y 
    end 

    if event.phase == "ended" then 
      endX = event.x 
      endY = event.y 
      checkSwipeDirection(); 
    end 

    return true 
end 

我的問題是,如果我在狀態1,我做的向上掃掠和我按太陽,我在狀態2,但行星繼續即使我刪除了Event Runtime,enterFrame,也要進行旋轉。

有人可以幫我嗎? 謝謝:)

回答

1

我可以在狀態2看到你寫的:

Runtime:addEventListener("enterFrame") 

你應該寫:

Runtime:removeEventListener("enterFrame", sun) 
+0

謝謝的回答!我試着寫下你寫的代碼,現在如果我只做一次滑動,一切都好(行星停止),但如果我做了兩次滑動,行星並沒有停止。無論如何,現在它效果更好! – Luca93

+0

sole:removeEventListener(「touch」,滑動) 什麼是state2中的「sole」?也許你不應該刪除「唯一」的滑動,或者你必須在行星移動時再次添加事件監聽器。 –