Delphi 3D – Align Camera to Origin

While the Camera used in the IDE the “Design Camera” always points to the origin [0,0,0] because of the way it is created any arbitrary camera created at any position on the form could point anywhere. It was useful to provide a routine to automate this process.

A library routine AngleToToOrigin provided in my unit “ThreeDUtils” achieves this.

Function AngleToToOrigin(APos: TPoint3D): TPoint3D;
Var
  SinA, CosA: Double;
  CurPoint, CurYPt, CurXpt, CurAngle: TPoint3D;
  Hyp, HypR1: single;

begin
  CurPoint := APos;
  Hyp := CurPoint.Length;
  if CurPoint.Z <= 0 then
  // Align to X axis then dip
  begin
    CurXpt := CurPoint;
    CurXpt.X := 0;
    HypR1 := CurXpt.Length;
    CurAngle.X := ToDegree(ArcSin(CurPoint.Y / HypR1));
    CurAngle.Y := ToDegree(ArcSin(-CurPoint.X / Hyp));
    CurAngle.Z := 0;
  end
  else
  begin
    CurXpt := CurPoint;
    CurXpt.X := 0;
    HypR1 := CurXpt.Length;
    CurAngle.X := ToDegree(Pi - ArcSin(CurPoint.Y / HypR1));
    CurAngle.Y := ToDegree(ArcSin(-CurPoint.X / Hyp));
    CurAngle.Z := 0;
  end;
  Result := CurAngle;
end;

By calling this code as part of the TMovingCamera.create the viewport is initially aligned with the
origin.

procedure TFlyingCamera.AlignCammeraToOrigin;
begin
   RotationAngle.Point:=AngleToToOrigin(Position.Point);
   UpdateHeadUpDisplay;
end;

It is interesting (and concerning) that calling this same code after panning the camera though a wide range using the control keys this function no longer brings the origin into the “Gun Sight”.

If you want to try this add the line

          'o','O':AlignCammeraToOrigin;

to the published TFlyingCamera.FmCamera3DKeyDown case statement.

Leave a Reply

Your email address will not be published. Required fields are marked *