# How to get the velocity of an object?

^^^

Login

DARK THEME

- Help
- All
- Questions
- Project Sharing
- Off Topic
- Suggestions
- Game Engines
- Bugs
- News
- Roadmap
- Tips
- Resources
- 3D
- Articles

2

For that, you might need the help of my vector2 library. Try making a vector2 object called velocity. At the start of the update (before anything else, very important), set the x and y of the vector to the object's x and y. Then, at the end of the update, subtract the object's new x and y from the original. You are left with the x and y distance traveled. If you want to know the true distance, than simply call the `getLength()`

function with no inputs required on the velocity object. Eg:

```
update = function()
velocity = new vector2
velocity.setVector(object.x, object.y) //replace "object" with the name of your object
object.doMovementStuff() //this is where the object moves in accordance with the regular gameplay
velocity.x -= object.x
velocity.y -= object.y
trueVelocity = velocity.getLength()
object.doStuffWithTrueVelocity(trueVelocity)
end
```

in addition, the true velocity from last update (but not the vector2) will be still available to use until it is updated. The option I showed requires my vector2 library, as it adds the vector2 object and all associated functions to use so link is here: https://microstudio.dev/i/Abr00/yarghhhh/

1

What Abr00 said. To calculate the velocity of an object you get it's `speedx`

and `speedy`

, and then use Pythagoras theorem to find the 'distance' of the two variables. What Abr00's program seems to be doing is the same thing but using the 'getlength' function and calculating the speedx and speedy by the past xy position and the new xy position.

So here is my code (if you already using a speedx and speedy):

```
update=function()
velocity=sqrt(speedx^2+speedy^2) //Pythagoras theorem, a^2+b^2=c^2 so sqrt(a^2+b^2)=c
end
```

If you are not using speedx or speedy but can keep track of the player's x and y position, then you can do this to find the speedx and speedy, before using the same formula:

```
update=function()
speedx=oldx-x
speedy=oldy-y
oldx=x
oldy=y
end
```

Validate your e-mail address to participate in the community