How to move a character at an angle with velocity y

Godot Version

4.3 stable

Question

`so i am trying to make a game where you can only acelerate and rotate if you want to move. but if i rotate i still go up. i know why because i use velocity y but i dont know any other way to add in the grafity.

code:
extends CharacterBody2D

var rocket_speed = -150
var gravity = 350

func get_input():
var up = Input.is_action_pressed(“up”)
var rotate_right = Input.is_action_pressed(“rotate right”)
var rotate_left = Input.is_action_pressed(“rotate left”)

if up:
	velocity.y = rocket_speed
if rotate_right:
	rotation += deg_to_rad(2)
if rotate_left:
	rotation += deg_to_rad(-2)

func _physics_process(delta):
velocity.y += gravity * delta
get_input()
move_and_slide() `

You need to apply the direction vector to the velocity.

Take a look at: 2D movement overview — Godot Engine (stable) documentation in English

It works now. But the gravity doesn’t work. i think it has something to do with transform.y at velocity and something to do with func _physics_process(delta) under velocity.y because that line doesnt work anymore.

extends CharacterBody2D

var rocket_speed = -150
var gravity = 20

func get_input():
var up = Input.is_action_pressed(“up”)
var rotate_right = Input.is_action_pressed(“rotate right”)
var rotate_left = Input.is_action_pressed(“rotate left”)
velocity = transform.y * Input.get_axis(“down”, “up”) * rocket_speed

if rotate_right:
	rotation += deg_to_rad(2)
if rotate_left:
	rotation += deg_to_rad(-2)

func _physics_process(delta):
velocity.y = velocity.y + gravity
get_input()
move_and_slide()

You may want to use move_toward and a acceleration value, and only apply movement if there is a direction pressed.

I’ve never been a fan of seperating into a get_input function since it’s never used anywhere else, it’s just an extra function that drops the delta parameter.

func _physics_process(delta: float) -> void:
    var rotation_input := Input.get_axis("rotate left", "rotate right")
    # using math over if/else and use `delta`
    rotation += deg_to_rad(2) * rotation_input * delta

    var direction_input := transform.y * Input.get_axis("down", "up")
    if direction_input:
        # a good acceleration value may be 4 to 8 times speed, maybe 600
        velocity = velocity.move_toward(direction_input * rocket_speed, acceleration * delta)
    else:
        velocity.y += gravity

    move_and_slide()

Make sure to use proper formatting when pasting code

thanks it works now learned a lot of the code, and im going to use the proper formatting in the future.

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