[Godot3.3.3] – 细腻的玩家移动控制脚本(初级)

Player.gd脚本内容:

extends KinematicBody2D

var gravity = 1000	# 重力值
var velocity = Vector2.ZERO	# 玩家最终的速度应用值
var maxHorizontalSpeed = 125	# 水平速度的上限值: 玩家的速度将会被限制在该范围内
var horizontalAcceleration = 2000	# 按下按键后会持续获得的水平加速度
var jumpSpeed = 360	# 玩家按下按键的起始向上速度 / 本模板中玩家可以最多跳上3格的方块
var jumpTerminationMultiplier = 4	# 用于提前停止玩家的跳跃的参数	-> 33行
	
	
func _process(delta):
	# 检测玩家移动的按键并存入moveVecor向量中
	var moveVector = Vector2.ZERO
	moveVector.x = Input.get_action_strength("move_right") - Input.get_action_strength("move_left")
	moveVector.y = -1 if Input.is_action_just_pressed("jump") else 0
	# 移动数组用来存储玩家的按键比特值
	
	# 进行玩家的实际移动 #
	velocity.x += moveVector.x * horizontalAcceleration * delta	# 按下按键后给予水平加速度
	############## 松开按键进行减速
	if (moveVector.x == 0):
		velocity.x = lerp(velocity.x, 0, pow(2, -50 * delta))	# 让速度从原来的速度变到 0, 重量为 pow(2, -25 * delta)
	############## 限制玩家的速度防止超过最大值
	velocity.x = clamp(velocity.x, -maxHorizontalSpeed, maxHorizontalSpeed)
	####################################################
	
	
	############## 按下跳跃键进行跳跃
	if (moveVector.y == -1 and is_on_floor()):	# 如果玩家按下了跳跃键才进行移动
		velocity.y = moveVector.y * jumpSpeed
	
	if (velocity.y < 0 && !Input.is_action_pressed("jump")):
		velocity.y += gravity * jumpTerminationMultiplier * delta	# 当没有按下按键时增强重力来达到提前落地的作用
	else:
		velocity.y += gravity * delta	# 让玩家受到重力的作用

	velocity = move_and_slide(velocity, Vector2.UP)	# 移动玩家并检测碰撞
	# 注意: move_and_slide()方法需要提供速度和向上的法向量
	

额外补充:

lerp(a, b, w)

让速度 ab 变化,重量为 w

clamp(velocity.x, -maxHorizontalSpeed, maxHorizontalSpeed)

限制变量的范围
作者:Sy_
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇