I’m completely lost on how to start tackling this problem. I want to instantiate segments of a rope between two points, as well as having the ropes face each other, as if they were connected (like the ends are touching) and every 0.5 (as this is the size of one rope segment) instantiate another segment of rope until it reaches the player.
I have no clue on how to:
- Figure out how to get this “line” between two points.
- Calculate the angle the rope segments should face so they lay in a line between the two points.
Fortunately, I do know how to place them every 0.5 units between on the line and attach it to the character when it is less than 0.5 units away.
To instantiate the objects between 2 points you could use Vector3.Lerp, this is an example of how you could do it:
public GameObject ropePrefab;
Vector3 pointA;
Vector3 pointB;
Vector3 instantiatePosition;
float lerpValue;
float distance;
int segmentsToCreate;
void InstantiateSegments()
{
//Here we calculate how many segments will fit between the two points
segmentsToCreate = Mathf.RoundToInt(Vector3.Distance(pointA, pointB) / 0.5f);
//As we'll be using vector3.lerp we want a value between 0 and 1, and the distance value is the value we have to add
distance = 1 / segmentsToCreate;
for(int i = 0; i < segmentsToCreate; i++)
{
//We increase our lerpValue
lerpValue += distance;
//Get the position
instantiatePosition = Vector3.Lerp(pointA, pointB, lerpValue);
//Instantiate the object
Instantiate(ropePrefab, instantiatePosition, transform.rotation);
}
}
So here we calculate how many segments will fit between the two points, then calculate the distance between those taking pointA as 0 and pointB as 1, then we use that value to increase the lerpValue used for the Vector3.Lerp towards 1.
In case your game is in two dimensions you only need to change all the Vector3 by Vector2.
Regarding to the rotation, if it’s a 3D game you could try transform.LookAt(), If it’s a 2D game you could use the trigonometric functions to calculate the angle between pointA and pointB and give all the segments that rotation.
PS: I haven’t tried the code so it may not work at the beginning.
I believe something like this would work.
note i did not add rotation on creation, but all you have to do is face it to ether pointA or Point B on creation
public class Test : MonoBehaviour {
public Transform PointA;
public Transform PointB;
public float NumberOfSegments=3;
public float AlonThePath=.25f;
// Update is called once per frame
void Start () {
//get distance
Creat ();
}
void Creat(){
NumberOfSegments += 1;// since we are skiping 1st placement since its the same as sytarting point we increase thsi number by 1
AlonThePath = 1/(NumberOfSegments);//% along the path
for(int i = 1; i < NumberOfSegments; i++)
{
Vector3 CreatPosition = PointA.position + (PointB.position - PointA.position)* (AlonThePath*i);
GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Cube);
sphere.transform.position = CreatPosition;
}
}
}