apply_impulse not working (possible duplicate, none of the others helped me)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By malthus

I was just following a simple tutorial. When I instantiate my Bullets, the apply_impulse won’t work.
Here’s the whole script:
extends CharacterBody2D

var movespeed = 500
var bullet_speed = 2000
var bullet = load(“res://bullet.tscn”)

func _ready():
pass

func _physics_process(delta):
velocity.x = 0
velocity.y = 0
if Input.is_action_pressed(“up”):
velocity.y -= 1
if Input.is_action_pressed(“down”):
velocity.y += 1
if Input.is_action_pressed(“left”):
velocity.x -= 1
if Input.is_action_pressed(“right”):
velocity.x += 1
velocity = velocity.normalized() * movespeed
move_and_slide()
look_at(get_global_mouse_position())

if Input.is_action_just_pressed("LMB"):
	fire()

func fire():
var bullet_instance = bullet.instantiate()
bullet_instance.position = get_global_position()
bullet_instance.rotation_degrees = rotation_degrees
bullet_instance.apply_impulse(Vector2(),Vector2(bullet_speed,0).rotated(rotation_degrees))
get_tree().get_root().call_deferred(“add_child”,bullet_instance)

:bust_in_silhouette: Reply From: a_world_of_madness

From the RigidBody2D docs you can see that apply_impulse has these parameters:

void apply_impulse ( Vector2 impulse, Vector2 position=Vector2(0, 0) )

You seem to be setting the impulse itself to a zero vector, and only passing in a position. You might want to replace apply_impulse with apply_central_impulse, which automatically uses the center of mass as the position (so you won’t get any unwanted angular velocity). And even simpler would be to just set the linear_velocity directly, since otherwise the mass of the bullet will affect how fast it will actually go:
Change

bulletinstance.applyimpulse(Vector2(),Vector2(bulletspeed,0).rotated(rotationdegrees))

to

bulletinstance.linear_velocity = Vector2(bulletspeed,0).rotated(rotationdegrees)

Thank you so much! It worked!

malthus | 2023-06-11 11:54