I have object A - plyer body with round area2D and object B - area2D. B following cursor, while in round area of A, and when mouse goes out of area of A - B stops, and i need to do something to make it following the cursor, but around limited circle of A’s area.
Code:
extends Area2D
var move_permition
func _ready() -> void:
$hand_sprite.scale.y = 0.5
func _physics_process(delta):
var hand_position = get_global_transform().origin
var cursor_position = get_global_mouse_position()
var distance = hand_position.distance_to(cursor_position)
if move_permition:
global_position = cursor_position
func _unhandled_input(event):
if event.is_action_pressed("left_mouse_button"):
$hand_sprite.scale.y = 0.3
if event.is_action_released("left_mouse_button"):
$hand_sprite.scale.y = 0.5
func _on_hand_zone_mouse_entered() -> void:
move_permition = true
func _on_hand_zone_mouse_exited() -> void:
move_permition = false
The Vector2 class has a few methods that might help you.
Specifically it has a .normalized() method, which returns a copy of the vector with length 1. You can multiply a length 1 vector by a number (such as the radius of your round area2d) to get a vector in the same direction of that length. The limit_length() method will do the same thing in fewer steps.
Alternatively, you can use a known angle (which could be obtained with Vector2’s angle() mehtod) and Vector2.from_angle() to get a normalized vector pointing in the given direction, and then multiply that.
I’m a bit confused about the relationship of objects A and B, relative to the code you posted, so I can’t help much more than that.
And also, how should i use limit_length()? Should it look like “global_position = cursor_position.limit_length(X)”? I just new and don’t know about of most of methods.
You’ll want to keep B a fixed distance from A, right? So if you get the vector from A to the cursor, you can limit the length of that vector and add it to A. That’s where B should be.