Godot 3.4.2
一个简单的平台角色的控制,包括土狼时间,跳跃输入缓冲,请看文末中的推荐阅读的文章
#============================================================
# Simple Platform Controller
#============================================================
# 简单的平台角色控制
# * 添加这个子节点到 KinematicBody2D 下即可使用
#============================================================
# @datetime: 2022-2-28 12:03:06
#============================================================
extends Node
class_name SimplePlatformController
## 在这个时间内按下跳跃,在落在地面上后自动进行跳跃
const BUFFER_TIME = 0.1
## 离开地面后,在这个时间内仍可以进行跳跃(土狼时间)
const GRACE_TIME = 0.2
export var input_left : String = "ui_left"
export var input_right : String = "ui_right"
export var input_jump : String = "ui_up"
export var move_speed = 300
export var jump_height = 800
export var gravity = 1500
var move_enabled : bool = true
var jump_enabled : bool = true
var motion_velocity := Vector2(0,0)
var __host__ : KinematicBody2D
var __jump_timer__ := Timer.new()
var __grace_timer__ := Timer.new()
#============================================================
# 内置
#============================================================
func _ready():
__host__ = get_parent()
__jump_timer__.wait_time = BUFFER_TIME
__jump_timer__.one_shot = true
__jump_timer__.connect("timeout", self, "set", ['__jump__', false])
add_child(__jump_timer__)
__grace_timer__.wait_time = GRACE_TIME
__grace_timer__.one_shot = true
add_child(__grace_timer__)
func _physics_process(delta):
# 获取输入
get_input()
# 重力
motion_velocity.y += gravity * delta
# 碰到天花板
if __host__.is_on_ceiling() and motion_velocity.y < 0:
motion_velocity.y = 0
# 开始跳跃
if __jump_timer__.time_left > 0:
if (__host__.is_on_floor()
or __grace_timer__.time_left > 0
):
motion_velocity.y = -jump_height
__jump_timer__.stop()
__grace_timer__.stop()
else:
# 土狼时间
if __host__.is_on_floor():
__grace_timer__.start(GRACE_TIME)
motion_velocity.y = 0
# 操控动
__host__.move_and_slide(motion_velocity, Vector2.UP)
motion_velocity.x = 0
#============================================================
# 自定义
#============================================================
## 按键输入
func get_input():
var v = Input.get_action_strength(input_right) - Input.get_action_strength(input_left)
move(v)
if Input.is_action_just_pressed(input_jump):
jump()
## 移动
## @dir 移动方向(-1 为左,1 为右)
func move(dir: float):
if move_enabled:
motion_velocity.x = dir * move_speed
## 跳跃
func jump():
# Jump
if jump_enabled:
__jump_timer__.start()
推荐阅读
|