When I try to set the velocity of an object the object goes to the position it was, at the very start

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

So basically I have this ball and I want this ball to follow the x position of the mouse but then get shot in a direction after I press left click. But when I do press left click the ball just moves to the position it was at at the very beginning and then gets shot.

extends RigidBody2D

var is_shot := false
var does_object_need_force := true

var velocity := Vector2(200, -200)

# Called when the node enters the scene tree for the first time.
func _ready():
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta):
	if !is_shot:
		if Input.is_action_just_pressed("ui_left_click"):
		is_shot = true

if !is_shot:
	self.position.x = get_global_mouse_position().x
	self.linear_velocity = Vector2.ZERO
elif does_object_need_force:
	self.position.x = self.position.x
	self.linear_velocity = velocity
	does_object_need_force = false

var hit_bodies : = get_colliding_bodies();
for body in hit_bodies:
	if body.is_in_group("Brick"):
		body.queue_free()
	elif body.is_in_group("Lost Wall"):
		get_tree().reload_current_scene()
pass
:bust_in_silhouette: Reply From: Inces

I don’t think this is what is happening. I guess You interpret it wrong, can You show printscreens or short film ?
WHat I see is:
-ball is following mouse at start
-you click, is_shot becomes true, elif line kicks in for ONE frame, linear velocity becomes 200,-200 for ONE frame teleporting ball to the top right
-is_shot is true, need_force is false, so neither of conditional line work, RIgidBody is moving in a built-in way till the end

Use apply_force instead of linear velocity when dealing with RigidBody. When mouse is holding your ball get the direction ball is heading ( mouse global position - ball global position ) one line before you set balls position to mouse position. Then, when you release your button, use this direction to apply force to Rigid Body ( direction.normalized() * speed), this way it can actually be done in ONE frame.