如何在 Godot 引擎中的正确位置绘制形状?

How to draw shapes in correct position in godot engine?

我正在尝试做一个选择工具。碰撞形状已正确绘制,如您在填充框的形式中所见。拖动鼠标时,我想绘制一个绿色矩形。但是,框绘制在错误的位置。我错过了什么?

extends Area2D

onready var shape: Shape2D = $CollisionShape2D.shape
onready var collision: CollisionShape2D = $CollisionShape2D

export (Color, RGBA) var color = Color.green
export var stroke_width: float = 1.0
export (bool) var isFilled = true

var startOfDrag: Vector2
var endOfDrag: Vector2
var width: int = 1
var height: int = 1
var isMouseDragged: bool = false

var points: PoolVector2Array

func _process(delta: float) -> void:
if isMouseDragged:
    update()

func _draw():
draw_polyline(points , color, stroke_width, isFilled)

func _input(event: InputEvent) -> void:
if Input.is_action_just_pressed("left_mouse_down") and not isMouseDragged:
    startOfDrag = get_global_mouse_position()
    position = startOfDrag
    shape.set_extents(Vector2(1, 1))
    isMouseDragged = true

if Input.is_action_just_released("left_mouse_down"):
    isMouseDragged = false
    handleSelection()

endOfDrag = get_global_mouse_position()
    
width = abs(startOfDrag.x - endOfDrag.x)
height = abs(startOfDrag.y - endOfDrag.y)

change_rectangle()

func handleSelection() -> void:
shape.set_extents(Vector2(width/2, height/2))
collision.position = Vector2(width/2, height/2)

func change_rectangle() -> void:
points = []
points.append(Vector2(startOfDrag.x, startOfDrag.y))
points.append(Vector2(startOfDrag.x + width, startOfDrag.y))
points.append(Vector2(startOfDrag.x + width, startOfDrag.y + height))
points.append(Vector2(startOfDrag.x, startOfDrag.y + height))
points.append(Vector2(startOfDrag.x, startOfDrag.y))

这是我看到的:

startOfDrag = get_global_mouse_position()
position = startOfDrag

鼠标位置在全局坐标系中。虽然您的对象的位置在本地坐标中(您可以将其视为相对于父对象的坐标)。

改为设置global_position

startOfDrag = get_global_mouse_position()
global_position = startOfDrag

顺便说一句,方法to_local将全局坐标转换为您调用它的节点的局部坐标。同样,有一个 to_global 方法可以将调用它的节点的局部坐标转换为全局坐标。

跟踪哪些矢量在全局坐标中,哪些在局部坐标中。


如果应用了缩放比例,您的 widthheight 也可能不匹配。如果你 运行 进入那个,你应该能够用 CollisionShape2Dto_local 来修复它。