By default, ue4 sets the camera in the defaultpawnclass object in agamemode as the default camera. Sometimes we want a global camera to observe the scene, which requires re-creating a camera and directly switching between the two cameras. The following describes how to implement it.
In the aplayercontroller class, there is a setviewtarget method. The parameter is an aactor pointer, which implements this function. Because the parameter must be aactor, that is, it must be the camera component contained in the aactor to be valid. For all, create an aactor object first.
Freecameraactor. h
Uclass ()
Class nantopdown_api afreecameraactor: Public aactor
{
Generated_uclass_body ()
Public:
Uproperty (visibleanywhere, blueprintreadonly, Category = camera)
Tsubobjectptr <class ucameracomponent> topdowncameracomponent;
Ufunction (blueprintcallable, Category = "view target ")
Void changeviewtarget ();
Virtual void beginplay () override;
PRIVATE:
Aactor * oldactor;
};
The changeviewtarget () method is provided to blueprint for switching between camera and freecamera of character.
Freecameraactor. cpp
Afreecameraactor: afreecameraactor (const class fpostconstructinitializeproperties & PCIP)
: Super (PCIP)
{
Topdowncameracomponent = PCIP. createdefadefasubobject <ucameracomponent> (this, text ("topdowncamera "));
This-> rootcomponent = topdowncameracomponent;
Oldactor = NULL;
}
Void afreecameraactor: changeviewtarget ()
{
Aactor * pactor = This-> getworld ()-> getfirstplayercontroller ()-> getviewtarget ();
If (pactor! = Oldactor)
{
This-> getworld ()-> getfirstplayercontroller ()-> setviewtarget (oldactor );
}
Else
{
This-> getworld ()-> getfirstplayercontroller ()-> setviewtarget (this );
}
}
Void afreecameraactor: beginplay ()
{
Super: beginplay ();
Oldactor = This-> getworld ()-> getfirstplayercontroller ()-> getviewtarget ();
This-> getworld ()-> getfirstplayercontroller ()-> setviewtarget (this );
}
In the editor, create an actor inherited from afreecameraactor and drag and drop it to the scene. You can see an object that contains the camera. Then edit level blueprint and add the script code.
In the play scenario, press the 1 key to see the camera switch between character and the new camera.
Unreal Engine 4 switch default camera implementation