# Getting angle from current position and next position

I am using pathfinding to move a train along rails, but I need the train to rotate. I have the next intended position and the current position at my disposal, how would I go about this? Pseudocode will do as an answer since I am using a specialized programming language for the engine that I use.

• You mean the angle of intersection between two lines? (first line is previews point and current, second line is current point and next point) Oct 7 '20 at 6:58
• Are you looking for the Atan2 function, that converts a direction vector to a heading angle? Oct 7 '20 at 12:43

This is a prototype lookat function , in which an object forward will point towards a defined position. In your case the Up vector can be set to fixed value since the object does not need to pitch up or down. Hope this helps

  //your object
glm::vec3 obPos = glm::vec3(sceneEntity->getPostion().x(),sceneEntity->getPostion().y(),sceneEntity->getPostion().z());

//Next positon
glm::vec3 tarPo = glm::vec3(ptl.x(),ptl.y(),ptl.z());

glm::vec3 delta = tarPo - obPos;//targetPosition-objectPosition
glm::vec3 up;
glm::vec3 dir(glm::normalize(delta));

if(abs(dir.x) < 0.00001 && abs(dir.z) < 0.00001){
if(dir.y > 0)
up = glm::vec3(0.0, 0.0, -1.0); //if direction points in +y
else
up = glm::vec3(0.0, 0.0, 1.0); //if direction points in -y
} else {
up = glm::vec3(0.0, 1.0, 0.0); //y-axis is the general up
}
up = glm::normalize(up);
glm::vec3 right = glm::normalize(glm::cross(up,dir));
//up = glm::normalize(glm::cross(dir, right));

rotationMatrix *= glm::mat4(right.x, right.y, right.z, 0.0f,
up.x, up.y, up.z, 0.0f,
dir.x, dir.y, dir.z, 0.0f,
obPos.x, obPos.y, obPos.z, 1.0f);

• I'm interested as to why you recalculate the up direction after calculating the right direction using the up and dir directions Mar 9 at 11:04
• Good catch , this was part of my algo tools code , I don't remember exactly why, but knowing me , i might have put it there to check if the up vector coming out is the same as what i put in , in a way validating that step(put a break point there and validate) , whiteout having to do the math on paper for each iteration with update values.. I should have commented it out . Thanks Mar 12 at 13:23