Hello,
I'm making a 2D game with 8 way movement and I'd like to be able to fire a projectile in the direction my player is facing. I've seen plenty of tutorials doing this with the mouse, but I'd like to do it without pointing the mouse. Right now my projectile fires upwards from my player no matter what position they are facing. I appreciate any help.
`#Projectile
extends CharacterBody2D
@export var SPEED = 75
var dir : float
var spawnPos : Vector2
var spawnRot : float
func _ready():
global_position = spawnPos
global_rotation = spawnRot
func _physics_process(delta):
velocity = Vector2(0, -SPEED).rotated(dir)
move_and_slide()
`
`#Player
extends CharacterBody2D
@export var move_speed : float = 100
@export var starting_direction : Vector2 = Vector2(0, 1)
@onready var animation_tree = $AnimationTree
@onready var state_machine = animation_tree.get("parameters/playback")
@onready var World = get_tree().get_root().get_node("World")
@onready var projectile = preload("res://Objects/projectile.tscn")
func _ready():
update_animation_parameters(starting_direction)
func _physics_process(delta):
var direction = input_movement()
update_animation_parameters(direction)
#Updates velocity
velocity = direction * move_speed
#Moves char
move_and_slide()
pick_new_state()
if Input.is_action_just_pressed("cast"):
cast()
func input_movement():
var input_direction = Vector2(
Input.get_action_strength("right") - Input.get_action_strength("left"),
Input.get_action_strength("down") - Input.get_action_strength("up")
)
return input_direction
func update_animation_parameters(move_input : Vector2):
#Doesn't change animation parameters if there is no move input
if(move_input != Vector2.ZERO):
animation_tree.set("parameters/Walk/blend_position", move_input)
animation_tree.set("parameters/Idle/blend_position", move_input)
#Chooses state based on what is happening with the player
func pick_new_state():
if(velocity != Vector2.ZERO):
state_machine.travel("Walk")
else:
state_machine.travel("Idle")
func cast():
var instance = projectile.instantiate()
instance.dir = rotation
instance.spawnPos = global_position
instance.spawnRot = rotation
World.add_child.call_deferred(instance)
`