How can i make a RigidBody2D be unaffected by gravity?

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

Hi there.
I have a RigidBody2D that it’s falling, so i wanna it to not be affect by gravity.
But the problem is that i can’t change the Default Gravity Vector in the project settings cuz that will affect other RigidBody2D in my game. And I’m also can’t put it’s Gravity scale to 0, because i wanna that body to be attract by a gravity point. (Area2D)

What should i do?

:bust_in_silhouette: Reply From: Kurotsuki

You can set the gravity scale to 0 and still have it be affected by gravity points, to do that all you have to do is call a function that pulls the rigidbody into the gravity point if it enters the area

Can u give me a example?

X | 2021-03-10 19:49

Im not very good with using godots built in function but i’d code the Area2D script somewhat like this

extends Area2D

func _on_RigidBody2D_body_enter(body):
    # gets global position of rigidbody and area2D
    var pos = self.get_global_position()
    var bodyPos = body.get_global_position()

    var target = pos - bodyPos
    
    # since target is a vector that points to the direction of the gravity point add_force(target) will move the body towards the gravity point
    body.add_force(target)

This code most likely wont work but im sure you can figure it out

Kurotsuki | 2021-03-11 01:57

It’s give me the following error:

Invalid call to function 'add_force' in base 'RigidBody2D'. Expected 2 arguments.

X | 2021-03-11 20:40

Right, i forgot, use add_central_force(target) instead as add_force requires an offset vector too

Kurotsuki | 2021-03-11 23:02