How to use applyLinearImpulse based on rotation in Corona / Lua

I use the Corona Gaming Addition SDK to create an iphone / andorid game. I have a spaceship on my screen, and I will allow the user to rotate the ship 360 degrees. Then I would like to call the applyLinearImpulse method so that the user can stick the ship forward in the direction the ship is in.

The method takes these arguments, which apply to ships X and Y to move the ship to a new destination. The trick is to determine which new X and Y should be based on the rotation / direction that the ship is pointing.

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

Has anyone done this or suggested a math suggestion that could understand this?

thanks -m

+3
source share
2 answers

Ok ... about 5 minutes after I posted it, 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
source

There are a few things you can improve on your code.

The first is a way to calculate the angle. Instead

ship.rotation*(math.pi/180)

You can do it:

local inverseRotation = ship.rotation + math.pi

Addition is faster than division and multiplication. In addition, storing it on a variable allows you not to calculate 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)

Hello!

+1
source

Source: https://habr.com/ru/post/1771121/


All Articles