Top-Down Spawn Bullet Positioning Problem

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By hamtaro99

I have a function that spawns a bullet, but somehow the start position of the bullet is wrong, please see the screenshot below:

Here’s my current code:
For the enemy for spawning the bullet

func _spawn_bullet():
var bullet = bulletScene.instance()
bullet.start($BulletSpawn.global_position, currentAngle, damage)
owner.add_child(bullet)
pass

and here’s for the bullet:

extends KinematicBody2D
# properties
var bulletDamage = 0;
var targetPos = Vector2.ZERO
var velocity = Vector2()
var bulletAngle: float
var startPos
var bulletSpeed: int = 100
func start(origin: Vector2, angle: float, damage: int):
    startPos = origin
    bulletDamage = damage
    bulletAngle = angle
    velocity = Vector2(bulletSpeed, 0).rotated(bulletAngle)
    pass
func _ready():
    self.position = startPos
    pass
func _physics_process(delta):
    var collision = move_and_collide(velocity * delta)
    if collision:
        velocity = velocity.bounce(collision.normal)
        if collision.collider.has_method("hit"):
                collision.collider.hit()
    pass
func _on_VisibilityNotifier2D_screen_exited():
    queue_free()
    pass

Try setting the global_position you pass in the bullet’s global_position by changing:

startPos = origin

to

global_position = origin

timothybrentwood | 2021-09-20 14:46

thank you very much @.@ you’re a life saver

hamtaro99 | 2021-09-20 15:11

:bust_in_silhouette: Reply From: Skunky

When you set the position of the bullet in the ready function, you set the local position of it in relation to the parent (owner).
But you get the global position of the Bulletspawner, so there might be some offset due to the difference

Just changing “self.position” to “self.global_position” in the bullets ready function should help

yep, I’ll take note of this. Thanks

hamtaro99 | 2021-09-21 11:22