控制
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
extends CharacterBody2D
class_name Player
@ export var speed = 200
func getMoveVector () :
var x = Input . get_action_strength ( "move_right" ) - Input . get_action_strength ( "move_left" );
var y = Input . get_action_strength ( "move_down" ) - Input . get_action_strength ( "move_up" );
return Vector2 ( x , y ). normalized ();
func _process ( delta ) :
var direction = getMoveVector ();
velocity = direction * speed ;
move_and_slide ();
获取对象
1
2
3
4
5
6
7
// 从根节点的完整路径获取对象
@ onready var skill_manager : SkillManager = get_node ( "/root/Main/SkillManager" )
// 简化版
$ / root / Main / Temp
// 根据唯一名称获取对象(只能获取当前场景的对象,对象需要"右键"-"%作为唯一名称访问")
% Continue . button_up . connect ( continue_game )
场景
1
2
3
4
// 保存场景:Ctrl+S 保存为 tscn 文件
// 加载场景
const PLAYER_SCENE : PackedScene = preload ( "res://scenes/player/player.tscn" )
配置文件
1
2
3
4
5
6
7
8
9
10
var config = ConfigFile ()
func _ready () :
var error = config . load ( "user://settings.cfg" )
if error == OK :
var fullscreen = config . get_value ( "display" , "fullscreen" , false )
print ( fullscreen )
else :
print ( "无法加载配置文件" )
粒子特效
配置
常用 GPUParticles2D(CPUParticles2D用于无显卡或低配环境)
注意 :
调用
1
2
3
4
5
6
7
8
9
10
11
12
// 实例化
var shot_vfx : ShotVFX = shot_vfx . instantiate ()
// 配置姿态
shot_vfx . position = position
shot_vfx . rotation = rotation
// 添加到场景中
get_node ( "/root/Main/Temp" ). add_child ( shot_vfx )
$ "/root/Main/Temp" . add_child ( shot_vfx )
// 播放特效
shot_vfx . emitting = true
// 播放完成后释放(可不释放进行重复利用)
shot_vfx . finished . connect ( queue_free )
碰撞
StaticBody2D 能应用于所有游戏,作为墙壁、地面、障碍物等固定物
RigidBody2D 比如像愤怒的小鸟、割绳子、太空飞船游戏的主角等
KinematicBody2D 几乎所有的前后左右移动、跳跃的平台游戏玩家或者敌人
Area2D 常见于游戏中的可收集元素或者标记,比如金币、楼梯、关口或者特殊区域等
class 定义
定义 class 的时候,必须先与 extends 空一行,否则虽然能正常使用,但是脚本中无提示,且系统的可选节点也不会显示
1
2
3
extends Node2D
class_name Bullet
相机跟随
1
2
3
4
5
6
7
8
9
10
11
12
13
14
extends Camera2D
# Called when the node enters the scene tree for the first time.
func _ready ():
pass # Replace with function body.
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process ( delta ):
if Util . get_player () == null :
return
var play_pos = Util . get_player () . position
global_position = global_position . lerp ( play_pos , 1.0 - exp ( - delta * 10 ))
Licensed under CC BY-NC-SA 4.0