What is wrong with my code?

Godot Version

v 4.6.1

Question

I try to understand why this script doesn`t work. I found other alternatives that do work, but I would like to understand the issue so I could prevent it happening next time. Thanks

Code:

extends CharacterBody2D

var direction = Vector2.ZERO
var speed = 400

func _ready():
	global_position = Vector2(960, 1000)
	#Each variable gets a random number for direction
	var valueX = random(direction.x)
	var valueY = random(direction.y)
	direction = [valueX, valueY]
	print(direction)

#Controls the movement of the ball
func _physics_process(delta):
	global_position = direction * speed * delta
	move_and_slide()

#This function chooses a random number for the direction
func random(value):
	value = [1, -1].pick_random()
	return value

You’re setting the global position directly, which ignores physics. You’re also setting it to a constant value instead of increasing it every frame. You should do velocity += direction * speed * delta

2 Likes