- Home /

# Speed based on distance

Hi, I try to make an object land on the ground based on distance. I already did this: distance = Vector3.Distance(target.position, obj.position); and tried to calculate the rigidbody velocity based on distance the object is from the target(ground).However I got problem with calculating it, could someone help me :/ Im quit new to vectors. rb.velocity = distance / Time.deltaTime?? ;

**Answer** by unity_ek98vnTRplGj8Q
·
Nov 03, 2020 at 07:21 PM

Your first issue is that you don't just want the distance, you also want the direction to your object so you know what direction to move in. Luckily, this is exactly what a Vector is, it is a mathematical structure that contains both *Direction* and *Magnitude*. So lets start by grabbing the Vector between your object and your target. This can be done by subtraction your object's position from your targets position.

```
Vector3 toTarget = target.position - obj.position
```

Now lets lets multiply by a speed factor. This will let you control how fast you want to go based off of how far away you are.

```
float speedFactor = 2;
toTarget *= speedFactor;
```

Now you have a vector that represents both the direction you want to travel AND how fast you want to travel, based off of your distance to your target. Now you just need to set your velocity (No need for Time.deltaTime as Velocity is independent of framerate

```
rb.velocity = toTarget;
```

Should the direction vector be normalized after getting the direction? I mean after the vector subtraction the direction is right but magnitude probably not 1.

```
Vector3 toTarget = (target.position - obj.position).normalized
```

EDIT: sorry $$anonymous$$y bad.. the intention was to have the magnitude related to the distance,

If the intended speed is a factor of distance (based on the title of your question), then the vector:

```
Vector3 toTarget = target.position - obj.position;
```

is already a composite of direction and magnitude:

```
toTarget = toTarget.normalized * toTarget.magnitude;
```

^{^^^ (Don't actually do this, it's a lot of square roots) ^^^}

If you want to move at a *fixed speed* in a given direction, then you would want to normalize the vector and multiply by your new intended speed, yes.

```
newVelocity = toTarget.normalized * movementSpeed;
```

Right.. my mistake, the @unity_ek98vnTRplGj8Q answer was too clever for me :)

### Your answer

### Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.