目录
优化死亡机制
添加死亡时慢动作效果,通过改变游戏时间尺度实现。
触碰怪物后,移除玩家碰撞形状节点,使玩家掉落。
编辑killzone脚本
extends Area2D
@onready var timer = $Timer
func _on_body_entered(body):
print("You died!")
# 将游戏速度改为半数
Engine.time_scale = 0.5
# 触碰怪物后,移除玩家碰撞形状节点,使玩家掉落。
body.get_node("CollisionShape2D").queue_free()
timer.start()
func _on_timer_timeout():
# 将游戏速度改为默认
Engine.time_scale = 1
get_tree().reload_current_scene()
优化玩家
更改玩家移动按键绑定
项目-项目设置-输入映射-添加新动作,并绑定按键
根据移动方向更改玩家图形
# 翻转玩家水平图像
if direction > 0:
animated_sprite.flip_h = false
elif direction < 0:
animated_sprite.flip_h = true
添加两个动画 jump run
player脚本
extends CharacterBody2D
const SPEED = 100.0
const JUMP_VELOCITY = -300.0
@onready var animated_sprite = $AnimatedSprite2D
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
func _physics_process(delta):
# 不在地板上就添加重力
if not is_on_floor():
velocity.y += gravity * delta
# Handle jump.
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = JUMP_VELOCITY
# 获取移动方向 -1 0 1
var direction = Input.get_axis("move_left", "move_right")
# 如果在地板上,站立不懂就播放闲置idle动画,左右移动就播放run动画
if is_on_floor():
# 动画播放
if direction == 0:
animated_sprite.play("idle")
else :
animated_sprite.play("run")
else :
# 如果在空中就播放jump动画
animated_sprite.play("jump")
# 翻转玩家水平图像
if direction > 0:
animated_sprite.flip_h = false
elif direction < 0:
animated_sprite.flip_h = true
# 移动玩家
if direction:
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
move_and_slide()