如何在电晕sdk的运动方向上改变碰撞后子弹的方向(角度)

时间:2013-08-21 17:05:03

标签: lua corona

我想在碰撞后改变子弹角度,它应该改变碰撞后它移动的方向,并且必须在碰撞后停止旋转....请给出任何建议......谢谢

示例代码写在下面

local physics = require("physics")
physics.start()

local obj

physics.setScale( 60 ) 
physics.setGravity( 0, 0 ) 

display.setStatusBar( display.HiddenStatusBar )
local obstacle = display.newCircle( 250, 250, 60 )
obstacle.x = display.contentWidth/2; obstacle.y = 200
physics.addBody( obstacle, { density=150, friction=0.2, bounce=0} )
obstacle.isBullet=true


obj = display.newRect(0, 0,20,40)
obj.x = display.contentWidth/2; obj.y = 780
obj.isBullet = true 
obj.color = "white"
physics.addBody( obj, { density=1, friction=0.4, bounce=0.1} )

local target = display.newCircle( 250, 250, 60 )
target.x = obj.x; target.y = obj.y; target.alpha = 0


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

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

        t:setLinearVelocity( 0, 0 )
        t.angularVelocity = 0

        target.x = t.x
        target.y = t.y

        startRotation = function()
            target.rotation = target.rotation + 4
        end

        Runtime:addEventListener( "enterFrame", startRotation )

        local showTarget = transition.to( target, { alpha=0.4, xScale=0.4, yScale=0.4, time=200 } )
        myLine = nil

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

    if ( myLine ) then
                myLine.parent:remove( myLine ) -- erase previous line, if any
            end
            myLine = display.newLine( t.x,t.y, event.x,event.y )
            myLine:setColor( 255, 255, 255, 50 )
            myLine.width = 8

        elseif "ended" == phase or "cancelled" == phase then

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

            local stopRotation = function()
                Runtime:removeEventListener( "enterFrame", startRotation )
            end

            local hideTarget = transition.to( target, { alpha=0, xScale=1.0, yScale=1.0, time=200, onComplete=stopRotation } )

            if ( myLine ) then
                myLine.parent:remove( myLine )
            end

            t:applyForce( (t.x - event.x), (t.y - event.y), t.x, t.y )

        end
    end

return true
end

obj:addEventListener( "touch", Shot)   

1 个答案:

答案 0 :(得分:1)

local physics = require "physics"
physics.start()

local rect1 = display.newRect(480,0,10,320)
physics.addBody(rect1, "static")

local rect2 = display.newRect(20,100,20,20)

local function shot()
    physics.addBody(rect2, "dynamic")
    rect2:applyForce( 1000, 0, rect2.x, rect2.y )
    rect2.myName = "rect2"
end
rect2:addEventListener("touch", shot)