Antoine
Antoine

Reputation: 141

Changing a projectile's speed based on the target distance in Unity

I have a projectile that moves towards the player, but I want to be able to adjust its speed based on the distance it has to travel.

The transform variables are:

The projectile starts at firePoint, and gets destroyed when it reaches playerTransform

The speedMultiplier has an initial value of 1 but should change to a value between 0.5 and 1.5 based on how far the player is.

// This is called every time a projectile is fired

float speedMultiplier = 1f; 
speedMultiplier = FORMULA TO CALCULATE HOW MUCH THE SPEED SHOULD CHANGE; // Should be between 0.5 and 1.5
projectileSpeed *= speedMultiplier; 

Upvotes: 0

Views: 485

Answers (1)

bar9833625
bar9833625

Reputation: 321

You can use Mathf.lerp(a, b, t). The lerp method linearly interpolates between two values based on the third parameter. Think of the last parameter as a percentage.

For example:

Math.lerp(0.0f,10.0f,0.0f); //Will yield 0 because 0 is 0% between 0 and 10
Math.lerp(0.0f,10.0f,0.5f); //Will yield 5 because 5 is 50% between 0 and 10
Math.lerp(0.0f,10.0f,1.0f); //Will yield 10 because 10 is 100% between 0 and 10

So for your example, you can lerp based on the x position but you will need to scale it to between 0 and 1 (0 being where x = -7.5 and 1 where x = 4).

float t = Mathf.clamp01((transform.position.x + 7.5) / (4 + 7.5));

The method Mathf.clamp01(x) just clamps a number between 0 or 1.

Now just lerp between the speeds:

Mathf.lerp(0.5f, 1.5f, t);

Upvotes: 1

Related Questions