#Make a rigidbody2d smoothly move up and down

1 messages · Page 1 of 1 (latest)

tame vector
#

I have a rigidbody2d character that has no gravity and no drag. I made a quick demonstration in the video to show the target goal of what it should look like, but basically the rigidbody2d is supposed to move up and down with easing, while being constrained to a range, imagine an idle animation.
So here's my current code:

 func _idling(_delta) -> void:
    if global_position.y < (y_anchor - y_anchor_distance):
        idle_target = 1
    elif global_position.y > (y_anchor + y_anchor_distance):
        idle_target = -1

  apply_central_force(Vector2(0, idle_strength * idle_target))```
The problem with this code is that its inconsistent. It goes up normally, but then shoots down and goes off track completely. I know i need to involve some kind of smoothing, but i cant figure something out with lerp()
uneven garnetBOT
ancient tendon
wanton sparrow
#

Have you tried making it a static body until you want to use rigid body physics and then deleting the static body and replacing it with the original rigid body. Because computer physics are weird and cause unintended effects.

#

Or character body. And if all that is too much work just update rigid body pos to be mouse pos.

tame vector
#

Sorry i think i should have specified more. So this is how the code currently looks like in engine. It moves up and down but with small overshoots everytime. And these add up so that the body eventually hits the ground. The other video was just an example of how the movement is supposed to look like visually, not actually react to the mouse.

tame vector
wanton sparrow
#

If you are trying to make a moving object physics objects can interact with, you might be able to use a dynamic body

ancient tendon
stuck ridge
#

I am suspecting the overshooting is happening because of the momentum induced by its mass

#

these changes might throw things out of whack for that object, of course

#

failing that, a kinematic* body instead of rigid with no physics solver 'intervention' might be your only 100% sane option

tame vector
# ancient tendon I think the easiest way would be to make the strength dependent on the distance ...

So this worked. I added linear damping with 5.0 and made the strength distance dependent. Here's the working code:

func _idling() -> void:
    if idle_target == null:
        idle_target = y_anchor + idle_anchor_bounds
    var idle_strength: float = 5
    var offset = idle_target - global_position.y
    
    if abs(offset) < 1:
        if idle_target > y_anchor:
            idle_target = y_anchor - idle_anchor_bounds
        else:
            idle_target = y_anchor + idle_anchor_bounds
            
    apply_central_force(Vector2(0, offset * idle_strength))```
Thanks for the help! I was stuck on this for like an actual month