Vector2 not changing kinematic body's position

99 views Asked by At

I already checked the console to see if it was registering the input, it is. I can't figure out why it won't move.

extends Node2D

const WALK_SPEED = 5000
var velocity = Vector2(0,0)

func walk():
    if Input. is_action_pressed("Walk_Up"):
        velocity.y -= WALK_SPEED
        print("debug up")

func _physics_process(delta):
    walk()

It is supposed to move the sprite when I press W but nothing is happening other then the text I put in that print statement appearing in the console.
Also Node2D is just the name of the kinematic body I didn't change it from when I changed the type.

2

There are 2 answers

0
pignales On

You are setting the velocity but not calling anything that would use it.

A kinematic body can be moved by setting the velocity and calling one of move_and_collide() or move_and_slide(), as spelled out in the docs.

Call either of the two after your walk() function:

func _physics_process(delta):
  walk()
  move_and_slide(velocity)
0
Theraot On

You are simply not moving the Node2D.

Every physics frame you execute walk, where if the "Walk_Up" action is pressed you update the field variable velocity.

And that's it.

No, changing the variable you declared with name velocity has no special meaning, it won't make the Node2D move. You can name the variable you declare whatever you want, and it will still not move.


Given that you are working on a Node2D, you might want to move it by changing its position or global_position. For example:

extends Node2D

const WALK_SPEED = 5000.0
var velocity = Vector2(0.0,0.0)

func _physics_process(delta:float) -> void:
    if Input.is_action_pressed("Walk_Up"):
        velocity.y -= WALK_SPEED

    global_position += velocity * delta

Note: here WALK_SPEED units would be pixels per second.


However, since you say Kinematic Body, you might want to use a KinematicBody2D, for which the code would be like this:

extends KinematicBody2D

const WALK_SPEED = 5000.0
var velocity = Vector2(0.0,0.0)

func _physics_process(delta:float) -> void:
    if Input.is_action_pressed("Walk_Up"):
        velocity.y -= WALK_SPEED

    velocity = move_and_slide(velocity)

Why is it different? Unlike Node2D, KinematicBody2D is a physics body and it can collide with the environment, and using move_and_slide it will move but react to walls (that stop it) and ramps (over which it slides).