Fire a projectile in the direction of a rotation

Godot Version

4

Question

Hi,

I’m currently exploring the possibility of a game and I’m trying to get a mechanic working, but I’m stuck on how I should code it.

I currently have a ball that is rotating around a pivot point in a circle when a user clicks. When the user lets go, I want to “fire” the ball but I want it to move in the direction that it would go based on it’s position rotating around the circle. A bit like a hammer throw at the olympics might be an easier way to describe it.

Here is my main code:

extends Node2D

@export var rotation_speed = PI
@export var Projectile:PackedScene

var pressed = false

func _process(delta):
	if pressed:
		$Circle/Pivot.rotation += rotation_speed * delta


func _unhandled_input(event: InputEvent) -> void:
	
	if event is InputEventMouseButton:
		if event.pressed:
			
			pressed = true
		else: 
			
			$Circle/Pivot.rotation = 0
			var b = Projectile.instantiate()
			owner.add_child(b)
			b.transform = $Circle/Pivot.global_transform
				
			pressed = false

My “projectile” does instantiate but at the moment it just shoots to the right due to how I’ve set things up in that class, but I’d like to get it to travel in a direction like I just mentioned. i’m assuming I need to pass the x,y position it should fire towards but I don’t know how I can calculate this from the rotation.

Any help would be appreciated.

thanks

You’ve already set the rotation (transform) for the projectile, so if the projectile has a script handling its movement, you can move it to the direction it’s facing.

# In the projectile script
position += transform.x * speed * delta

The desired direction should be transform.x, -transform.x, transform.y or -transform.y depending on where the pivot is pointing at, when its rotation is 0.

Hey thanks, for the reply, my projectile script was doing that, though I realised I was resetting the rotation of the pivot before setting the transform.

However I now need some way to pass whether it should be -x,x,-y,y etc. to the Projectile. I tried adding a

var dir = 0;

and then doing

b.dir = //some logic based on the pivots rotation_degrees.

However the editor doesn’t allow me to assign to this variable as it doesn’t exist on Node2D.

I tried giving my Projectile.gd script a specific class name, but this also doesn’t work. I assume it’s because I’m instantiating a scene the script is attached to.

This might seem basic but I’m new to Godot so I’m not sure how to pass this info along - I’m obviously just trying to set a property as one might do to a javascript object.

Any chance you could point me in the direction of how this is possible?

thanks