Godot Version
4.1.1
Question
Hi, I’m new to game development, especially GDScript, I’ve been messing around with scripts and nodes for 2 days now trying to create something like Brotato where you got multiple guns and they shoot at enemies within range without player pressing a button or aiming
I’ve made far more progress than I expected thanks to GDScript and Godot being so user-friendly and easy, but I’ve spent 7 hours today trying everything I could find on the internet to make guns shoot at targets but I can’t.
I’ll go deep into details since I’m so desperate
my player character (top image)
GunSlots are placeholders for guns scene which are later instantiated through code and put into these places
this is the script attached to it’s root:
extends CharacterBody2D
@export var speed = 200.0
@onready var label = $Label
var guns = []
func get_input():
var input_direction = Input.get_vector("move_left", "move_right", "move_up", "move_down")
velocity = input_direction * speed
func _ready():
var gun_scene = preload("res://scenes/gun.tscn")
for child in $GunSlots.get_children():
var gun = gun_scene.instantiate()
child.add_child(gun)
guns.append(gun)
gun.position = Vector2.ZERO
func _physics_process(delta):
get_input()
move_and_slide()
label.text = str(round(global_position))
for gun in guns:
gun.auto_shoot()
the gun scene (mid image)
the script attached to it (the real headache, this is like my 7th or maybe 10th attempt to write something that works)
extends Node2D
var bullet_scene = preload("res://scenes/bullet.tscn")
var weapon_range = 500.0
func _physics_process(delta):
auto_shoot()
func auto_shoot():
var closest_enemy = find_closest_enemy()
if closest_enemy:
look_at(closest_enemy.global_position)
shoot()
func find_closest_enemy():
var enemies = get_tree().get_nodes_in_group("enemy")
var closest_enemy = null
var closest_distance = weapon_range # Set to a very large value initially
for enemy in enemies:
var distance_to_enemy = global_position.distance_to(enemy.global_position)
if distance_to_enemy < closest_distance:
closest_distance = distance_to_enemy
closest_enemy = enemy
return closest_enemy
func shoot():
var bullet = bullet_scene.instantiate()
get_parent().add_child(bullet)
bullet.global_position = global_position
bullet.rotation = rotation
print("Bullet info: " + str(bullet.global_position) + "Gun info:" + str(get_parent().global_position))
and the problem itself (bottom image)
bullets spawn far away from the guns(there is no move function implemented yet so they just spawn they don’t move or damage anything, except for a script where they queue_free() if they leave the screen)
I can’t find the reason for it, I’ve tried many ways and most of them end up having this exact problem
another problem (after adding movement to bullets) is that they keep rotating with weapons after being shot
please I’m having a breakdown over this any help is greatly appreciated
thank you for being patient and reading this whole mess of a topic