2013-06-13 4 views
1

여기에 내 손가락으로 회전 할 수있는 게임이있는 대포가 있습니다. 팁이 항상 손가락의 반대 방향으로 향하도록하고 싶습니다. 즉 손가락을 왼쪽 하단으로 드래그하면 팁이 오른쪽 상단을 가리켜 야합니다.센터에 관련된 오브젝트를 회전하십시오.

나는 이것을 어떻게 작동시키는 지 알 수 없다. 나는 다음과 같은 코드를 사용하여 회전을 얻기 위해 관리했습니다 :

local function rotateObj(event) 
    local t = event.target 
    local phase = event.phase 

    if (phase == "began") then 
     display.getCurrentStage():setFocus(t) 
     t.isFocus = true 

     -- Store initial position of finger 
     t.x1 = event.x 
     t.y1 = event.y 

    elseif t.isFocus then 
     if (phase == "moved") then 
      t.x2 = event.x 
      t.y2 = event.y 

      angle1 = 180/math.pi * math.atan2(t.y1 - t.y , t.x1 - t.x) 
      angle2 = 180/math.pi * math.atan2(t.y2 - t.y , t.x2 - t.x) 
      print("angle1 = "..angle1) 
      rotationAmt = angle1 - angle2 

      --rotate it 
      t.rotation = t.rotation - rotationAmt 
      print ("t.rotation = "..t.rotation) 

      t.x1 = t.x2 
      t.y1 = t.y2 

     elseif (phase == "ended") then 

      display.getCurrentStage():setFocus(nil) 
      t.isFocus = false 
     end 
    end 

    -- Stop further propagation of touch event 
    return true 
end 
cannon:addEventListener("touch", rotateObj) 

이 내 대포를 회전 할 수 있도록 않지만, 내가 끌어있어 위치로 팁 관계를 유지 나던. 나는 여기서 어디로 가야할지 전혀 몰라.

답변

1

내 코드를 사용해 볼 수 있습니다.

나는 당신과 같은 게임을 만들었지 만 당신은 활과 화살을 컨트롤합니다.

function getAngle(x1,y1,x2,y2) 
    local PI = 3.14159265358 
    local deltaY = y2 - y1 
    local deltaX = x2 - x1 

    local angleInDegrees = (math.atan2(deltaY, deltaX) * 180/PI)*-1 

    local mult = 10^0 

    return math.floor(angleInDegrees * mult + 0.5)/mult 
end 

local arrow = display.newImage("wind_arrow.png") 
arrow.x = display.contentWidth/2 
arrow.y = display.contentHeight/2 
arrow.touch = function(self, event) 
    print(event.phase) 
    if event.phase == "moved" then 
     --If your image is originally pointing to the north use +90 
     --If your image is originally pointing to the east use +180 
     --If your image is originally pointing to the south use +270 
     --If your image is originally pointing to the west use +360 or +0 

     --My wind_arrow.png is point to the east so I use +180 
     --You can use this formula 
     arrow.rotation = (getAngle(arrow.x,arrow.y,event.x,event.y)+180)*-1 
    end 
end 
Runtime:addEventListener("touch",arrow) 
+0

고마워요! 이것은 내가 원했던 것과 똑같습니다. 이 코드는 원래 코드보다 훨씬 작을뿐만 아니라 사용하기도 쉽습니다. 감사합니다! – Cleverbird

+0

사실, 약간의 오류가 있음을 발견했습니다 ... 대포를 만질 때가 아니라 화면을 터치 할 때 대포가 움직입니다. 사용자가 대포에 닿은 경우에만 작동하도록 할 수있는 방법이 있습니까? – Cleverbird

+0

나는 처음에 나 자신을 먼저 파악해야하고, 그런 다음 질문을한다. 이것은 런타임 이벤트 리스너를 다음과 같이 변경하여 쉽게 해결할 수 있습니다. cannon : addEventListener ("touch", cannon) – Cleverbird

0

첫 번째 elseif 문구를보십시오. ELSEIF 문장은 하나 개의 경로를 입력 할 경우 때문에 상 == "시작"

if (phase == "began") then 
    t.isFocus = true 
elseif t.isFocus then 
    XXX 
end 

가 작동하지 않을 것입니다. if에서 t.isFocus를 true로 설정하지만 elseif 경로에서 즉시 판단되지 않습니다.

관련 문제