LookAt / Target property or function for camera or any TCastleTransform

I would say that we give you here the building blocks to make it easy:

  • Set the Direction (or Rotation, or use SetView or WorldSetView) on any TCastleTransform as often as you’d like.

  • Do stuff from Update methods (overridden in view, or in particular TCastleTransform or in behavior).

Indeed, behaviors that you mentioned would be my recommendation in many cases. In the simplest case, define a behavior like this:

type
  TLookAtBehavior = class(TCastleBehavior)
  public
    Target: TCastleTransform;
    procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType);   override;
  end;

procedure TLookAtBehavior.Update(const SecondsPassed: Single; var RemoveMe: TRemoveType);
begin
  inherited;
  // Note: No need to normalize direction, it will be done on the engine side.
  Parent.WorldDirection := Target.WorldTranslation - Parent.WorldTranslation;
end;

Add a new instance of this class to the TCastleTransform that should act as an “observer” . This can be anything, including a camera, since TCastleCamera is also a descendant from TCastleTransform. Like

procedure TMyView.Start;
var
  LookAtBehavior: TLookAtBehavior;
begin
  inherited;
  LookAtBehavior := TLookAtBehavior.Create(FreeAtStop);
  LookAtBehavior.Target := SomeTarget;
  Observer.AddBehavior(LookAtBehavior);
end;

This is simplest, and assumes that the Up vector of the observer is already good. If not, you can adjust it, once and/or each frame.

I think above can be extended / modified for a particular use-case, so it’s OK that we don’t explicitly provide such behavior ready in the engine, instead giving you “building blocks” to do it on your side… Hm, but it’s a very good example for behaviors! I have added it to Behaviors | Manual | Castle Game Engine docs :slight_smile:

2 Likes