How to make Rigid body left or right?

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

i’m new to using GD script and am trying to find a simple way of making a rigid body left or right for a game i’m making and i was wondering if anyone could give me any help. i’ve tried to code the Rigid bodies movement but don’t know how. what i’ve done so far is;

extends RigidBody
var playermovement = Vector3(10,0,0)

if (Input.is_action_pressed(“ui_left”)):
playermovemnt = -playermovement;
elif (Input.is_action_pressed(“ui_right”)):
playermovement = playermovement;

func _ready():
pass # Replace with function body.

i know this is wrong but i can’t figure out how to move a character left or right on a 3d plane.

like user payload already wrote, you might go better with a KineticBody (but in your case in 3D). Except when you really need the player to be behave in a physically correct way.

If you still insist on using a RigidBody: :wink:
RigidBodies are usually moved by applying forces or impulses (apply_impulse). Such forces need direction vector3’s in global space. You can obtain those easily from the transform. So for applying forces along the x-axis this would be global_transform.basis.x or global_transform.basis.x * -1 for the opposite direction.

Directly setting the velocity of a RigidBody is generally not advisable. But if you really need to, you might want to do this inside the _integrate_forces handler.

wombatstampede | 2020-03-25 12:03

:bust_in_silhouette: Reply From: payload505

you can make a rigidBody move ,but it’s better to use KinematicBody2D
or Area2d for left and right movement since rigidbody has gravity and
for KinematicBody2D code to move it will be

func get_input():
velocity = Vector2()
if Input.is_action_pressed('right'):
    velocity.x += 1
if Input.is_action_pressed('left'):
    velocity.x -= 1
if Input.is_action_pressed('down'):
    velocity.y += 1
if Input.is_action_pressed('up'):
    velocity.y -= 1
velocity = velocity.normalized() * speed

func _physics_process(delta):
get_input()
velocity = move_and_slide(velocity)
and for moving Area2D around the same thing actually
just instead of move_and_slide(velocity)
it will be position += velocity * delta