I have a scenario where I’ve an origin point and an end point provided by the user (effectively arbitrary). Now I need to “travel” down this line segment performing an action at every arbitrary distance. Since I have a distance per step and direction traveling down the line is easy, but how do I build the loop so that when my current position on the line is after the end point I stop.
Some sudo code to demonstrate the issue (what goes in the while loop):
float distance = 1.234f;
Vector2 origin = Vector2.zero;
Vector2 end = new Vector2(100f, 159f);
Vector2 vectorDirection = (end - origin).normalized;
Vector2 moveStep = vectorDirection * distance;
Vector2 p = origin + moveStep;
while (?????) {
//do something
p += moveStep;
}
One way to do this is to keep track of the total distance traveled and stop when that distance exceeds the length of the line segment. You can calculate the length of the line segment using the distance formula, which is the square root of the sum of the squares of the differences between the x-coordinates and the y-coordinates of the endpoints. Here’s an example of how this can be implemented in your code:
float distance = 1.234f;
Vector2 origin = Vector2.zero;
Vector2 end = new Vector2(100f, 159f);
Vector2 vectorDirection = (end - origin).normalized;
Vector2 moveStep = vectorDirection * distance;
Vector2 p = origin + moveStep;
// Calculate the length of the line segment
float lineLength = Mathf.Sqrt(Mathf.Pow(end.x - origin.x, 2) + Mathf.Pow(end.y - origin.y, 2));
// Keep track of the total distance traveled
float totalDistance = distance;
// Keep looping until the total distance traveled exceeds the length of the line segment
while (totalDistance < lineLength) {
// Do something
// Move to the next position
p += moveStep;
// Update the total distance traveled
totalDistance += distance;
}
Aytgancha, siz mostbet ga qarashingiz mumkin, chunki hozirda juda ko’p ajoyib takliflar va bonuslar mavjud. Menga juda yoqadi, chunki bu men uchun juda foydali. Bu yerda mobil ilova borligi va istalgan joyda pul tikishim qulayligi menga juda yoqdi