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 SPEED=100.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.y+=SPEED*deltaifposition.y>get_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.x+=SPEED*delta增加需求:如何限制paddle的移动范围,让其不越过显示区域?
不需要手动实现,使用godot内部提供的函数clampf即可实现,增加逻辑
#用clampf函数来限制即可position.x=clampf(position.x,get_viewport_rect().position.x,get_viewport_rect().end.x)进一步优化输入脚本
使用Input.get_axis()进一步优化,将四行优化成两行,完整代码
extends Area2D const SPEED=300.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 action=Input.get_axis("move_left","move_right")position.x+=action*SPEED*delta#用clampf函数来限制即可position.x=clampf(position.x,get_viewport_rect().position.x,get_viewport_rect().end.x)pass