Hello to everyone. How can I position the object between two points so that when I move the points the object rests on the line. I made the angular calculation of the object, but I could not find what code to write about its position. please help me. 2 picture added commend. please look at pictures
The codes I wrote for the angle:
public GameObject node1, node2;
Vector3 dir1 = (node1.transform.position - node2.transform.position);
float atan2_1 = Mathf.Atan2(dir1.y, dir1.x);
transform.rotation = Quaternion.Euler(0f, 0f, atan2_1 * Mathf.Rad2Deg);
I would start by getting the direction between the two points:
Vector3 direction = node2.transform.position - node1.transform.position;
direction.Normalize();
Now you can move along the line by adding the direction vector to the starting node position
//Move 1 unit along the line
transform.position = node1.transform.position + direction;
You can multiply the direction by whatever distance you want to move along the line.
//Move 5 units along the line
transform.position = node1.transform.position + 5*direction;
If you want to move a certain percentage of the length of the line, Vector3.Lerp is a good shortcut
//Move 30% of the way down the line
transform.position = Vector3.Lerp(node1.transform.position, node2.transform.position, 0.3f);
If you want to move along the line smoothly, use one of the above methods but just do a tiny amount each frame
void Update(){
transform.position = transform.positon + direction * speed * Time.deltaTime;
}
thank you @unity_ek98vnTRplGj8Q this code is works!!!
public float distanceBetweenNodes;
Update()
{
transform.position = Vector3.Lerp(node1.transform.positon, node2.transform.position, distanceBetweenNodes);
distanceBetweenNodes = Vector3.Distance(transform.positon, node1) / Vector3.Distance(node1, node2);
}