Modify player position using a vector

Godot Version

Godot 4.2.2

Question

Hello, I’m currently tring to program a top down game where the player can move left and right freely but where up and down movements are more limited.

Basically the player can move along an horizontal line on the x axis in the middle of the screen, but pressing “up” and “down” can modify the player’s position on the y axis for a short time before coming back to the horizontal line where the y position equals 0.
Kind of like a claw machine in fairs ? But it can also go up as well as down.

At first I thought I could adjust position.y when pressing up or down, but I couldn’t get it to work. Now I’m thinking about adding a vector force when pressing the direction and resetting the y value afterwards, but all I can find on the internet is how to add a force to a RigidBody for physics simulations.

I’m mainly looking for indications of what and where to search, I want to understand the whole thing and not just copy/paste pre-made code.

Thank you for your help !!

show code and , share a video or screen shot from your problem.

but , now you can do this:

var velo = vector2()

...

if Input.is_action_pressed("up"):
    velo.y=-10 #for example 10

Thank you ! Unfortunately, the movement isnt affected by adding those lines. Here’s the full CharacterBody2D script:

extends CharacterBody2D


@export var speed = 500
var velo=Vector2()


func _physics_process(delta: float) -> void:
	var direction = Input.get_vector("left", "right", "up", "down")
	velocity = direction * speed
	move_and_slide()
	if Input.is_action_pressed("up"):
		velo.y=-10

Here is a video of what is happening: Watch insomniac_movement | Streamable

It’s the same standard movement I get when I use the rest of the code all alone.
Another example of what I’d like to do would be the underwater physics of 2D Mario games, but instead of having to mash a button to avoid sinking, you’d just hold one.

Thank you for your help !!

You could get the x axis seprately

var direction: float = Input.get_axis("left", "right")

and apply the y “up” if need be

var jump: bool = Input.is_action_pressed("up")

Now apply these two controls to velocity

func _physics_process(delta: float) -> void:
	var direction: float = Input.get_axis("left", "right")
	var jump: bool = Input.is_action_pressed("up")

	velocity.x = direction * speed
	if jump:
		velocity.y = -10
	else:
		velocity.y += 400 * delta

	move_and_slide()

Thanks, I did exactly that and now the player is falling. It’s not exactly what I had in mind, but playing with it just now I think it’s better and it gave me a new gameplay idea, I think I’m going to keep it that way.

Thanks for your help and your explanation !!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.