如何使用transition.to函数开火子弹,并在开火时改变子弹角度和方向在corona sdk中。

我想使用transition.to函数射出子弹,我能够在对象的tap事件上生成子弹,但是我如何在旋转对象时改变子弹发射的方向,以及在发射方向上改变角度... 生成子弹的代码如下...

请给我一些想法如何实现这个功能.... 谢谢

点赞
用户185316
用户185316

一个简单的解决方案是,在与你的枪具有相同角度的位置计算一个距离(你的子弹射程)的点的 x、y 坐标。

display.setStatusBar( display.HiddenStatusBar )

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

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

        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)
            rotationAmt = angle1 - angle2
            t.rotation = t.rotation - rotationAmt

            t.x1 = t.x2
            t.y1 = t.y2
        elseif (phase == "ended") then
            display.getCurrentStage():setFocus( nil )
            t.isFocus = false
        end
    end

    return true
end

-- 提前声明 `gun` 所以 `shootfunc` 函数可以"看到"它
local gun

--[[
计算距离为 `distance` 的一条线上的点 `angle` 度的 x、y 坐标。
]]--
local function pointAtDistance(angle, distance)
    -- 将角度转换为弧度,因为 Lua 的数学函数需要弧度作为参数
    local r = math.rad(angle)
    local x = math.cos(r) * distance
    local y = math.sin(r) * distance

    return x, y
end

local function shootfunc(event)
    local laser = display.newRect(0, 0,10, 35)
    laser:setFillColor(240, 0, 0)

    -- 激光应该从枪管中射出,所以我们获取沿着枪管的一点
    -- 以用来发射激光
    local tipX, tipY = pointAtDistance(gun.rotation - 90, (gun.height / 2) + (laser.height / 2))
    laser.x = gun.x + tipX
    laser.y = gun.y + tipY

    -- 枪弹发射的距离(任何地方离屏幕都足够)
    local distance = 1000

    -- 使枪弹的角度与枪的角度匹配
    laser.rotation = gun.rotation

    -- 我们实际上想垂直于我们的角度射击
    local shootAngle = laser.rotation - 90

    -- 基于角度绘制 x、y 目标点以射出枪弹
    local x, y = pointAtDistance(shootAngle, distance)
    local targetX = laser.x + x
    local targetY = laser.y + y

    -- 使用过后移除枪弹
    local function destroy()
        laser:removeSelf()
    end

    transition.to(laser, {
        time = 800,
        -- 渐隐
        alpha = 0,
        x = targetX,
        y = targetY,
        -- 完成后移除
        onComplete = destroy
    })
end

-- 使用一个组来放置枪,可以在其中加入其他对象
gun = display.newGroup()
gun.x = display.contentCenterX
gun.y = display.contentCenterY

-- 枪的形状
local gunBody = display.newRect(-20, -50, 40, 100)
gunBody:setFillColor(240, 200, 0)
gun:insert(gunBody)

-- 瞄准器,可以告诉我们枪的指向
local site = display.newRect(-5, -55, 10, 20)
site:setFillColor(100, 200, 50)
gun:insert(site)

gun:addEventListener("touch", rotateObj)
gun:addEventListener("tap", shootfunc)
2013-09-02 12:14:34