KinematicBody2D 在 Godot 中不动

问题描述

我为方形字符的基本移动编写了一些代码,但它似乎不起作用,没有错误,我对 if 语句的缩进进行了纠正,代码如下:

Extends KinematicBody2D
var movespeed = 500
    
func _ready():
    pass # Replace with function body.
func _physics_process(delta):
    var motion = Vector2()
    
    if Input.is_action_pressed("up"):
        motion.y -= 1
        if Input.is_action_pressed("down"):
            motion.y += 1
    if Input.is_action_pressed("left"):
        motion.x += 1
    if Input.is_action_pressed("right"):
        motion.x -= 1
    
    motion = motion.normalized()
    motion = move_and_slide(motion * movespeed)

解决方法

您的代码有效,但您需要确保输入图中存在“上”“下”“左”“右”,否则,代码将运行,但字符不会移动。

>

要做这个,菜单左上角按“项目”然后“项目设置”,然后选择输入地图选项卡。

您需要添加动作,例如向上、向下、向左、向右,然后添加它们后,在该列表的底部找到它们,然后在键盘上分配您希望控制角色的键。这就是我必须对您的代码执行的操作才能使其正常工作。

,

首先,你对第三个 if 语句的缩进是错误的,应该留一个制表符。

其次,如果您在 ui_"up" 等前面添加 "down"。假设您没有按照 {{3} 的建议更改设置,它应该可以工作}.这些默认映射到箭头键。

创建一个空白项目后,以下代码可以代替您现有的语句:

if Input.is_action_pressed("ui_up"):
    motion.y -= 1
if Input.is_action_pressed("ui_down"):
    motion.y += 1
if Input.is_action_pressed("ui_left"):
    motion.x += 1
if Input.is_action_pressed("ui_right"):
    motion.x -= 1

最后,开头的Extends肯定是错误的,会报错,应该是extends