My bullets fly in the wrong direction!

Godot Version

4.2.2

Question

I want bullets to emit in the direction an object is travelling. Currently, they leave to the object’s right rear—ugh! Am I missing something obvious?

  • %ObjectParent (Node2D)
    – Object (RigidBody2D)
    ---- Container (Node2D)
    ———Emitter (Node2D)
# OBJECT CODE

# This is called from the Emitter
func return_velocity():
	var objVelocity = linear_velocity
	return objVelocity

# EMITTER CODE

extends Node2D

@onready var projectile = load("res://Balls/Projectile.tscn")

func _physics_process(_delta):
	objVelocity = $"../..".return_velocity() 
	self.global_rotation = objVelocity.angle()

func fire_projectile():
	var instance = projectile.instantiate()
	instance.dimacr = rotation
	instance.spawnPos = global_position
	instance.spawnRot = rotation
	%ObjectParent.add_child.call_deferred(instance) 
	
	await get_tree().create_timer(1.0).timeout
	fire_projectile()
	
# PROJECTILE CODE

extends CharacterBody2D

var SPEED = 300
var dir : float
var spawnPos : Vector2
var spawnRot : float


func _ready():
	global_position = spawnPos
	global_rotation = spawnRot
	velocity = Vector2(0, SPEED).rotated(dir)


func _physics_process(delta):
	var collision = move_and_collide(velocity * delta)
	if collision:
		velocity = velocity.bounce( collision.get_normal() )

Might be the projectile’s _ready? The initial speed vector is rotated by dir but it isn’t set during instancing. Do you want to use spawnRot for that as well?

Good thought—I’ll try it. Thanks gertkeno!

UPDATE: pulled that thread but made no headway :confused:

Littered the scripts with prints. The Emitter happily reports the correct angle, which matches the Object’s, and the Projectile reports it’s travelling at that angle. It must be my eyes that are wrong.

Have you tried global_rotation instead of local?

Yeah, thanks! I had changed to global_rotation but no go. I ended up using a magic number. It turned out adding 90 deg did the trick, so I’m thinking there must be something I did in the scene. Couldn’t figure it out though, so hack it is.

I see that you seem to have got it to work.
In your code however, I don’t see you giving dir a value before firing the projectile.

Sharp eyes, sancho :sweat_smile: I just noticed I pasted

instance.dimacr = rotation

from the emitter, but I must have caught some overtype in my running around. That should read

instance.dir = rotation

and it looks like I noticed and fixed right away on my end. Still needed a magic 90!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.