0 votes

I am trying to make a selection tool. The collision shape is drawn correctly, as you can see in form of the filled box. While the mouse is dragged, I want to draw a green rectangle. However, the box is drawn in the wrong place. What am I missing?
Screenshot

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))
Godot version 3.4.2
in Engine by (42 points)

1 Answer

0 votes

the problem is related using position instead of global_position. See detailed answer:

https://stackoverflow.com/questions/70473738/how-to-draw-shapes-in-correct-position-in-godot-engine

by (42 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.