0 votes

I have a problem with my gun system. in the scene it is structured as KinematicBody2D-Animated sprite - Area2D - Position 2D. the problem is when I fire the bullet just goes in a straight line or go in just one direction even I rotate.

this is my code for the gun (under Area2D)

extends Area2D

onready var bullet_scene = preload("res//Scenes/shot.tscn")
func _fixed_process(delta):
if Input.is_action_pressed("attack"):
var pos = get_pos()
var rotation = self.get_rot()
var direction = Vector2(sin(rotation),cos(rotation))
var distance_from_me = 50
var spawn_point = self.get_global_pos() + direction * distance_from_me
var bullet = bullet.scene.instance()
var world = self.get_node("../../..")
world.add_child(bullet)
bullet.set_global_pos(spawn_point)
bullet.start_at(get_rot(),get_global_pos())
func _ready():
set_fixed_process(true)

and this is the code for the bullet:

extends Area2D
var vel = Vector2()
export var speed = 1000

func start_at(dir,pos):
set_rot(dir)
vel = Vector2(speed,0).rotated(dir -PI/2)

func _fixed_process(delta):
set_pos(get_global_pos() + vel * delta)

func _ready():
set_fixed_process(true)

I think there's is something wrong in the func start_at. the bullets direction depends on where i put the speed in but I cant solve it. and if i removedbullet.start_at(get_rot(),get_global_pos())the bullet spreads in all direction but it wont travell. it will just damp on the spawn point and if the character collides with it the bullet disappears so meaning the bullet is active yet wont travell across the direction

in Engine by (23 points)
edited by

Can you fix your indentation? It's hard to tell exactly what your code is doing.

1 Answer

0 votes

I agree with kidscancode that it's hard to read without indentation, but I'll throw out a couple possible things.
I'm not sure what you are trying to do with the vel variable in the bullet block. That would typically have an x/y factor for the movement direction.
You DO calculate your x/y direction factor in the gun block, but you are passing the rotation value to function start_at instead. You could/should pass the direction variable value as your first argument. Then the fixed process would look something like:

set_global_pos(get_global_pos() + (dir * delta * speed))
by (312 points)
edited by
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 Frequently asked questions and 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 [email protected] with your username.