Reputation: 15
I have a world scene, that has a player.tscn in it, the player is a cannon, the cannon spawns a projectile, but I cannot seem to get the projectile(RigidBody2d) to move, it will drop with gravity enabled so i know its not set to static.
This is the player.tscn,
extends CharacterBody2D
@export var projectile : PackedScene = preload("res://projectile.tscn")
var cannon_rotation_speed = 10
var cannon: Sprite2D
var max_angle:float = -87.0
var min_angle:float = 4.0
var projectile_speed:float = 100.0
func _ready():
set_physics_process(true)
cannon = $Cannon
func _process(delta):
if Input.is_action_pressed("aim_up"):
rotate_cannon(-cannon_rotation_speed * delta)
elif Input.is_action_pressed("aim_down"):
rotate_cannon(cannon_rotation_speed * delta)
if Input.is_action_pressed("Velocity_Increase"):
projectile_speed += 1
elif Input.is_action_pressed("Velocity_Decrease"):
projectile_speed -= 1
func rotate_cannon(angle):
var new_angle = cannon.rotation_degrees + angle
if new_angle > max_angle and new_angle < min_angle:
cannon.rotation_degrees = new_angle
func _unhandled_input(event):
if event.is_action_pressed("shoot"):
shoot()
func shoot():
var b = projectile.instantiate()
owner.add_child(b)
var muzzle_transform = $Cannon/Muzzle.global_transform
b.global_transform = muzzle_transform
var direction = Vector2.RIGHT.rotated(deg_to_rad(cannon.rotation_degrees)) # Convert degrees to radians
var impulse_direction = direction.normalized()
b.apply_impulse(Vector2.ZERO, impulse_direction * projectile_speed * b.mass)
and this is the projectile.tscn,
extends RigidBody2D
# Called when the node enters the scene tree for the first time.
func _ready():
set_physics_process(true)
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
pass
func _on_body_entered(body):
queue_free()
I have tried setting the physics_process for both .tscn, changed speed values to extremes. but getting no change.
Upvotes: 0
Views: 466
Reputation: 15
Okay so I added, impulse_direction * projectile_speed to an impulse var first and used that, that fixed my issue, looks like rotated was initially receiving a Vector2 when it requires a float.
func shoot():
var b = projectile.instantiate()
owner.add_child(b)
var muzzle_transform = $Cannon/Muzzle.global_transform
b.global_transform = muzzle_transform
var direction = Vector2.RIGHT.rotated(deg_to_rad(cannon.rotation_degrees)) # Convert degrees to radians
var impulse_direction = direction.normalized()
var impulse = impulse_direction * projectile_speed
b.apply_impulse(impulse)
Upvotes: 0