jzuraf
jzuraf

Reputation: 53

Why isn't my code working for basic Movement in Godot?

I just started a new project in godot. So far I have one png which is the main player. I have added a sprite and CollisionShape2D to the player. When i run the game the player does not move (using keys). Does anyone know what is going on here? Heres my code:

extends KinematicBody2D

export var speed = 10.0
export var tileSize = 32.0

var initpos = Vector2()
var dir = Vector2()
var facing = 'down'
var counter = 0.0

var moving = false

func _ready():
    initpos = position

func _process(delta):
    if not moving:
        set_dir()
    elif dir != Vector2():
        move(delta)
    else:
        moving = false

func set_dir(): #set moving
    dir = get_dir()

    if dir.x != 0 or dir.y != 0:
        moving = true
        initpos = position

func get_dir(): #user input

    var x = 0
    var y = 0

    if dir.y == 0:
        x = int(Input.is_action_pressed("ui_right")) - int(Input.is_action_pressed("ui_left"))
    if dir.x == 0:
        y = int(Input.is_action_pressed("ui_down")) - int(Input.is_action_pressed("ui_up"))

    return Vector2(x, y)

func move(delta): #move player linearly
    counter += delta + speed

    if counter >= 1.0:
        position = initpos + dir * tileSize
        counter = 0.0
        moving = false
    else:
        position = initpos + dir * tileSize * counter

EDIT:

I have also tried copying and pasting the code directly from Godots documentation and the player still does not move:

extends KinematicBody2D

export (int) var speed = 200

var velocity = Vector2()

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)

Upvotes: 0

Views: 1534

Answers (1)

jzuraf
jzuraf

Reputation: 53

I figured it out. When adding a new script I did not add it to the Player but to the scene.

Upvotes: 0

Related Questions