Topic was automatically imported from the old Question2Answer platform.
Asked By
congbinh75
I’m making a shooter game, following Angega Studios’s tutorials.
There’s a problem when making the ship shoot bullets. The bullets follow the ship’s horizontal position when moving although it should keep its direction.
The bullets’s scripts:
extends Area2D
export var speed = 1
var direction = Vector2(0, -1)
func _process(delta):
self.position += direction * speed
pass
func _on_VisibilityNotifier2D_viewport_exited(viewport):
queue_free()
pass
The ship’s scripts: (Elite is the name of the ship):
extends KinematicBody2D
var mouse_pos = Vector2()
var direction = Vector2()
var elite_pos = Vector2()
var laser_pos = Vector2()
onready var main_cannon = get_node("weapons/main_cannon")
var elite_laser = preload("res://scenes/elite_laser.tscn")
export var speed = 5
func _ready():
_process(true)
pass
func _process(delta):
mouse_pos = get_global_mouse_position()
elite_pos = self.position
direction = mouse_pos - elite_pos
direction.normalized()
move_and_slide(direction * speed)
pass
func _create_laser():
var laser = elite_laser.instance()
var cannon_pos = main_cannon.position
laser.position = cannon_pos
self.add_child(laser)
pass
func _on_Timer_timeout():
_create_laser()
pass
Don’t be adding lasers (or missiles, in general) to a ship. Add it to Node that is a parent (not neccesarily a direct parent) of your ship. A Node that represents level or world, something like that. It’s a Node that doesn’t change its position.
There should be a node like this in tutorial you’re following.
Thanks, I will notice that. The tutorial and my projects have some differences. Also the tutorials was made in Godot 2 so there are somethings I don’t know to change properly.
Instead of self.add_child(laser), try get_tree.get_root.add_child(laser)
edit: get_tree().get_root().add_child(laser)
I have tried this before but it said “Attempt to call function ‘get_root’ in base ‘null instance’ on a null instance”.
congbinh75 | 2018-12-09 04:20
sorry, get_tree().get_root().add_child(laser), typo!
can also try get_node("/root").add_child(laser)
shield | 2018-12-09 04:41
The scene ran without error but the bullets didn’t even show up on the scene.
congbinh75 | 2018-12-09 09:48
That’s kind of weird, what the bullet’s script? Maybe something with the _ready() func.
shield | 2018-12-09 09:55
I tried put some print function in the visibility notifier and it still printed out repeatedly, so it seem likes the bullets are on the scene. But by some reasons the bullets are not visible in the scene which they are instanced, though the bullet scene works well.
congbinh75 | 2018-12-09 11:58
Can you show me your scene tree?
shield | 2018-12-10 11:29
Sorry I don’t know how to upload image. I tried GG Drive or Imgur but it didn’t work. And I don’t know how to copy scene tree and paste it here.