How to apply force depends on z rotation of object

Hi friends
I use 2D physics, imagin i have an spaceship object which it’s head is toward right direction ( z angle = 0 degree )
I have this code to move my object forward ( to right side ):

if action_id == hash("up") then
    msg.post('.', "apply_force", {force = vmath.vector3(50, 0, 0), position = go.get_world_position()})
end

it’s ok while it’s not rotating, after it rotates i need to get new z angle and change direction of force towards its head ( to push it forward not to right )
how should i change my force vector?

  • how you write lua codes in forum that it looks beautiful not like normal texts, is there any tag for it? ( instead of copy and paste directly )! ( answered )

Some knowledge of trigonometry and vector math is necessary for making games, though Defold comes with a lot of helper functions in the vmath module. You can use vmath.rotate to rotate your force vector to match the ship’s rotation.

local rot = go.get_rotation()
local force = vmath.vector3(50, 0, 0)
force = vmath.rotate(rot, force)

Note that it takes a quaternion rotation, not just an angle.


On the forum, you can format blocks of code between three backticks: ``` or inline code like this between single backticks.

``` -- opens the code block
code here
-- end with another: ```
6 Likes