rotationgame-engineunreal-engine4quaternionsverse

What are the algorithmic steps to find the Look At Rotation between two points?


I want to SLERP the rotation of ObjectA toward the position of ObjectB over a period of time.The interpolation I have working, what I can't figure out is how to produce the DestinationRotation (the Look to Rotation, or rotation ObjectA needs to eventually reach)

What are the steps to accomplish that?

What I have available:

  1. vector3 rotation of both objects
  2. vector3 position of both objects
  3. vector3 axis of both objects
  4. Angle of each object
  5. Dot product of position X,Y between both objects
  6. Euclidean distance between two vectors
  7. Local up vector of each object
  8. Local forward vector of each object

How do I calculate the Look to Rotation?

Note: This is the Verse programming language using Unreal Engine spatial math libraries, but my problem isn't code as much as knowing which tools (math) to use in which order.

loop:
        Sleep(0.0)
        CurrentTime := GetSimulationElapsedTime()
        DeltaTime := CurrentTime - PreviousTime
        set PreviousTime = CurrentTime
        var MoveToPosition : vector2 = vector2{X := 0.0, Y := 0.0}

        # Player Current Position
        if (Agent := agent[Player], FortChar := Agent.GetFortCharacter[], Trans := FortChar.GetTransform(), Position := Trans.Translation):
                set MoveToPosition = vector2{X := Position.X, Y := Position.Y}
        
        SpiderTrans := Spider.GetTransform()
        SpiderVec := SpiderTrans.Translation
        CurrentSpiderRotation := SpiderTrans.Rotation
        CurrentSpiderPos := vector2{X := SpiderVec.X, Y := SpiderVec.Y}
        DeltaSpeed := SpiderSpeed * DeltaTime
        NewPos := Lerp(CurrentSpiderPos, MoveToPosition, DeltaSpeed)
        
        FinalMoveVector := vector3{X := NewPos.X, Y := NewPos.Y, Z := SpiderVec.Z}
       
        # This is where my rotation gets wonky
        DP := DotProduct(CurrentSpiderPos, MoveToPosition)
        var NewRotation : rotation = CurrentSpiderRotation.ApplyLocalRotationZ(DP)
        if (set NewRotation = Slerp[CurrentSpiderRotation,NewRotation, SpiderSpeed]) {}

        # Movement works fine, but rotation is all over the place
        if (Spider.TeleportTo[FinalMoveVector, NewRotation]) {}

Solution

  • Get the position vectors and subtract them.

    enter image description here

    You will get a Vector Pointing from B to A, Normalize it and use that as your rotation destination.

    Edit: Note that vector magnitude before the normalization will represent the Distance, so dont Normalize it if you want it for some reason.