为什么我的代码不能用于Godot中的基本运动?

问题描述 投票:0回答:1

我刚刚在godot中启动了一个新项目。到目前为止,我有一个png是主要角色。我已经向播放器添加了一个精灵和CollisionShape2D。当我运行游戏时,玩家不会移动(使用键)。有人知道这是怎么回事吗?这是我的代码:

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

编辑:

我也尝试过直接从Godots文档中复制和粘贴代码,但播放器仍然不移动:

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)
2d game-engine godot gdscript
1个回答
0
投票

我知道了。添加新脚本时,我没有将其添加到播放器中,而是添加到了场景中。

© www.soinside.com 2019 - 2024. All rights reserved.