Вращение объекта вокруг точки или другого объекта с помощью сенсорной короны SDK

Я пытаюсь заставить несколько ящиков вращаться как колесо обозрения на основе сенсорного ввода

так что представьте колесо обозрения на экране, и перетаскивание одной из тележек будет вращать колесо в одну сторону, а перетаскивание вверх будет вращать колесо в другую сторону

каждая коробка или "тележка" на колесе обозрения не вращается, они будут двигаться только круговыми движениями, точно так же, как колесо обозрения

у меня в значительной степени это работает сейчас, однако мои ящики отрываются от начальной точки захвата, поэтому, когда я касаюсь одного из ящиков, он быстро появляется в другом месте, но затем поворачивается как обычно, я хочу, чтобы он продолжал плавно вращаться от начальной точки захвата

вот мой текущий код ниже

local squares = display.newGroup()

local square = display.newRect(0,0,200,200)
square.x, square.y = 320, 320
square:setFillColor(100,255,55)
squares:insert(square)

local square2 = display.newRect(0,0,200,200)
square2.x, square2.y = 320, 320
square2:setFillColor(999,255,55)
squares:insert(square2)

local function onTouch( event )
local t = event.target

local phase = event.phase
if "began" == phase then

    local parent = t.parent
    parent:insert( t )
    display.getCurrentStage():setFocus( t )
    t.isFocus = true

    -- Store initial position
    t.x0 = event.x - t.x
    t.y0 = event.y - t.y

elseif t.isFocus then
    if "moved" == phase then

   local degrees = event.y

        local rads = degrees * (math.pi / 360.0)
            square.x = 300 * math.cos(rads) + 500
            square.y = 300 * math.sin(rads)+ 500
            degrees = degrees + 100
           print (square.x, square.y)

         local rads2 = degrees * (math.pi / 360.0)
            square2.x = 300 * math.cos(rads2)+ 500
            square2.y = 300 * math.sin(rads2)+ 500
            degrees = degrees - 100

           print (square.x, square.y)




    elseif "ended" == phase or "cancelled" == phase then
        display.getCurrentStage():setFocus( nil )
        t.isFocus = false
    end
end
return true
end


squares:addEventListener( "touch", onTouch )

пожалуйста, не стесняйтесь указывать на любые глупые ошибки, которые я сделал, а также, если бы вы могли показать мне, как получить такой же эффект, но вокруг другого объекта, а не точки, я был бы очень благодарен, спасибо

2 ответа

Решение

Это полный рабочий пример.

local squares = display.newGroup()

local wheelX =  display.contentCenterX
local wheelY =  display.contentCenterY

local radius = 220
local degrees = -180
local squareH = 150

local square = display.newRect(0,0,squareH,squareH)
square:setFillColor(255,255,255)
square.degStart = 100
squares:insert(square)

local square2 = display.newRect(0,0,squareH,squareH)
square2:setFillColor(999,255,55)
square2.degStart = -10
squares:insert(square2)


local function drawRects(degrees)
    local rads = (square.degStart + degrees) * (math.pi / 180.0)
    square.x = radius * math.cos(rads) + wheelX
    square.y = radius * math.sin(rads) + wheelY

    local rads2 = (square2.degStart + degrees) * (math.pi / 180.0)
    square2.x = radius * math.cos(rads2) + wheelX
    square2.y = radius * math.sin(rads2) + wheelY
end

local function getDegrees(square)
    local x = square.x
    local y = square.y

    local degrees = math.atan2((y - wheelY) , (x - wheelX)) * (180 / math.pi)

    return degrees
end


local function onTouch( event )
    local t = event.target

    local phase = event.phase
    local parent = t.parent

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

        square.degStart = getDegrees(square)
        square2.degStart = getDegrees(square2)
    elseif t.isFocus then
        if "moved" == phase then
            degrees = math.atan2((event.yStart - wheelY) , (event.xStart - wheelX)) * (180 / math.pi)

            degrees2 = math.atan2((event.y - wheelY) , (event.x - wheelX)) * (180 / math.pi)

            diffDegrees = degrees2 - degrees
            drawRects(diffDegrees)

            print("diffDegrees: " .. diffDegrees)
        elseif "ended" == phase or "cancelled" == phase then
            display.getCurrentStage():setFocus( nil )
            t.isFocus = false
        end
    end
return true
end

squares:addEventListener( "touch", onTouch )

drawRects(degrees)

Это заняло у меня много времени.

Вы должны попытаться получить event.y и event.x, а затем получить градусы по формуле:

degrees = Math.atan(event.y / event.x)
Другие вопросы по тегам