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

淺唱寂寞╮ 提交于 2019-12-21 20:23:37

问题


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 ship 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


回答1:


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



回答2:


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!



来源:https://stackoverflow.com/questions/4006550/how-do-i-use-applylinearimpulse-based-on-rotation-in-corona-lua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!