This is the code I wrote to spawn something randomly btw two positions but it always spawns it in the "spawnpoint2" and IDK what to do
{
public Transform spawnpoint1;
public Transform spawnpoint2;
public GameObject enemyprefab;
private void Start()
{
InvokeRepeating("spawn", 3f, 5f);
}
void spawn()
{
float randomizer= Random.Range(0f, 3f);
if (randomizer == 1f)
Instantiate(enemyprefab, spawnpoint1);
else
Instantiate(enemyprefab, spawnpoint2);
}
}
THis is the float version of the method Random.Range. You will have 1.0f sometimes, but it's pretty rare.
You would better use the int version.
// Random.Range(0f, 3f); // float version
Random.Range(0, 3); // int version
If you try to get a floating point number between 0 and 3 (inclusive) there is really a small possibility to get exactly 1.0 between all the possibile intermediate values.
You should use the integer version from Random.Range, but this version has the upper limit excluded so you should use 4 as the upper limit to get any value from 0 to 3
While it seems secondary (you check only for 1 so you will get the 1 even if the upper limit were 2) using an upper limit of 3 changes the frequences of 1 results vs other numbers and so your spawnpoint1 will be more frequent.
void spawn()
{
int randomizer= Random.Range(0, 4);
if (randomizer == 1)
Instantiate(enemyprefab, spawnpoint1);
else
Instantiate(enemyprefab, spawnpoint2);
}
Related
I am generating a random number between a range but I want the number to not be 0. It can be 0.1, 0.2...etc but not 0. How do I do this?
public float selectedValue;
void Start()
{
selectedValue = Random.Range(-0.5f, 0.5f);
}
Keep finding random values until its value is not zero
float RandomNumExceptZero (float min, float max){
float randomNum = 0.0f;
do {
randomNum = Random.Range (min, max);
} while (randomNum == 0.0f );
return randomNum ;
}
Building on the suggestion of #Psi you could do this:
public float selectedValue;
void Start()
{
selectedValue = Random.Range(float.MinValue, 0.5f)*(Random.value > 0.5f?1:-1);
}
Random.Range() takes in 2 arguments in which the second argument is exclusive. You can use it for your advantage by excluding the value 0. The logic used is to find a random value between -0.5f and 0 (exclusive). Use another randomizer to get either a positive value or a negative value
public float selectedValue;
void Start()
{
selectedValue = Random.Range(-0.5f, 0);
int sign = Random.Range(0, 2);
// the value sign can be either 0 or 1
// if the sign is positive, invert the sign of selectedValue
if(sign) selectedValue = -selectedValue;
}
I just want to point out that there are 2,113,929,216 (*) float values in the interval [-0.5, 0.5) which gives a ≈ 0.000000047305 % chance that exactly 0.0f will be generated.
(*) found by brute force with C++ std::next_after but both implementation should follow IEEE 754 so I don't expect to be language differences in this regard, unless Unity somehow doesn't use subnormal numbers.
Well, just make if{} in Update() to pick another random number with same function if it is 0.0f. No way it will get 0.0f two times in a row
I am trying to create a program that will spawn balls from the top randomly at random times. The problem is it is not fast enough, but if I change the value to like 1/2 it spawns 50 super fast.
using System.Collections.Generic;
using UnityEngine;
public class SpawnAstroids : MonoBehaviour
{
public GameObject astriod;
public float xBounds, yBounds;
public int playerPoints = 0;
public int enemyPoints = 0;
void Start()
{
StartCoroutine(SpawnRandomGameObject());
}
IEnumerator SpawnRandomGameObject()
{
yield return new WaitForSeconds(Random.Range(1,2)); //Random.Range(1/2, 2)
Instantiate(astriod, new Vector2(Random.Range(-xBounds, xBounds), yBounds), Quaternion.identity);
StartCoroutine(SpawnRandomGameObject());
}
}
Unity C# requires that you specify whether your decimal is specifically a float or a double. Add in f to the end of each decimal number. For example: Random.Range(0.5f, 2);
(Minor Note that Random.Range is inclusive vs exclusive depending on whether you use integers or floats.)
Similarly when you define a Vector2 bob = new Vector2(0.5f,0);, the f is also needed to denote explicitly that it is a float.
Random.Range has two overloads.
public static float Range(float minInclusive, float maxInclusive);
and
public static int Range(int minInclusive, int maxExclusive);
you are passing in
Random.Range(1, 2);
which are two int values so the second overload is used where the result will be an int between 1 and 2 - 1 ... not many options here ;)
Also your attempt
Random.Range(1/2, 2);
are again int values! 1/2 is an integer division which results in 0! So this random can either return 0 or 1.
What you rather want to do is passing in float values like e.g.
Random.Range(1f, 2f);
which can result in any floating point value between 1 and 2 or accordingly
Random.Range(0.5f, 2);
or back to your attempt
Random.Range(1 / 2f, 2);
which now uses a float division and thereby the result is automatically a float so the first overload will be used.
In general btw there is no need to call a Coroutine recursively, you can simply loop forever and also note that Start itself can be a Coroutine like e.g.
private IEnumerator Start()
{
while(true)
{
yield return new WaitForSeconds(Random.Range(0.5f, 2f));
Instantiate(astriod, new Vector2(Random.Range(-xBounds, xBounds), yBounds), Quaternion.identity);
}
}
I have a code that allows me to draw lines and limit the number of lines that can be drawn.
My problem is that I want to create a line (with for example line renderer)
and then allow the user to try drawing a similar (not necessarily exactly the same) line and the code needs to know according to the setting if the line is similar enough or not, but I can't figure it.
I would appreciate any tips.
public class DrawLine : MonoBehaviour
{
public GameObject linePrefab;
public GameObject currentLine;
public LineRenderer lineRenderer;
public EdgeCollider2D edgeCollider;
public List<Vector2> fingerPositions;
public Button[] answers;
public bool isCurrButtonActive;
int mouseButtonState = 0;
void Update()
{
Debug.Log(rfgrhe);
if (isCurrButtonActive)
{
if (Input.GetMouseButtonDown(0))
{
if (mouseButtonState == 0)
{
CreateLine();
}
}
if (Input.GetMouseButtonUp(0))
{
mouseButtonState++;
}
if (Input.GetMouseButton(0))
{
if (mouseButtonState == 1)
{
Debug.Log(Input.mousePosition.ToString());
if (Input.mousePosition.x < 100 || Input.mousePosition.y > 420 || Input.mousePosition.x > 660 || Input.mousePosition.y < 7)
{
return;
}
Vector2 tempFingerPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (Vector2.Distance(tempFingerPos, fingerPositions[fingerPositions.Count - 1]) > .1f)
{
UpdateLine(tempFingerPos);
}
}
}
}
}
void CreateLine()
{
mouseButtonState++;
currentLine = Instantiate(linePrefab, Vector3.zero, Quaternion.identity);
lineRenderer = currentLine.GetComponent<LineRenderer>();
edgeCollider = currentLine.GetComponent<EdgeCollider2D>();
fingerPositions.Clear();
fingerPositions.Add(Camera.main.ScreenToWorldPoint(Input.mousePosition));
fingerPositions.Add(Camera.main.ScreenToWorldPoint(Input.mousePosition));
lineRenderer.SetPosition(0, fingerPositions[0]);
lineRenderer.SetPosition(1, fingerPositions[1]);
edgeCollider.points = fingerPositions.ToArray();
}
void UpdateLine(Vector2 newFingerPos)
{
fingerPositions.Add(newFingerPos);
lineRenderer.positionCount++;
lineRenderer.SetPosition(lineRenderer.positionCount - 1, newFingerPos);
edgeCollider.points = fingerPositions.ToArray();
}
public void ActivateCurrentButton()
{
// Debug.Log(isCurrButtonActive);
isCurrButtonActive = true;
for (int i = 0; i < answers.Length; i++)
{
if (answers[i].CompareTag("onePoint"))
{
answers[i].GetComponent<MapLvl>().isCurrButtonActive = false;
}
else if (answers[i].CompareTag("TwoPoints"))
{
answers[i].GetComponent<DrawLine>().isCurrButtonActive = false;
}
}
}
}
For example in that case, the blue line is the correct one, the green and the red ones are two options of an answer from the user.
What I want is that the program will acknolage only the green line as a correct answer.
EDIT: Since it's clearer now what we want, here's a way to achieve it:
The function float DifferenceBetweenLines(Vector3[], Vector3[]) below gives you a measure of the "distance between the two lines".
It walks along the line to match with a maximum step length, and for each point, computes the distance from the closest point on the draw line.
It sums the squares of those distances and divide them by the length of the line to match (don't ask me to explain this with mathematical rigor).
The smaller the return value, the closer the first line matches the second -- the threshold is yours to decide.
float DifferenceBetweenLines(Vector3[] drawn, Vector3[] toMatch) {
float sqrDistAcc = 0f;
float length = 0f;
Vector3 prevPoint = toMatch[0];
foreach (var toMatchPoint in WalkAlongLine(toMatch)) {
sqrDistAcc += SqrDistanceToLine(drawn, toMatchPoint);
length += Vector3.Distance(toMatchPoint, prevPoint);
prevPoint = toMatchPoint;
}
return sqrDistAcc / length;
}
/// <summary>
/// Move a point from the beginning of the line to its end using a maximum step, yielding the point at each step.
/// </summary>
IEnumerable<Vector3> WalkAlongLine(IEnumerable<Vector3> line, float maxStep = .1f) {
using (var lineEnum = line.GetEnumerator()) {
if (!lineEnum.MoveNext())
yield break;
var pos = lineEnum.Current;
while (lineEnum.MoveNext()) {
Debug.Log(lineEnum.Current);
var target = lineEnum.Current;
while (pos != target) {
yield return pos = Vector3.MoveTowards(pos, target, maxStep);
}
}
}
}
static float SqrDistanceToLine(Vector3[] line, Vector3 point) {
return ListSegments(line)
.Select(seg => SqrDistanceToSegment(seg.a, seg.b, point))
.Min();
}
static float SqrDistanceToSegment(Vector3 linePoint1, Vector3 linePoint2, Vector3 point) {
var projected = ProjectPointOnLineSegment(linePoint1, linePoint1, point);
return (projected - point).sqrMagnitude;
}
/// <summary>
/// Outputs each position of the line (but the last) and the consecutive one wrapped in a Segment.
/// Example: a, b, c, d --> (a, b), (b, c), (c, d)
/// </summary>
static IEnumerable<Segment> ListSegments(IEnumerable<Vector3> line) {
using (var pt1 = line.GetEnumerator())
using (var pt2 = line.GetEnumerator()) {
pt2.MoveNext();
while (pt2.MoveNext()) {
pt1.MoveNext();
yield return new Segment { a = pt1.Current, b = pt2.Current };
}
}
}
struct Segment {
public Vector3 a;
public Vector3 b;
}
//This function finds out on which side of a line segment the point is located.
//The point is assumed to be on a line created by linePoint1 and linePoint2. If the point is not on
//the line segment, project it on the line using ProjectPointOnLine() first.
//Returns 0 if point is on the line segment.
//Returns 1 if point is outside of the line segment and located on the side of linePoint1.
//Returns 2 if point is outside of the line segment and located on the side of linePoint2.
static int PointOnWhichSideOfLineSegment(Vector3 linePoint1, Vector3 linePoint2, Vector3 point){
Vector3 lineVec = linePoint2 - linePoint1;
Vector3 pointVec = point - linePoint1;
if (Vector3.Dot(pointVec, lineVec) > 0) {
return pointVec.magnitude <= lineVec.magnitude ? 0 : 2;
} else {
return 1;
}
}
//This function returns a point which is a projection from a point to a line.
//The line is regarded infinite. If the line is finite, use ProjectPointOnLineSegment() instead.
static Vector3 ProjectPointOnLine(Vector3 linePoint, Vector3 lineVec, Vector3 point){
//get vector from point on line to point in space
Vector3 linePointToPoint = point - linePoint;
float t = Vector3.Dot(linePointToPoint, lineVec);
return linePoint + lineVec * t;
}
//This function returns a point which is a projection from a point to a line segment.
//If the projected point lies outside of the line segment, the projected point will
//be clamped to the appropriate line edge.
//If the line is infinite instead of a segment, use ProjectPointOnLine() instead.
static Vector3 ProjectPointOnLineSegment(Vector3 linePoint1, Vector3 linePoint2, Vector3 point){
Vector3 vector = linePoint2 - linePoint1;
Vector3 projectedPoint = ProjectPointOnLine(linePoint1, vector.normalized, point);
switch (PointOnWhichSideOfLineSegment(linePoint1, linePoint2, projectedPoint)) {
case 0:
return projectedPoint;
case 1:
return linePoint1;
case 2:
return linePoint2;
default:
//output is invalid
return Vector3.zero;
}
}
The math functions at the end are from 3d Math Functions - Unify Community Wiki
Here is how it can be used to compare a LineRenderer against another:
Array.Resize(ref lineBuffer1, lineRenderer1.positionCount);
Array.Resize(ref lineBuffer2, lineRenderer2.positionCount);
lineRenderer1.GetPositions(lineBuffer1);
lineRenderer2.GetPositions(lineBuffer2);
float diff = DifferenceBetweenLines(lineBuffer1, lineBuffer2);
const float threshold = 5f;
Debug.Log(diff < threshold ? "Pretty close!" : "Not that close...");
A few things to consider:
The performance of SqrDistanceToLine could definitely be improved on
You get a measure of how close the first line matches the second, not the other way around -- that is, the first line can be longer or go for a walk mid-way as long as it comes back on track and "covers" the other line closely enough. You can solve this by calling DifferenceBetweenLines a second time, swapping the arguments, and taking the biggest result of them two.
We could work with Vector2 instead of Vector3
Original answer:
Similar?
As #Jonathan pointed out, you need to be more precise about "similar enough":
does similarity in size matter ?
does orientation matter ?
do similarity in proportions matter (or only the "changes of direction" of the line) ?
...
As you might guess, the fewer of those criteria matter, the harder it will be; because
your concept of similarity will become more and more abstract from the raw positions
you've got in the first place.
For example, if the user needs to draw a cross, with exactly two strokes,
that cover more or less a defined area, the task is as easy as it gets:
You can measure the distance between the area's corners and each stroke's first
and last points, and check that the lines are kind of straight.
If you want to check if the user drew a perfect heart-shape, in any orientation,
it's noticeably trickier...
You might have to resort to a specialized library for that.
Another thing to consider is, does the user really need to make a line similar to another one,
or should it only be close enough that it can be differentiated from other possible lines?
Consider this example:
The user needs to draw either a cross (X) or a circle (O):
If there is only one stroke that comes back close to the starting point, assume a circle.
If there is strokes whose general directions are orthogonal, assume a cross.
In this case, a more involved system would probably be overkill.
A few "raw pointers"
Assuming simple requirements (because assuming the opposite, I wouldn't be able to help much),
here are a few elements:
Exact match
The user has to draw on top of a visible line: this is the easiest scenario.
For each point of his line, find out the distance from the closest point on the reference line.
Sum the square of those distances -- for some reason it works better than summing the distances
themselves, and it's also cheaper to compute the square distance directly.
LineRenderer.Simplify
Very specific to your use-case, since you're using Unity's LineRenderer,
it's worth knowing that it packs a Simplify(float) method, that decreases the
resolution of your curve, making it easier to process, and particularly effective
if the line to match is made of somewhat straight segments (not complex curves).
Use the angles
Sometimes you'll want to check the angles between the different sub-segments of your line,
instead of their (relative) lengths. It will measure changes in direction regardless
of the proportions, which can be more intuitive.
Example
A simple example that detects equilateral triangles:
LineRenderer.Simplify
close the shape if the ends are close enough
check the angles are ~60deg each:
For arbitrary lines, you could run the line to match through the same "filter" as the lines the user draws, and compare the values. It will be yours to decide what properties matter most (angles/distances/proportions...), and what's the threshold.
Personally I would take points along the users line and then figure out the angles on the lines and if the average angle is within a specific range then it is acceptable. If the points you draw angles from are close enough together then you should have a pretty accurate idea whether the user is close to the same line.
Also, if the line needs to be in a particular area then you can just check and make sure the line is within a specified distance of the "control" line. The math for these should be pretty simple once you have the points. I am sure there are many other ways to implement this, but I personally would do this. Hope this helps!
I would like to know how to make a smooth color lerp based on distance between 2 objects. The color should lerp from green to red to green to red... Cube far = color red, cube near = color green.
I already got everything working, but the only thinks that isn't working is the fact that the color doesn't lerp smooth. This is how it looks like at the moment.
https://i.gyazo.com/a85852e76d2418ab7d44c18e152647c0.mp4
I am using this script for the color change:
FindClosestCube ();
float lerpProgress = 0f;
GameObject cubeChildTop = null;
GameObject closestCube = FindClosestCube ();
cubeChildTop = closestCube.transform.Find("Top").gameObject;
if (cubeDiffX >= 0.8f || cubeDiffX <= -0.8f)
{
lerpProgress = 0.5f;
}
if (cubeDiffX <= 0.8f || cubeDiffX <= -0.8f)
{
lerpProgress = 1f;
}
if (cubeDiffX >= 1.6f || cubeDiffX <= -1.6f)
{
lerpProgress = 0f;
}
if(closestCube != GameObject.Find("Cube (1)2"))
{
cubeChildTop.GetComponent<Renderer>().material.color = Color.Lerp(redColor, greenColor, lerpProgress);
}
So... how do I make it lerping smooth from red to green?
This is really easy.
1.Find the max distance that you think both of those Objects can travel apart.
The first thing you need to do is determine the max distance value those two GameObjects will be apart from. You need to pass that value into the inValueMax parameter of the mapValue function fro #2.
You can determine that max value with this code:
public GameObject obj1;
public GameObject obj2;
void Update()
{
UnityEngine.Debug.Log(getSqrDistance(obj1.transform.position, obj2.transform.position));
}
public float getSqrDistance(Vector3 v1, Vector3 v2)
{
return (v1 - v2).sqrMagnitude;
}
Run it, manually move each Object/Cube then get the highest value both Objects can travel from each other with the Debug.Log message.
Looking that the video you posted I estimated that the distance value of 200 is fine for that but you still have to do your experiment with the script above if you want a perfect result.
2.Use the map to convert 0 and that MAX_DISTANCE distance range to 0f and 1f range
float mapValue(float mainValue, float inValueMin, float inValueMax, float outValueMin, float outValueMax)
{
return (mainValue - inValueMin) * (outValueMax - outValueMin) / (inValueMax - inValueMin) + outValueMin;
}
It scales values between some certain point to another.
For example, you need to use the Lerp function to do this and the Lerp function takes 0 to 1 values. The mapValue function can scale any number to range between 0 and 1 that the Lerp function need.
For me, I will scale 0 to 200 range values to 0f and 1f range with the mapValue function.
3.Finally, use Color.Lerp(near, far, lerp); to lerp between Colors. The lerp value is the result value from #2.
In Code:
Once you find #1, plug that value to the MAX_DISTANCE variable from the script below should work:
public GameObject obj1;
public GameObject obj2;
Color near = Color.green;
Color far = Color.red;
const float MAX_DISTANCE = 200;
void Update()
{
//Get distance between those two Objects
float distanceApart = getSqrDistance(obj1.transform.position, obj2.transform.position);
UnityEngine.Debug.Log(getSqrDistance(obj1.transform.position, obj2.transform.position));
//Convert 0 and 200 distance range to 0f and 1f range
float lerp = mapValue(distanceApart, 0, MAX_DISTANCE, 0f, 1f);
//Lerp Color between near and far color
Color lerpColor = Color.Lerp(near, far, lerp);
obj1.GetComponent<Renderer>().material.color = lerpColor;
}
public float getSqrDistance(Vector3 v1, Vector3 v2)
{
return (v1 - v2).sqrMagnitude;
}
float mapValue(float mainValue, float inValueMin, float inValueMax, float outValueMin, float outValueMax)
{
return (mainValue - inValueMin) * (outValueMax - outValueMin) / (inValueMax - inValueMin) + outValueMin;
}
Result:
It seems that you are confused with the concept of lerp. When you apply lerp, lerpProgress should be continous values in [0, 1] to make it change smoothly. In your caes, you are setting them to 0, 0.5, 1.0, and that's where the colour is not appearing smoothly.
Remember that lerp (linear interpolation) is summing up two values with each having different contribution ratio. So if you have Color A and Color B that you want to lerp, you are saying that I want 40% from A and 60% from B and mix them up.
How much contribution ratio each instance should have is entirely up to you, and it is where you are designing your game to be.
One way I could think of is in terms of distance. If Z is moving between X and Y, then there are two distance ratios of XZ and YZ. If Z is 40% (0.4f) toward X and 60% (0.6f) toward Z, you could take 40% of X's colour value and 60% of Y's colour value, for example.
The idea is not limited to only 2 objects, but can be extended to N objects.
Edit:
Here's an example on how you could get a ratio from only X values. In this example I am assuming two predefined values of minX and maxX.
The idea is to consider the leftX to be the starting point. If x == left.x, it returns 0, and if x == right.x, it returns 1.
float GetDistanceRatio()
{
float maxDistance = maxX - minX;
float distanceFromLeft = currX - minX;
float distanceFromLeftRatio = distanceFromLeft / maxDistance;
return distanceFromLeftRatio;
}
Consider two points: (0,0,0) as source and (1000,0,0) as target
A cube game object wants to travel from source and target at a pre-defined/constant speed. Time taken: t1
Introduce 100 intermediate points between source and target, i.e. INTERMEDIATE_POINTS = 10
Example: (0,0,0), (10,0,0), (20,0,0), (30,0,0).... (980,0,0), (990,0,0), (1000,0,0). Same speed, time taken: t2.
Introduce 50 intermediate points, i.e. INTERMEDIATE_POINTS = 20 ; (0,0,0), (20,0,0), (40,0,0),..., (960,0,0), (980,0,0), (1000,0,0). Same speed, time taken: t3.
Result: t1 < t3 < t2, i.e. more intermediate points, more time taken to reach the target (although same path and same speed)
Question: If you compare, the game object moves in the same way (same path, same speed) in all the three cases (no intermediates, 100 intermediates, and 50 intermediates) that are mentioned above. But why is there a time difference to reach the target?
Code to test this scenario:
using UnityEngine;
using System.Collections.Generic;
public class TestSpeed : MonoBehaviour
{
private List<Vector3> listOfPoints = new List<Vector3>();
private int INTERMEDIATE_POINTS = 1;
private int counter = 1;
private float speed = 50.0f;
private float originalDistance = 0.0f;
private float distanceCovered = 0.0f;
private float overshoot = 0.0f;
private Vector3 modifiedTarget;
// for the car movement.
private Vector3 targetPosition; // after every loop, get the next position
private Vector3 currentPosition;
// Use this for initialization
void Start()
{
for (int i = 0; i <= 1000; i = i + INTERMEDIATE_POINTS)
{
listOfPoints.Add(new Vector3(i, 0, 0));
}
currentPosition = this.transform.position; // at the beginning, from (0,0,0)
targetPosition = listOfPoints[counter];
}
// Update is called once per frame
void Update()
{
originalDistance = Vector3.Distance(targetPosition, currentPosition);
distanceCovered = Vector3.Distance(transform.position, currentPosition);
if(Vector3.Distance(transform.position, new Vector3(0,0,0)) >= 995.0f)
{
System.TimeSpan t = System.TimeSpan.FromSeconds(Time.timeSinceLevelLoad);
string answer = string.Format("{0:D2}:{1:D2}:{2:D2}",
t.Hours,
t.Minutes,
t.Seconds);
}
if ((originalDistance - distanceCovered) <= 0.0f)
{
currentPosition = transform.position;
targetPosition = listOfPoints[counter];
counter++;
}
else
{
float step = speed * Time.deltaTime;
if((distanceCovered + step) >= originalDistance)
{
overshoot = distanceCovered + step - originalDistance;
counter++;
modifiedTarget = Vector3.Lerp(targetPosition, listOfPoints[counter], (overshoot / originalDistance));
}
else
{
modifiedTarget = targetPosition;
}
transform.position = Vector3.MoveTowards(transform.position, modifiedTarget, step);
}
}
}
How to use the code:
Just create a cube game object and assign the script to it. Near to string answer set a break-point to check the time duration with various number of intermediate points.
I'm pretty sure this logic here is the cause of the strange observation:
if ((originalDistance - distanceCovered) == 0.0f)
{
currentPosition = transform.position;
targetPosition = listOfPoints[counter];
counter++;
}
You check whether or not you've arrived at your destination waypoint by checking for an exact position match; however, the distance you travel per Update is anything but exact. That means that your object could very well overshoot the destination, then try to move back towards it, overshoot it again, then repeat.
I bet if you watch your cube in the scene view, you'll see it hover around a single waypoint for a bit until it manages to hit the exact distance it needed.
You're probably better off using an inequality here, for example:
if ((originalDistance - distanceCovered) <= 0.0f)
{ /* ... */ }
Your object has reached its waypoint if the distance it has traveled is greater than or equal to the distance it needed to travel. originalDistance - distanceCovered will be negative as soon as the object has reached or passed the waypoint.
EDIT:
X.....X.....X.....X.....X.....X
Here are some waypoints. Pretend we have an object traveling along the path of waypoints. It starts at the first one on the left and goes right. It'll be represented by an O.
O.....X.....X.....X.....X.....X
Now it moves along for a while. Due to the variability of Time.deltaTime, it might move one or two spots each tick. So let's say it winds up here after a few ticks:
X....OX.....X.....X.....X.....X
And during the next tick, it moves two:
X.....XO....X.....X.....X.....X
With your original check, the object will now travel backwards. It needed to travel a distance of seven spaces, but it traveled 8. So with your original check, originalDistance - distanceCovered != 0.0f. So it'll keep trying to hit that spot over and over again until it hits it on the dot.
Even if you introduce the idea of a "threshold", you're still going to have the same problem. There is no fixed distance traveled per tick, so that means that each waypoint will have some artificial "bounce" time unless that threshold is so large that the waypoints become meaningless.
If you use originalDistance - distanceCovered <= 0.0f, you will always move on to the next waypoint if it overshoots. Instead of trying to land the object in some small window, you're just making sure that the object has passed or met its waypoint.