如何解决线条渲染有时无法检测相交以及如何在循环时使其更宽容
我有一个创建循环的 2d 线渲染,我注意到的一个问题是,当以速度循环时,它有时无法检测到,我想知道如何阻止这种情况发生,另一个问题是如何制作它更宽容,例如,如果这条线真的很接近前一行,我希望它把它算作一个循环,以及我如何使这条线实际上成为鼠标指针,而不是让它后面有鬼影,这可能是一个未来的问题我目前让它创建一个区域 2d 来检测它自身内部的物品/对象我想知道是否有更好的方法来准确地检测到它们在所述循环中。
我上传了一个视频链接,可以直观地向您展示问题:https://www.youtube.com/watch?v=Jau7YDpZehY
extends Node2D
var points_array = PoolVector2Array()
#var check_array = []
var colision_array = []
var index : int = 0
onready var Line = $Line2D
onready var collision = $Area2D/CollisionPolygon2D
onready var collision_area = $Loop_collider
func _physics_process(delta):
Line.points = points_array # Link the array to the points and polygons
collision.polygon = points_array
if Input.is_action_just_pressed("left_click"): #This sets a position so that the next line can work together
points_array.append(get_global_mouse_position()) # This makes a empty vector and the mouse cords is assigned too it
#points_array.append(Vector2()) #This is the vector that follows the mouse
if Input.is_action_pressed("left_click"): #This checks the distance between last vector and the mouse vector
#points_array[-1] = get_global_mouse_position() # Gets the last position of the array and sets the mouse cords
var mouse_pos = get_global_mouse_position()
var distance = 20
while points_array[-1].distance_to(mouse_pos) > distance:
var last_point = points_array[-1]
var cords = last_point + last_point.direction_to(mouse_pos) * distance
points_array.append(cords)
create_collision()
if points_array.size() > 80: # This adds a length to the circle/line so it wont pass 18 mini lines
points_array.remove(0) #Removes the first array to make it look like it has a length
#check_array = []
colision_array[0].queue_free()
colision_array.remove(0)
if Input.is_action_just_released("left_click"): # This just clears the screen when the player releases the button
points_array = PoolVector2Array()
#check_array = []
for x in colision_array.size():
colision_array[0].queue_free()
colision_array.remove(0)
#index = 0
if points_array.size() > 3: # If the loop is long enough,to detect intersects
if points_array[0].distance_to(get_global_mouse_position()) < 5: # Checks if the end of the loop is near the end,then start new loop
new_loop()
for index in range(0,points_array.size() - 3):
if _segment_collision(
points_array[-1],points_array[-2],points_array[index],points_array[index + 1]
):
new_loop()
break
#if check_array.size() != points_array.size():
# check_array = points_array
#create_collision()
func _segment_collision(a1:Vector2,a2:Vector2,b1:Vector2,b2:Vector2) -> bool:
# if both ends of segment b are to the same side of segment a,they do not intersect
if sign(_wedge_product(a2 - a1,b1 - a1)) == sign(_wedge_product(a2 - a1,b2 - a1)):
return false
# if both ends of segment a are to the same side of segment b,they do not intersect
if sign(_wedge_product(b2 - b1,a1 - b1)) == sign(_wedge_product(b2 - b1,a2 - b1)):
return false
# the segments must intersect
return true
func _wedge_product(a:Vector2,b:Vector2) -> float:
# this is the length of the cross product
# it has the same sign as the sin of the angle between the vectors
return a.x * b.y - a.y * b.x
func new_loop(): # Creates a new loop when holding left click and or loop is complete
var new_start = points_array[-1]
collision.polygon = points_array
points_array = PoolVector2Array()
collision.polygon = []
#check_array = []
points_array.append(new_start)
for x in colision_array.size():
colision_array[0].queue_free()
colision_array.remove(0)
func create_collision(): # Creates collisions to detect when something hits the line renderer
var new_colision = CollisionShape2D.new()
var c_shape = RectangleShape2D.new()
var mid_point = Vector2((points_array[-1].x + points_array[-2].x) / 2,(points_array[-1].y + points_array[-2].y) / 2)
c_shape.set_extents(Vector2(10,2))
new_colision.shape = c_shape
if points_array.size() > 1:
colision_array.append(new_colision)
collision_area.add_child(new_colision)
new_colision.position = mid_point
#new_colision.position = Vector2((points_array[-1].x),(points_array[-1].y))
new_colision.look_at(points_array[-2])
func _on_Area2D_area_entered(area): # Test dummies
print("detect enemy")
func _on_Loop_collider_area_entered(area):
print("square detected")
解决方法
诊断
症状 1
我注意到,当以速度循环时,有时检测不到
事情是这样的:
-
当鼠标指针在帧之间移动太多时,它会创建多个片段,这里:
var mouse_pos = get_global_mouse_position() var distance = 20 while points_array[-1].distance_to(mouse_pos) > _distance: var last_point = points_array[-1] var cords = last_point + last_point.direction_to(mouse_pos) * distance points_array.append(cords) create_collision()
-
但是碰撞检查只是比较最后一个,这里:
for index in range(0,points_array.size() - 3): if _segment_collision( points_array[-1],points_array[-2],points_array[index],points_array[index + 1] ): new_loop() break
*记住
[-1]
给出最后一项,而[-2]
给出倒数第二个。
因此,交叉点可能发生在未检查的路段之一上。
症状 2
如何使它更宽容,例如,如果该行真的很接近前一行,我希望它把它算作一个循环
我们可以检查点到线段的距离。
症状 3
我如何让这条线实际上是鼠标指针而不是让它在后面
目前这些段的长度都相同。这似乎是您创建 CollisionShape2D
方式的限制。
治疗选择
我们可以通过检查每个段来解决症状 1。症状 2 通过改进上述检查。但是我们仍然需要一个允许可变段长度的症状 3 的解决方案。
如果我们创建一个支持可变段长度的解决方案,我们就不需要一次创建多个段,这就解决了症状 1。我们仍然需要改进检查以解决症状 2。
如果我们需要改进检查碰撞的方式并且无论如何我们都在重写碰撞,我们不妨实现一些允许我们检测自相交的东西。
我们将移植一种定义碰撞形状的新方法,它允许我们制作所需尺寸的旋转矩形。
手术
我最终重写了整个脚本。 因为我就是那样,我猜。
我决定让脚本按照以下结构创建其子节点:
Node
├_line
├_segments
└_loops
这里的_line
将是一个 Line2D
,_segments
将包含多个 Area2D
,每个都是一个段。并且 _loops
也将包含 Area2D
,但它们是跟踪的循环的多边形。
这将在 _ready
中完成:
var _line:Line2D
var _segments:Node2D
var _loops:Node2D
func _ready() -> void:
_line = Line2D.new()
_line.name = "_line"
add_child(_line)
_segments = Node2D.new()
_segments.name = "_segments"
add_child(_segments)
_loops = Node2D.new()
_loops.name = "_loops"
add_child(_loops)
我做出的另一个决定是考虑应用程序上的数据方式:我们正在采取立场。第一个位置是刚按下点击时。随后的位置是它移动的时候。从这些位置,我们将点添加到线和线段。从这些片段中,我们将得到循环。并且我们会一直这样下去,直到点击被释放。
好吧,如果点击是刚刚按下还是按住,都没有关系。无论哪种方式,我们都会获取鼠标的位置。
现在,_physics_process
将如下所示:
func _physics_process(_delta:float) -> void:
if Input.is_action_pressed("left_click"):
position(get_global_mouse_position())
# TODO
我们还需要在点击释放时进行处理。让我们为此创建一个函数,稍后再考虑:
func _physics_process(_delta:float) -> void:
if Input.is_action_pressed("left_click"):
position(get_global_mouse_position())
if Input.is_action_just_released("left_click"):
total_purge()
在 position
上,我们将遵循移动最后一个点以匹配最近位置的奇怪技巧。我们需要确保至少有两点。所以第一个点不动,我们可以安全地移动最后一个点。
var _points:PoolVector2Array = PoolVector2Array()
var _max_distance = 20
func position(pos:Vector2) -> void:
var point_count = _points.size()
if point_count == 0:
_points.append(pos)
_points.append(pos)
elif point_count == 1:
_points.append(pos)
else:
if _points[-2].distance_to(pos) > _max_distance:
_points.append(pos)
else:
_points[-1] = pos
注意我们检查到倒数第二个点的距离。我们无法检查最后一点,因为那是我们要移动的一点。
如果距离大于_max_dinstance
,那么我们添加一个新点,否则我们移动最后一个点。
我们还需要添加和更新细分:
var _points:PoolVector2Array = PoolVector2Array()
var _max_distance = 20
func position(pos:Vector2) -> void:
var point_count = _points.size()
if point_count == 0:
_points.append(pos)
_points.append(pos)
add_segment(pos,pos)
elif point_count == 1:
_points.append(pos)
add_segment(_points[-2],pos)
else:
if _points[-2].distance_to(pos) > _max_distance:
_points.append(pos)
add_segment(_points[-2],pos)
else:
_points[-1] = pos
change_segment(_points[-2],pos)
你知道,我们稍后会担心它是如何工作的。
我们也需要处理点太多的情况:
var _points:PoolVector2Array = PoolVector2Array()
var _max_points = 30
var _max_distance = 20
func position(pos:Vector2) -> void:
var point_count = _points.size()
if point_count == 0:
_points.append(pos)
_points.append(pos)
add_segment(pos,pos)
elif point_count == 1:
_points.append(pos)
add_segment(_points[-2],pos)
elif point_count > _max_points:
purge(point_count - _max_points)
else:
if _points[-2].distance_to(pos) > _max_distance:
_points.append(pos)
add_segment(_points[-2],pos)
我们需要更新 Line2D
,我们需要处理任何循环:
var _points:PoolVector2Array = PoolVector2Array()
var _max_points = 30
var _max_distance = 20
func position(pos:Vector2) -> void:
var point_count = _points.size()
if point_count == 0:
_points.append(pos)
_points.append(pos)
add_segment(pos,pos)
_line.points = _points
process_loop()
好的,让我们谈谈添加和更新细分:
var _width = 5
func add_segment(start:Vector2,end:Vector2) -> void:
var points = rotated_rectangle_points(start,end,_width)
var segment = Area2D.new()
var collision = create_collision_polygon(points)
segment.add_child(collision)
_segments.add_child(segment)
func change_segment(start:Vector2,_width)
var segment = (_segments.get_child(_segments.get_child_count() - 1) as Area2D)
var collision = (segment.get_child(0) as CollisionPolygon2D)
collision.set_polygon(points)
这里的 _width
是我们想要的碰撞多边形的宽度。
我们要么添加一个带有碰撞多边形的 Area2D
(通过我们稍后会担心的函数创建),要么我们使用最后一个 Area2D
并以相同的方式更新其碰撞多边形。
那么,我们如何获得旋转矩形的点数?
static func rotated_rectangle_points(start:Vector2,end:Vector2,width:float) -> Array:
var diff = end - start
var normal = diff.rotated(TAU/4).normalized()
var offset = normal * width * 0.5
return [start + offset,start - offset,end - offset,end + offset]
因此,您获取从线段开始到结束的向量,并将其旋转四分之一圈(也称为 90º)。这为您提供了一个与线段垂直(垂直)的向量,我们将使用该向量为其指定宽度。
从起点开始,我们通过法线方向的一半宽度找到矩形的第一个点,我们通过相反方向的另一半宽度找到第二个点。对终点做同样的事情,我们就有了矩形的四个角。
我们按顺序返回它们,使它们围绕矩形。
用这些点创建一个碰撞多边形很简单:
static func create_collision_polygon(points:Array) -> CollisionPolygon2D:
var result = CollisionPolygon2D.new()
result.set_polygon(points)
return result
好的,让我们谈谈净化。我添加了一个功能来清除点(线的)和线段。这是总清除的一部分。另一部分将删除循环:
func total_purge():
purge(_points.size())
purge_loops()
这很简单。
好的,为了清除点和分段,我们迭代并删除它们。
func purge(index:int) -> void:
var segments = _segments.get_children()
for _index in range(0,index):
_points.remove(0)
if segments.size() > 0:
_segments.remove_child(segments[0])
segments[0].queue_free()
segments.remove(0)
_line.points = _points
顺便说一下,对 if segments.size() > 0
的检查是必要的。有时清除会留下没有段的点,这会在以后导致问题。这是更简单的解决方案。
当然,我们必须更新 Line2D
。
清除循环怎么样?好吧,您将它们全部删除:
func purge_loops() -> void:
for loop in _loops.get_children():
if is_instance_valid(loop):
loop.queue_free()
最后我们可以处理循环。我们将检查线段的重叠区域,以确定它们是否相互交叉。
一个警告:我们要忽略相邻段的重叠(这肯定会发生,并且不构成循环)。
所以我们遍历段,检查重叠区域,在段中寻找它们(如果它们在那里),如果它们不相邻(它们在段中的索引的差异必须大于1 )。如果这一切都发生了,我们就有了一个循环:
func process_loop() -> void:
var segments = _segments.get_children()
for index in range(segments.size() - 1,-1):
var segment = segments[index]
var candidates = segment.get_overlapping_areas()
for candidate in candidates:
var candidate_index = segments.find(candidate)
if candidate_index == -1:
continue
if abs(candidate_index - index) > 1:
push_loop(candidate_index,index)
purge(index)
return
所以,当循环发生时,我们想用它做点什么,对吧?这就是 push_loop
的用途。我们还想删除属于循环(或循环之前)的点和线段,因此我们调用 purge
。
只剩下 push_loop
需要讨论:
func push_loop(first_index:int,second_index:int) -> void:
purge_loops()
var loop = Area2D.new()
var points = _points
points.resize(second_index)
for point_index in first_index + 1:
points.remove(0)
var collision = create_collision_polygon(points)
loop.add_child(collision)
_loops.add_child(loop)
如您所见,它创建了一个 Area2D
,并带有一个与循环相对应的碰撞多边形。 我决定使用 rezise
删除循环之后的点,并使用 for 循环删除之前的点。所以只剩下循环的点。
另请注意,我在开始时调用 purge_loops
,以确保一次只有一个循环。
回到症状上来:症状 1 和 3 可以通过始终移动最后一个点(并更新段)的技巧解决。症状 2 由矩形的宽度解决。调整该值。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。