开发者

How do I use applyLinearImpulse based on rotation in Corona / Lua

I am using the Corona Gaming Addition SDK to build an iphone / andorid game. I have a space ship on the screen and I will allow the user to rotate the ship 360 degrees. I would like to then call the applyLinearImpulse method to allow the user to thrust the ship forward in the direction the ship is facing.

The method accepts these arguments witch are applied to the ships X and Y in order to move the ship to the new destination. The trick is to figure out what the new X and Y needs to be based on rotation / direction the shi开发者_运维百科p is pointing.

ship:applyLinearImpulse(newX, newY, player.x, player.y)

Anyone done this or have a suggestion on the math that would figure this out?

thanks -m


Ok .... about 5 min after I posted this I figured it out. Here is the answer

speedX = 0.5 * (math.sin(ship.rotation*(math.pi/180)))
speedY = -0.5 * (math.cos(ship.rotation*(math.pi/180)))

if(event.phase =="began") then
  ship:applyLinearImpulse(speedX, speedY, player.x, player.y)
end


There are several things that you can improve in your code.

The first one is the way you calculate the angle. Instead of

ship.rotation*(math.pi/180)

You could do this:

local inverseRotation = ship.rotation + math.pi

An addition is faster than a division and a multiplication. Also, storing it on a variable will save you from calculating it twice. Then you can do:

local inverseRotation = ship.rotation + math.pi
local speedX, speedY = 0.5 * math.sin(inverseRotation), -0.5 * math.cos(inverseRotation)

Regards!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜