godot项目【宝石捕手】02~脚本初始化

发布时间:2026/8/10 8:46:41
godot项目【宝石捕手】02~脚本初始化 宝石Gem移动脚本编写宝石下坠逻辑实现修改position.y实现重力下坠的效果检测宝石是否移动到屏幕外面了首先确认我们屏幕的大小如何确认屏幕的大小可以根据godot提供的尺子模式量一下或者打开网格进行初步的检测就能够定下来。当gem移动到屏幕外边后节省资源的措施一、停止gem的移动可以节省cpu资源使用set_process(false)实现功能二、将gem资源释放掉使用queue_free()来实现功能并不是马上消失当我们的游戏场景中有很多的元素时可能会发生预料之外的问题。可以在游戏运行过程中观察Remote窗口可以看见节点确实被删除了额外的优化一、提取代码中对数值的硬编码1优化步骤一将数值的硬编码优化为常量单个脚本同一维护起了变量名2考虑到用户的屏幕大小不一定是统一的需要能够动态的获取屏幕的大小用代码动态获取窗口的大小1介绍一下Rect2的属性①position 是窗口的左上角②end 是窗口的右下角2使用get_viewport_rect().end.y来代替底部的数值最终宝石下坠以及检测运动到屏幕底部然后消失的逻辑实现如下extends Area2D const SPEED100.0# Called when the node enters the scene tree for the first time.func _ready()-void:pass# Replace with function body.# Called every frame. delta is the elapsed time since the previous frame.func _process(delta:float)-void:position.ySPEED*deltaifposition.yget_viewport_rect().end.y:set_process(false)queue_free()pass挡板Paddle移动脚本编写新建输入映射在项目设置里的input map可以在里面添加action然后将这些action与具体的键位输入进行绑定此处我们将move_leftaction绑定了键盘A键将move_rightaction绑定了键盘D键这些action能够在后续的GD脚本中识别到使用。脚本编写实现挡板的简单左右移动在func _process(delta: float) - void:内添加逻辑ifInput.is_action_pressed(move_left):position.x-SPEED*deltaifInput.is_action_pressed(move_right):position.xSPEED*delta增加需求如何限制paddle的移动范围让其不越过显示区域不需要手动实现使用godot内部提供的函数clampf即可实现增加逻辑#用clampf函数来限制即可position.xclampf(position.x,get_viewport_rect().position.x,get_viewport_rect().end.x)进一步优化输入脚本使用Input.get_axis()进一步优化将四行优化成两行完整代码extends Area2D const SPEED300.0# Called when the node enters the scene tree for the first time.func _ready()-void:pass# Replace with function body.# Called every frame. delta is the elapsed time since the previous frame.func _process(delta:float)-void:#if Input.is_action_pressed(move_left):#position.x - SPEED * delta#if position.x get_viewport_rect().position.x:#set_process(false)#if Input.is_action_pressed(move_right):#position.x SPEED * delta#if position.x get_viewport_rect().end.x:#set_process(false)var actionInput.get_axis(move_left,move_right)position.xaction*SPEED*delta#用clampf函数来限制即可position.xclampf(position.x,get_viewport_rect().position.x,get_viewport_rect().end.x)pass效果演示