Search code examples
2dgodotcalculationmousemove

Godot 4. Calculate hand position for throw force


Video

Hi, does anyone know how could i calculate a throw force from my moving hands. In the video you can see what i mean. Right now when i let go of the box it just drops what im trying to achieve is a "throw". The box is a rigibody2d.

So this is how I move my hands.

func _integrate_forces(state):
var _transform = state.get_transform()
if idName == "Left":
    var mouse_position = get_global_mouse_position()
    var abovePlayer = Vector2(4,-8)
    var direction = (mouse_position - _player.global_position )
    var distance = direction.length()
    if distance > MAX_DISTANCE:
        direction = direction.normalized() * MAX_DISTANCE
    var hands_pos = _player.global_position + abovePlayer + direction
    _transform.origin = hands_pos
state.set_transform(_transform)

This is how the box is handled after picked up.

func _integrate_forces(state):
    angular_velocity = 0
    var _transform = state.get_transform()
    if(following):
        gravity_scale = 0;
        var middlePoint = get_middle_point(Game.bodyHandLeft.global_position,Game.bodyHandRight.global_position)
        _transform.origin = middlePoint
        call_deferred("lock_me")
    else:
        if(followTarget != null):
            followTarget = null;
        call_deferred("let_me_go")
    state.set_transform(_transform)

What i was trying to get from the box is the linear_velocity after picked up but its always 0 same with constant_force always 0. I was looking the same for the hands but the hands have the same results so i dont know how could i get the moving force of the hand / box so i could give it a apply_impulse(). Any help is rly appreciated. Thank you in advance.

Tip: if the video was deleted let me know i will update the link again.


Solution

  • You will need to compute the velocity of the hands, so you can use the last velocity they had when the player releases the object.

    We could do it with the hands, but it is probably better to do in the box directly.

    In the code, you place the box while held like this:

    _transform.origin = middlePoint
    

    Well, take the displacement:

    var displacement := middlePoint - _transform.origin
    _transform.origin = middlePoint
    

    And we can use state.step as surrogate for delta, so we can divide displacement over time to get velocity:

    var displacement := middlePoint - _transform.origin
    var computed_velocity := displacement / state.setp
    _transform.origin = middlePoint
    

    You could store that in a field, I mean, a script variable, to later call apply_impulse. Or you might set the linear velocity directly (I'm not sure if this is better):

    var displacement := middlePoint - _transform.origin
    state.linear_velocity := displacement / state.setp
    _transform.origin = middlePoint