how to add force locally of rigidbody2d in gdscript?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Ghost#1

I am making a rocket game that the rocket moves with the mouse position
and this rocket is rigidbody 2d i wanted the rocket to add force to move the rocket.
i tried this code :

func addforcelocal(force: Vector2, pos: Vector2):
    var pos_local = self.transform.basis_xform(pos)
    var force_local = self.transform.basis_xform(force)
    self.add_force(force_local, pos_local)

Thanks : )

:bust_in_silhouette: Reply From: l-e-webb

Can you clarify what you’re trying to do? How are force and pos determined, and what is the result you want?

Some potentially helpful notes:

  • You can use the to_local and to_global methods on any object which extends Node2D. That may be more reliable than messing with the transform itself.

  • There’s a get_local_mouse_position method you might find helpful.

  • Here’s the doc for the add_force method:

`void add_force(offset: Vector2, force: Vector2)`

"Adds a positioned force to the body. Both the force and the offset from the body origin are in global coordinates."

So it may be that you’re supplying the arguments in the wrong order.

  • If you just want to move the rocket, you could try applying the force centrally rather than at a specific position. That’s often better for simple objects. If you want to move the rocket towards the mouse position, for example, you could do something like this:
`var to_mouse = get_global_mouse_position() - global_position`
`to_mouse = to_mouse.normalized()`
 `add_central_force(to_mouse * force_strength)`

Where force_strength is some variable you’ve defined elsewhere in the script.