Godot Version
Godot version 4.6.2. stable
Question
I’m trying to code a cannon that tracks the player and shoots, so I started following octodemy’s “making projectiles hit moving targets in game”, a problem arise when test firing the code breaks because of the PackedScene most likely because the cannon balls aren’t a PackedScene and I don’t know how to pack them. there might be another video explaining what he did but I haven’t found it yet
If you share code, please wrap it inside three backticks or replace the code in the next block:
extends Node3D
class_name CannonWeapon
@export var EXPLOSION_IMPULSE: float = 25.0
@export var show_aim := true
@export var ammo_resource:PackedScene <The Problem
@onready var spawn_point: Node3D = $Stand/Cannon/SpawnPoint
@onready var cannon: Node3D = $Stand/Cannon
func _physics_process(_delta: float) -> void:
if show_aim:
draw_aim()
func get_forward_direction() -> Vector3:
return cannon.global_transform.basis.y
func do_attack()-> void:
var cannonball = ammo_resource.instantiate() as RigidBody3D
get_tree().current_scene.add_child(cannonball)
cannonball.global_position = spawn_point.global_position
var dir: Vector3 = get_forward_direction()
cannonball.linear_velocity = dir*EXPLOSION_IMPULSE
func draw_aim()-> void:
var vel: Vector3 = get_forward_direction()
vel *= EXPLOSION_IMPULSE
var tstep := 0.1
var start_pos := spawn_point.global_position
var g: float = -ProjectSettings.get_setting("physics/3d/default_gravity", 9.8)
var line_start := start_pos
var line_end := start_pos
var colors = [Color.BLACK, Color.RED]
for i in range(1, 51):
var dt := (i * tstep)
line_end.x = dt * vel.x
line_end.z = dt * vel.z
line_end.y = dt * vel.y + (g*dt*dt)/2.0
line_end += start_pos
DebugDraw.draw_line(line_start, line_end, colors[i%2])
line_start = line_end
func _input(event):
if event.is_action_pressed("click"):
do_attack()