extends Area2D
signal hit # 声明一个名为hit的信号
@export var speed = 400 # 角色移动速度
var screen_size # 游戏窗口尺寸
func _ready():
screen_size = get_viewport_rect().size
hide() # 游戏开始隐藏角色
func _process(delta):
var velocity = Vector2.ZERO # 角色的移动向量
if Input.is_action_pressed("move_right"):
velocity.x += 1
if Input.is_action_pressed("move_left"):
velocity.x -= 1
if Input.is_action_pressed("move_down"):
velocity.y += 1
if Input.is_action_pressed("move_up"):
velocity.y -= 1
if velocity.length() > 0:
velocity = velocity.normalized() * speed
$AnimatedSprite2D.play()
else:
$AnimatedSprite2D.stop()
position += velocity * delta
position.x = clamp(position.x, 0, screen_size.x)
position.y = clamp(position.y, 0, screen_size.y)
if velocity.x != 0:
$AnimatedSprite2D.animation = "walk"
$AnimatedSprite2D.flip_v = false
$AnimatedSprite2D.flip_h = velocity.x < 0
elif velocity.y != 0:
$AnimatedSprite2D.animation = "up"
$AnimatedSprite2D.flip_v = velocity.y > 0
func _on_body_entered(body):
hide() # 被击中时隐藏Player
hit.emit()
$CollisionShape2D.set_deferred("disabled", true) # 被击中后禁用碰撞
func start(pos):
position = pos
show()
$CollisionShape2D.disabled = false
2D Player脚本
最新推荐文章于 2025-12-04 22:56:41 发布
该代码示例展示了在Godot引擎中创建一个2D角色,角色能响应键盘输入进行移动,有特定的移动速度。角色有hit信号,在与其他对象碰撞时触发,并改变动画状态以表示行走方向。同时,当角色被击中时会隐藏并禁用碰撞检测。
6703

被折叠的 条评论
为什么被折叠?



