DraggableComponent.gd:13 @drag(): 参数“get_viewport()”为空

问题描述 投票:0回答:1

我正在尝试使用组合来开发 Godot 中的拾取和放下机制。到目前为止我只使用了继承,所以我不确定我做得是否正确。另外,我是戈多的新手。

当我播放胡萝卜种子包场景并尝试移动胡萝卜种子包时,出现以下错误:

E 0:00:06:0469   DraggableComponent.gd:13 @ drag(): Parameter "get_viewport()" is null.
<C++ Source>   scene/main/canvas_item.cpp:1047 @ get_global_mouse_position()
<Stack Trace>  DraggableComponent.gd:13 @ drag()
             carrot_seedpack.gd:46 @ _physics_process()

这些是我的课程:

SelectableComponent.gd

extends Node

var selected = false
var selectable_type = 0 # value for type of item that can be collected

func _init(type : int):
    selectable_type = type

func toggle_select(global_state):
    selected = !selected
    if selected:
        global_state.item_selected = selectable_type
    else:
        global_state.item_selected = 0
    return selected

DraggableComponent.gd

extends StaticBody2D

var is_dragging = false

func start_drag():
    is_dragging = true

func stop_drag():
    is_dragging = false

func drag(position, delta, speed):
    if is_dragging:
        return lerp(position,get_global_mouse_position(), speed * delta)
    return position

carrot_seedpack.gd

extends StaticBody2D

var selectable_component_import = preload("res://scripts/crops/SelectableComponent.gd")
var draggable_component_import = preload("res://scripts/crops/DraggableComponent.gd")

@onready var global_state = Global
@onready var anim_sprite = $AnimatedSprite2D


var selectable
var draggable

func _ready():
    anim_sprite.play("default")
    selectable = selectable_component_import.new(1)
    draggable = draggable_component_import.new()
    
func _on_area_2d_input_event(_viewport, event, _shape_idx):
        if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
            if selectable.toggle_select(global_state):
                draggable.start_drag()
            else:
                draggable.stop_drag()
                
func _physics_process(delta):
        global_position = draggable.drag(global_position, delta, 80)

你能帮我吗?

inheritance godot composition godot4
1个回答
0
投票

使用 ChatGPT 并工作:

出现此问题的原因是 StaticBody2D(您的 DraggableComponent.gd 扩展的节点类型)本身没有视口上下文,而视口上下文是获取全局鼠标位置所必需的。此上下文通常可用于从 CanvasItem 或其他 GUI 类继承的节点。

以下是如何修改方法来解决问题并使用 Godot 中的组合来完善实现:

由于 StaticBody2D 不会自动提供视口访问,因此您需要修改 Drag() 函数以接受全局鼠标位置作为参数,而不是从内部调用 get_global_mouse_position() 。此更改使组件更加通用,并且不直接依赖于它所附加的节点类型。

© www.soinside.com 2019 - 2024. All rights reserved.