Hello,
I want to create a chain type effect, so when I click and drag from my scene, spheres will line them selves up from where I initially clicked, to where I have dragged to.
I’ve achieved this by using three spheres:
- One for the starting marker (so where I initially clicked)
- One for the ending marker (so where my mouse position is currently)
- And a sphere for the middle point.
The problem is now, is that I want to have multiple middle points. So instead of 1 middle sphere, I want to have 3. And I want them to line up perfectly between the starting marker and the finishing marker:
if(Input.GetButton("Fire1")){
isDragging = true;
end.position = hit.point;
//middle.position = (end.position / 2) + (start.position / 2);
for(var m = 0; m < middles.length; m++){
middles[m].position = ((end.position * m / 2) + (start.position * m / 2));
}
}
Thanks
Well just take one position from the other, then multiply that difference by a number between 0 and 1 to get that interval and add on the lower value.
var difference = start - end;
var quarterPoint = start + difference * 0.25f;
var midPoint = start + difference * 0.5f;
This is quite an old post but if anyone stumbles across this like I did, Unity has a built-in method for exactly this!
The [Mathf.Lerp][1] method allows you to indicate a start and end value, and then give it a decimal percent for where between these two points you’re interested in.
For implementing what OP was interested in, this would mean doing:
for(var i = 1; i < numberOfSpheres + 1; i++) {
float decimalPercent = i / (numberOfSpheres + 1);
middles*.position = Mathf.Lerp(start.position, end.position, decimalPercent);*
}
----------
The numberOfSpheres + 1
is needed within the loop declaration and when calculating decimal percent since for any x number of spheres being created, there will be x+1 gaps between spheres.
----------
This can be visualized by the following:
If we have an example 1D space where we’re interested in creating spheres between the two points:
START: ------------------------------------------------------ :END
And for example we want to draw 4 spheres between the start and end points, it would look like this:
START: ----------O----------O----------O----------O---------- :END
So 4 spheres were created between the points, but 5 gaps were also created between these spheres, so this extra increment is needed to account for this,
[1]: Unity - Scripting API: Mathf.Lerp