Alejandro Obando
Alejandro Obando

Reputation: 1

Function for move the character2D in Godot

The error is in move_in_slide()

extends CharacterBody2D


var motion = Vector2(0, 0)
const speed = 50
const gravity = 50

const UP=Vector2(0,-1)

func _physics_process(delta):
    apply_gravity()
    if Input.is_action_pressed("left") and not Input.is_action_just_pressed("right"):
        motion.x = speed
    elif Input.is_action_pressed("right") and not Input.is_action_just_pressed("left"):
        motion.x = -speed
    else:
        motion.x=0

    move_and_slide(motion, UP)

func apply_gravity():
    if is_on_floor():
        motion.y=0
    else:
               motion.y +=gravity

I hope that solution my wrong. I am starting to learn Godot. I need help please

Upvotes: 0

Views: 154

Answers (2)

Roci49
Roci49

Reputation: 61

Since Godot4, to move a characterBody2D/3D you simply have to define the velocity vector and call move_and_slide() (or move_and_collide() with an argument) in the built-in function _physics_process(). See here for more details.

The solution you found is the actual solution to move a characterBody in Godot 3, where you had to specify which was the "floor vector" (since player falls down, ground had to "point up" to correctly collide with the player)

If you are using Godot4 and you are new, I reccomend use the template to move the player, read and understand that BEFORE going on (and read documentation, actually it is well written)

Upvotes: 0

PixelEggs
PixelEggs

Reputation: 1

I assume that you are using Godot 4, in which case move_and_slide() should take in 0 arguments. Try replacing move_and_slide(motion, UP) with simply move_and_slide().

Upvotes: 0

Related Questions