In my game, I have a ball at the center of the screen. When the user clicks and drags anywhere on the screen, a line is drawn from the center of that ball to wherever the mouse is. I’d like to make it so that more balls are spawned along that line. Any idea how that can be done? All I have so far is the code to draw the line, which is attached to the Ball script:
using UnityEngine;
public class Ball : MonoBehaviour
{
private LineRenderer line;
void Start()
{
line = GetComponent<LineRenderer>();
}
void Update()
{
if (Input.GetMouseButton(0))
{
line.SetPosition(0, transform.position);
line.startWidth = .05f;
line.endWidth = .05f;
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
line.SetPosition(1, mousePos);
}
else
{
line.startWidth = 0;
line.endWidth = 0;
}
}
}
Figure out how many balls will fit on the line based on the spacing desired and the distance:
int howManyBalls = (int) distance / spacing;
Then place your balls:
//get direction
Vector3 direction = (clickPos - ballPos).normalized;
//make an array for balls
GameObject [] balls = new GameObject [howManyBalls];
for(int i = 0; i < howManyBalls; i++)
if(i == 0) { newSpacing = spacing; }else{ newSpacing = spacing * i; } balls_.transform.position = ballPos + (direction * newSpacing);_ } I didn’t test the code, but should be ok. Hope that helps.
Because MoveTowards returns target on the last run, the last two items may be closer than others. So you’d want to define whether it is fine like this or last is skipped or should you have an even distance between each item, then you’d take the distance between (end - start).magnitude and divide by how many items.
It all depends on what you want to do.
You can even draw them over time with a coroutine:
@sean244 If you want to make the balls evenly spaced along the line I would go ahead and try something like this
`
float numberOfBalls = 10;
float distance = Vector3.Distance(Vector3.zero, transform.position)
Vector3 dir = transform.position.normalized;