…I want it so that the ball changes it’s degrees therefore changing the direction it’s facing to randomly.
Okay, but in every physics update?
Your question
…could you also explain to me how each velocity computation works…?
Sure thing.
Velocity:
As you may know from physics, velocity is a vector representing how fast an object is going. This velocity-vector can be described as being made up of two parts: a speed (a scalar) and a direction (a vector). As an example, your code has a direction, dir
, which is your direction, and SPEED
which is your scalar.
Physics Simulation:
When working with real-time physics simulations, just like you are right now, you write your code to work in what is called time steps (also known as ticks). Time steps are necessary to simulate a physical system on a computer for a variety of reasons (see Computer simulation - Wikipedia) and represent a fraction of time in the simulation in which you want to compute the next state of the system (i.e. where is my ball in the next frame?). In your case, this timestep (fraction of time) is delta
.
This brings us to your question.
What does the velocity computations in the code snippet I provided achieve?
Velocity computation explanation
velocity = dir * SPEED
In this line I am computing the desired velocity of the ball (which is a Vector2: a two-dimensional vector) and storing it in your velocity
-variable.
move_and_collide(velocity * delta)
Here, we are calling move_and_collide()
to move the ball. The amount that the ball is moved is given by the parameter that we give the function. In this case, we want to move the ball by velocity * delta
amount.
The reason we don’t just move by velocity
alone is because we want to move the ball delta
time into the future (timesteps, remember). To explain further:
Remember that velocity is in metres … per … second. If we want to move the ball by delta
seconds into the future, we have to multiply the velocity of the ball by those delta
seconds to achieve the correct distance that the ball would move in that timeframe.
Summary
- Velocity is a vector representing direction and speed
- Its unit (m/s) describes how far, in metres, an object moves in one second
- Physics simulations run in timesteps (In Godot, the standard is 60 steps per second)
- Seconds for one timestep: 1 / 60 ≈ 0,0166… seconds
Additional resources
If you have some questions about any of this, let me know.