0 votes

I made a 2D shooter game, it looks like space invaders. But i've coded the spaceship to look at the mouse. It shoots by creating instances of the bullet from another room. But it shoots only toward the Y vector, i would love to know how to make the bullet spawn and shoot towards where the mouse is. Also is kinematic body a good choice for the bullet? or you have any better suggestions?

Here is the code for the player:

extends KinematicBody2D

export var speed = 100
var velocity = Vector2.ZERO
const Bullet = preload("res://bullet.tscn")
const RELOAD_TIME = 0.1
var reloading = 0.0


func _physics_process(delta):
    look_at(get_global_mouse_position())
    if Input.is_action_pressed("ui_up"):
        if reloading <= 0.0:
            var bullet = Bullet.instance()
            bullet.global_position = global_position
            get_parent().add_child(bullet)
            reloading = RELOAD_TIME     
    if Input.is_action_pressed("ui_left"):
        velocity.x = -10 * delta * speed
    elif Input.is_action_pressed("ui_right"):
        velocity.x = 10 * delta * speed
    else:
        velocity.x = 0 

    reloading -= delta

    move_and_collide(velocity * delta)

And this is the code for the bullet:

extends KinematicBody2D

var velocity = Vector2.ZERO
var speed = 800

func _physics_process(delta):
    velocity.y = -10 * delta * speed
    if not get_node("notifier").is_on_screen():
        queue_free()

    move_and_slide(velocity)
asked Jun 1 in Projects by senkai (13 points)

1 Answer

0 votes

you can store the direction of the shooting in the bullet node, and instead of moving it in the y direction, you can move it into this normalized direction. something like

func _physics_process(delta):
    if Input.is_action_pressed("ui_up"):
        if reloading <= 0.0:
            var bullet = Bullet.instance()
            bullet.global_position = global_position
            get_parent().add_child(bullet)
            bullet.direction=(get_global_mouse_position()-global_position).normalized

and in bullet

var direction=Vector2()
func _physics_process(delta):
    velocity = delta * direction
    if not get_node("notifier").is_on_screen():
        queue_free()

    move_and_collide(velocity)

You can use any node for the bullet, even a simple area2D might work.
If you use a kinematic body i would use the move_and_collide() function rather than move_and_slide, as you dont usually expect the bullets to slide.

answered Jun 1 by Andrea (519 points)
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.