0 votes

I have an issue where when I move my player character, any bullets that it fires also move with it.

I have a separate scene which is my main scene, and have imported my main charecter as an instance into that scene

Code below:
extends KinematicBody2D

export (int) var speed = 200
var velocity = Vector2()
var main = gettree().getroot()

export(PackedScene) var Bullet = preload("res://Bulletthin.tscn")

func shoot():
var b = Bullet.instance()
add_child(b)
b.transform = $Muzzle.transform

func getinput():
velocity = Vector2()
if Input.is
actionpressed('right'):
velocity.x += 1
rotation
degrees = 90
if Input.isactionpressed('left'):
velocity.x -= 1
rotationdegrees = -90
if Input.is
actionpressed('down'):
velocity.y += 1
rotation
degrees = 180
if Input.isactionpressed('up'):
velocity.y -= 1
rotation_degrees = 360
velocity = velocity.normalized() * speed

func physicsprocess(delta):
getinput()
velocity = move
andslide(velocity)
if Input.is
action_pressed("fire"):
shoot()

Godot version Godot 3.0
in Engine by (24 points)

1 Answer

+1 vote
Best answer

Assuming the above script is attached to the player, your problem is here:

add_child(b)

That'll add the bullet as a child of the player, so the bullets will naturally move with the player.

To fix it, you need to add the bullet as a child of something outside of your player node's hierarchy.

That could be as simple as this:

get_parent().add_child(b)

That'll add the bullet as a child of the parent of the player (so, a sibling of the player). According to your above-described scene layout, it'll be added as a child of the main scene. That should fix the problem.

by (10,836 points)
selected by

Well, I did that, and all I needed to go was put
b.transform = $Muzzle.golbal_transform
instead of
b.transform = $Muzzle.transform

and it worked! Thank you!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.

Categories