Topic was automatically imported from the old Question2Answer platform.
Asked By
MaximoTG98
Hi!
i’m trying to a simple game in 2D,
Two spaceships one infront of each other horizontaly.
They can only move in the Y axis.
Prevent them to keep going up or down.
They have to shoot bullets to each other.
I’ve managed to create a wall to prevent the players to keep going up(by code,i don’t know why but neither static,rigid or kinematic bodies worked).
And now what i’m trying to do is to make them shot to each other.
I have an scene called bullet with an Area2D->CollisionShape+Sprite.
And i’m adding it into the main scene(where both ships are) when i press a key,but then the thing is, as it is child of the player node,it sticks with it,so if i move the player the bullet(i’ve only managed to get one out) follows the player y axis too.
This is how child nodes are supposed to behave, they follow the transform of their parent. What you want to do is add the bullets to the node above the spaceship.
You haven’t showed your whole tree, but if you had this:
Main
- Ship1
- Ship2
Then you can do this:
get_parent().add_child(bala)
The other problem you have is you’re only making one instance of the bullet. I think you want to be able to fire more than once, so remove .instance() from the variable declaration. Now bala is a PackedScene variable. Then, when you fire, you create an instance:
I tried what you just said,this is the code in one of the players right now:
extends KinematicBody2D
var bala = preload("res://Bala.tscn") #Bala is Bullet
var speed = gl_vars.speed // It's 5
func _process(delta):
if Input.is_action_pressed("ui_up") && (self.position.y > 0):
self.position.y -= speed
elif Input.is_action_pressed("ui_down")&& (self.position.y < 600):
self.position.y += speed
elif Input.is_action_just_pressed("ui_shot2"):
var bala_instance = bala.instance()
get_parent().add_child(bala)
add_child(bala_intance) #Does work but we have the "sticking" problem.
get_parent().add_child(bala_instance) #Doesn't seem to work.
print("Bullet out")
My tree is exactly like you said:
Main
Player1
Player2
But it only works when it’s add_child() alone,without get_parent().In the console the print(“Bullet out”) mensagge apears every time i press the shooting key.I don’t know what is wrong.
If you want to take a look at the project here it is.
MaximoTG98 | 2018-08-16 12:41
Your problem is that you’re spawning the bullet at (0, 0). So when it’s not a child of the player, it winds up in the corner of the screen and moves off right away.
Set the bullet’s position to the players:
var bala_instance = bala.instance()
bala_instance.position = position
get_parent().add_child(bala_instance)
print("Bullet out")