沿其旋转方向移动对象
Move object in the direction of it's rotation
我有一个不断旋转的物体,它会发射子弹。我想让子弹按照它们的方向向前移动。
physics.setGravity( 0, 0 )
fireBullets = function ( )
local bullet = display.newRect( sceneGroup,0,0, 40, 40 )
bullet:setFillColor( 0, 1, 0 )
local h = player.height
local posX = h * math.sin( math.rad( player.rotation ))
local posY = h * math.cos( math.rad(player.rotation ))
bullet.x = player.x + posX
bullet.y = player.y - posY
bullet.rotation = player.rotation
到目前为止一切顺利,子弹随着玩家的精确旋转出现。
local angle = math.rad( bullet.rotation )
local xDir = math.cos( angle )
local yDir = math.sin( angle )
physics.addBody( bullet, "dynamic" )
bullet:setLinearVelocity( xDir * 100, yDir * 100)
end
他们并没有按照他们的方向前进,他们似乎在向他们的右边移动。我的计算有什么问题?
您可以将 sin/cos 翻转为 x/y 并在 y 上使用 -velocity。
这是一个有用的重构:
local function getLinearVelocity(rotation, velocity)
local angle = math.rad(rotation)
return {
xVelocity = math.sin(angle) * velocity,
yVelocity = math.cos(angle) * -velocity
}
end
...您可以替换:
local angle = math.rad( bullet.rotation )
local xDir = math.cos( angle )
local yDir = math.sin( angle )
physics.addBody( bullet, "dynamic" )
bullet:setLinearVelocity( xDir * 100, yDir * 100)
与:
physics.addBody( bullet, "dynamic" )
local bulletLinearVelocity = getLinearVelocity(bullet.rotation, 100)
bullet:setLinearVelocity(bulletLinearVelocity.xVelocity, bulletLinearVelocity.yVelocity)
我有一个不断旋转的物体,它会发射子弹。我想让子弹按照它们的方向向前移动。
physics.setGravity( 0, 0 )
fireBullets = function ( )
local bullet = display.newRect( sceneGroup,0,0, 40, 40 )
bullet:setFillColor( 0, 1, 0 )
local h = player.height
local posX = h * math.sin( math.rad( player.rotation ))
local posY = h * math.cos( math.rad(player.rotation ))
bullet.x = player.x + posX
bullet.y = player.y - posY
bullet.rotation = player.rotation
到目前为止一切顺利,子弹随着玩家的精确旋转出现。
local angle = math.rad( bullet.rotation )
local xDir = math.cos( angle )
local yDir = math.sin( angle )
physics.addBody( bullet, "dynamic" )
bullet:setLinearVelocity( xDir * 100, yDir * 100)
end
他们并没有按照他们的方向前进,他们似乎在向他们的右边移动。我的计算有什么问题?
您可以将 sin/cos 翻转为 x/y 并在 y 上使用 -velocity。
这是一个有用的重构:
local function getLinearVelocity(rotation, velocity)
local angle = math.rad(rotation)
return {
xVelocity = math.sin(angle) * velocity,
yVelocity = math.cos(angle) * -velocity
}
end
...您可以替换:
local angle = math.rad( bullet.rotation )
local xDir = math.cos( angle )
local yDir = math.sin( angle )
physics.addBody( bullet, "dynamic" )
bullet:setLinearVelocity( xDir * 100, yDir * 100)
与:
physics.addBody( bullet, "dynamic" )
local bulletLinearVelocity = getLinearVelocity(bullet.rotation, 100)
bullet:setLinearVelocity(bulletLinearVelocity.xVelocity, bulletLinearVelocity.yVelocity)