I want to extend Brackeys “How to make a video game in 2d” , by adding a weapon to the game for the player which spawns and deletes itself when the LMB is clicked and released respectively.
However, I want it to spawn slightly to the the right of the player, but cannot figure out to implement this. Here’s my code of the player:
extends CharacterBody2D
const SPEED = 150.0
const JUMP_VELOCITY = -300.0
var sword_slash_path = load("res://Scenes/sword_slash.tscn")
@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
func _physics_process(delta: float) -> void:
# Add the gravity.
if not is_on_floor():
velocity += get_gravity() * delta
# Handle jump.
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var direction := Input.get_axis("move_left", "move_right")
if direction > 0:
animated_sprite.flip_h = false
elif direction < 0:
animated_sprite.flip_h = true
if is_on_floor():
if direction == 0:
animated_sprite.play("idle")
else:
animated_sprite.play("run")
else:
animated_sprite.play("jump")
if direction:
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
if Input.is_action_just_pressed("swing_sword"):
sword_swing(animated_sprite)
if Input.is_action_just_released("swing_sword"):
$sword_slash.free()
move_and_slide()
func sword_swing(animated_sprite):
var sword_slash = sword_slash_path.instantiate()
sword_slash.set_position(animated_sprite )
add_child(sword_slash)
I would be extremely grateful if anyone could help, and thanks in advance!