介绍

使用4.4.1版本的Godot,开发一个简单的桌面小宠物,可以拖拽移动。所用到的材料会在最后面的参考给出。

原理

把主要窗口设置成透明,通过拖拽宠物进行窗口的拖拽,宠物在主要窗口中的位置是固定的。

Project Settings设置

在Display/Windows中,viewport width和viewport height设置成130px。Mode设置成Maximized(这个不能设置成Windowed),否则无法使主要窗口变成透明的。

选中Always On Top、Borderless、Transparent,Per Pixel Transparency 选中Allowed。

在Rendering/Viewport中,选中Transparent Background。

在Input Map中,添加一个名为drag的Action,绑定鼠标右键(可随意)。

节点创建与编码

创建一个StaticBody2D节点作为根节点,命名为Cat,在Inspector/Input中,选中Pickable。

创建一个Sprite2D作为子节点,命名为CateIdle,导入图片Idle.png设置其Texture,给Animation/Hframes属性设置成10。

创建一个AnimationPlayer作为子节点,在底部的Animation面包,给CateIdle的Frame属性,做一个命名为“cat_idle”的动画。

创建一个CollisionShape2D作为子节点,设置其Shape为一个RectangleShape2D实例,在2D编辑器设置其相应大小。

创建一个Camera2D节点,使的宠物在主要窗口内居中,它在主要窗口内的坐标是(0,0)。

给Cat节点添加一个脚本,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
extends StaticBody2D

var is_dragged = false
var offset = Vector2.ZERO

func _ready() -> void:
$AnimationPlayer.play("cat_idle")

func _physics_process(delta: float):
if Input.is_action_just_released("drag"):
is_dragged = false
offset = Vector2.ZERO
if is_dragged:
get_window().position += Vector2i(get_global_mouse_position() - offset)

func _input_event(viewport: Viewport, event: InputEvent, shape_idx: int) -> void:
if not is_dragged and Input.is_action_pressed("drag"):
offset = get_global_mouse_position()
is_dragged = true

结果

结果

源码下载地址:https://wwgu.lanzouq.com/iIEye2t8g8ti

密码:36y5

参考

1、https://godotengine.org

2、https://www.bilibili.com/video/BV1c4q5YGEVJ

3、https://toffeecraft.itch.io/cat-pack