Bug? Or something else (projectile zipping backwards instead like boomerang)

Hi folks, got a weird one. So I’m trying to recreate a game using similar code to Alien Attack and applying what I’m learning so far (practicing). Got the player and enemy movement down pat no worries and all the nodes and scenes are in place. However the projectile (I’m using the icon.svg squished down) to be a projectile rather than the rocket file as per the course and now the projectile is boomeranging backwards as you see in the GIF below:

Here’s the code I’ve got for the player:

extends CharacterBody2D

@export var speed = 300
var bullet_scene = preload("res://Scenes/bullet.tscn")
@onready var bullet_container = $BulletContainer

func _process(delta):
	if Input.is_action_just_pressed("shoot"):
		_shoot()
		
func _physics_process(delta):
	velocity = Vector2(0,0)
	if Input.is_action_pressed("move_right"):
		velocity.x = speed
	if Input.is_action_pressed("move_left"):
		velocity.x = -speed
	if Input.is_action_pressed("move_up"):
		velocity.y = -speed	
	if Input.is_action_pressed("move_down"):
		velocity.y = speed
	move_and_slide()
	
	var screen_size = get_viewport_rect().size
	global_position = global_position.clamp(Vector2(0,0), screen_size)

func _shoot():
	var bullet_instance = bullet_scene.instantiate()
	bullet_container.add_child(bullet_instance)
	bullet_instance.global_position = global_position
	bullet_instance.global_position.x += 50

And the projectile:

extends Area2D

@export var speed = 200

func _physics_process(delta):
	global_position.x = speed*delta

func _on_visible_on_screen_notifier_2d_screen_exited():
	queue_free()

And the nodes I have set for the player and bullet:

Screenshot 2023-05-30 at 7.39.10 pm
Screenshot 2023-05-30 at 7.39.17 pm

This is a really bad habit of mine. I looked and compared the bullet code over and over until I noticed this:

func _physics_process(delta):
	global_position.x = speed*delta

IT SHOULD be this one:

func _physics_process(delta):
	global_position.x += speed*delta

So sorry to waste anyone’s time that’s replying to this now.

1 Like

Morning,

the first thing that catches my eye is where you are setting the position of the bullet.
rathen that adding its movement to its current position, its always being set to a specific position at the left of the screen,

have a try at
global_position.x = global_position.x + speed*delta

Darren

1 Like

nice that you caught it, must have been replying at the same time lol :slight_smile:

glad its working

Thank you! That code you mentioned did work as well.

Thank you again :slight_smile:

sweet, no bother at all :slight_smile: , i only put it that way to be a little verbose in explaining.
i would normally use the += thing as well.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms