Projectile direction not being precise when instantiated

Godot Version

<stable4.2>

Question

<i made arc projectile using characterbody2d which will land on player’s position. The projectile always works perfectly and land on target position precisely. however, when it was instantiated from enemy node, the landing position seems to go off, and i have no idea why. i would appreciate if you could help me solve the problem.

ezgif-7-c6b44a003f

func _shoot():
	print("THROW")
	var bomb = bombScene.instantiate()
	get_parent().add_child(bomb)
	bomb.global_position = $BombSpawnPoint.global_position
extends CharacterBody2D

@onready var target = get_node("../player")

var gravity: float = 500.0
var time_to_reach: float = 2.0
var max_height: float = 300.0

func _init():
	set_as_top_level(true)

func _ready():
	if target:
		calculate_velocity()
	else:
		print("Error: target not found")

func _physics_process(delta):
	velocity.y += gravity * delta
	move_and_slide()

func calculate_velocity():
	var start_position = global_position
	var target_position = target.global_position

	var distance_x = target_position.x - start_position.x
	var velocity_x = distance_x / time_to_reach

	var distance_y = target_position.y - start_position.y
	var velocity_y = (distance_y - 0.5 * gravity * time_to_reach * time_to_reach) / time_to_reach

	velocity = Vector2(velocity_x, velocity_y)

if you try to

print(target.global_position)

on calculate velocity
will it reflect the right position of the player?

no. it will not reflect the right position of the player

then you would want it to be shooting on the right target. if you print(target.name) on calculate velocity, will it still show “player”

yes. it will print “player”

okay. i fixed it. i did node path wrong i guess. but still dont know why.

@onready var target: Node2D
func init(initial_position: Vector2, target_node: Node2D):
	global_position = initial_position
	target = target_node
	calculate_velocity()
func _shoot():
	print("THROW")
	var bomb = bombScene.instantiate()
	get_parent().add_child(bomb)
	bomb.init($BombSpawnPoint.global_position, player)

node path wrong shouldnt even let you print the player though, but it’s all good if it’s fixed now

1 Like