- Home /
How To Calcutale New Position and Angle On The Line Objects
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);
@dirilikerhan355 Consider using Vector3.Lerp between your start and end point; the third parameter, t, defines the interpolant distance between 0 (start) and 1 (end), so would be scaled appropriately.
Answer by dirilikerhan355 · Mar 12, 2020 at 04:05 PM
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); }
Answer by unity_ek98vnTRplGj8Q · Mar 11, 2020 at 08:09 PM
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;
}
Re-reading you question I think maybe you want the object to maintain its position along the line even while you move the points? If this is the case, Vector3.Lerp is def the way to go, just keep track of how far you were between the nodes
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);