Godot Version
Godot 4.3
Question
I’m a little stupid. I have this code from tutorial about boids
extends Area2D
@export var player : Node2D
@onready var raycasts := $raycast.get_children()
@onready var agent := $NavigationAgent2D
var boidsISee := []
var vel := Vector2.ZERO
var speed := 2
var screensize : Vector2
var movv := 30
func _ready():
vel.x += 1
screensize = get_viewport_rect().size
randomize()
func _process(delta):
boid()
checkCollision()
vel = vel.normalized() * speed
move(delta)
func move(delta):
agent.target_position = player.global_position #my attempts so they are pathfinding to a player
var dir = position.direction_to(agent.get_next_path_position()).normalized()
look_at(agent.target_position)
global_position += vel + dir #spawns boids on the other half on the screen if the leave the viewport
if global_position.x < 0:
global_position.x = screensize.x
if global_position.x > screensize.x:
global_position.x = 0
if global_position.y < 0:
global_position.y = screensize.y
if global_position.y > screensize.y:
global_position.y = 0
func boid():
if boidsISee:
var numOfBoids := boidsISee.size()
var avgVel := Vector2.ZERO
var avgPos := Vector2.ZERO
var steerAway := Vector2.ZERO
for boid in boidsISee:
avgVel += boid.vel
avgPos += boid.position
steerAway -= (boid.global_position - global_position) * (movv/( global_position- boid.global_position).length())
avgVel /= numOfBoids
vel += (avgVel - vel)/2
avgPos /= numOfBoids
vel += (avgPos - position)
steerAway /= numOfBoids
vel += (steerAway)
func checkCollision():
for ray in raycasts:
var r : RayCast2D = ray
if r.is_colliding():
if r.get_collider().is_in_group("ground"):
var magi := (100/(r.get_collision_point() - global_position).length_squared())
vel -= (r.target_position.rotated(rotation) * magi)
pass
func clamp_rotation():
var maxDeltaRotation = 1.5708
var previous_rotation = rotation
var clampedRotation = clamp(rotation,previous_rotation - maxDeltaRotation, previous_rotation + maxDeltaRotation)
rotation = clampedRotation
func _on_vision_area_entered(area):
if area != self && area.is_in_group("boid"):
boidsISee.append(area)
func _on_vision_area_exited(area):
boidsISee.erase(area)
The problem is that pathfinding is a bit weird - boids stop instead if overcoming the obstacle or if there’s many boids neraby. is there a better way to make boids follow the player and overcome obstacles?