C++ Programming Tutorials_2翻譯



所在原文目錄結構位置:

C++ Programming Guide

 |_____Programming Quick Start Guide

 |_____Introduction to C++ Programming in UE4

 |_____C++ Programming Tutorials

 |_____Managing Game Code

 |_____Development Setup

 |_____Gameplay Programming

 |_____Engine Architecture

 |_____Console Manager: Console Variables in C++

 |_____Command-Line Arguments

 |_____Assertions

 |_____Blueprint Function Libraries

 |_____Unreal Build System

 |_____Plugins

 |_____Coding Standard

 |_____Symbol Debugger


原文地址:Programming Tutorials


-------------------------------------------------------------------------------------------------------------------------------------------------------


C++ Programming Tutorials

C++編程教程


1.Player Input and Pawns 玩家輸入和Pawn(個人感覺Pawn是副角色,配角) 

 見譯文:  C++ Programming Tutorials_1 

2.Game-Controlled Cameras 遊戲控制攝像機

This tutorial will show you how to activate a camera, and change your active camera from one to another.

本教程將展示如何激活一個攝像機,還有,切換活動的攝像機


Steps 步驟:

    1.Place Cameras In The World 在世界中放置攝像機們

          !!!If you are new to Unreal Engine 4, you might want to read ourProgramming Quick Start tutorial first. For this tutorial, we will assume you are familiar with creating a project, adding C++ code to it, compiling your code, and adding Components to Actors in the Unreal Engine editor.

           !!!如果是新手,請先看前面的譯文.

           ①We will begin by creating a new Basic Code project, with starter content, named "HowTo_AutoCamera". The first thing we'll need to do is create two cameras in our world. Since there are multiple ways to set up cameras, we'll go with the two most common ways here. For our first camera, go to the Modes tab in the Placement Browser and click Place, or press Shift-1. In the All Classes section, you'll find a Camera actor. Drag this into the Level Editor and position it so that it has a good view of our scene.

              我們從創建一個新的 C++基礎代碼項目 開始,項目命名爲"HowTo_AutoCamera". 首先,我們要在世界中創建兩個攝像機.有多種方式創建攝像機們,我們這兒用兩種常見的方式來創建.第一個攝像機,找到Placement Browser(佈局瀏覽器) 下的Modes(模式)標籤,點擊放置,或者按Shift-1(不知道Shift-1是什麼). 在All Classes (所有類)部分,你會找到Camera(相機)


       When this is done, the Level Editor window will have a picture-in-picture view of what our new Camera Actor can see as long as we have the Camera Actor selected.

        做到這兒,關卡編輯器窗口會有攝像機對象看到的畫中畫

       ②For our second camera, we'll use a method that goes a little more in-depth and gives us a little more control. Start by clicking on Basic in the Mode tab in the Placement Browser and dragging a Cube into the Level Editor window.

         至於我們第二個攝像機, 我們將使用一個更深入的方法,給我們更多的控制,找到Placement Browser (放置瀏覽器),找到Modes標籤下Basic(基本)中的Cube(方塊),把方塊拖進關卡編輯器窗口中

 

            !!!We can use almost any actor class for this step. The MyActor class we created in the QuickStart tutorial might be interesting to substitute for the Cube.

            !!!這一步我們能用絕大多數的actor類.在QuickStart 教程中我們創建的MyActor 類是對這個Cube的替代品

           ③When our Cube actor is placed, we should add a CameraComponent to it, and set the position and rotation of that CameraComponent to give us a different view of the scene than the CameraActor we placed earlier.

           當我們的Cube對象放置好,我們需要爲它增加一個CameraComponent (相機組件),設置位置和旋轉以便相機組件給我們不同於原先的畫面.

          ④We should customize our CameraComponent by turning on Constrain Aspect Ratio so that it matches the setting on our CameraActor. This will make transitions between camera views smoother, but it is not required.

           我們需要打開限制長寬比來設定我們的相機組件,這樣它與我們的CameraActor相匹配.這將使相機視圖之間流暢的過渡,但這不是必需的

           設置比率


        With our world set up, we're now ready to create the class that will control our camera view.

        我們創建好了世界,我們現在已經能創建類來控制我們的攝像機了.


     2.Control Camera View In C++ 在C++中控制攝像機的視角

            ①We're ready to create a C++ class to control our camera view. For this tutorial, we can extend Actor into a new class which we'll call CameraDirector.

              創建類控制相機,本教程,我們可以擴展Actor 到一個新的類,我們叫CameraDirector。

             ②InCameraDirector.h, add the following code to the bottom of the ACameraDirector class definition:

                在CameraDirector.h中,在ACameraDirector類定義的最後,添加如下代碼:

UPROPERTY(EditAnywhere)
AActor* CameraOne;

UPROPERTY(EditAnywhere)
AActor* CameraTwo;

float TimeToNextCameraChange;


       !!!The UPROPERTY macro makes our variables visible to Unreal Engine. This way, values set in these variables will not be reset when we launch the game or reload our level or project in a future work session. We have also added the EditAnywhere keyword, which will allow us to set CameraOne and CameraTwo in the Unreal Editor.

       !!!UPROPERTY 宏讓變量在虛幻中可見,通過這種方式,這些設置的變量當我們以後啓動遊戲,重裝載關卡也不會被重置,我們也加了EditAnywhere 這個關鍵字,這允許了虛幻編輯器能對該兩個變量做修改了.

       ③In CameraDirector.cpp, add the following line of code to the top of the file, right underneath the other "#include" lines:

        在CameraDirector.cpp中,添加如下頭文件

     

#include "Kismet/GameplayStatics.h"


       The GameplayStatics header file gives us access to some useful general-purpose functions, one of which we will need for this tutorial. When that is done, add the following code to the bottom of ACameraDirector::Tick:

       這個頭文件給了我們一些有用的通用函數,其中一個我們本教程需要,這步做完,在ACameraDirector::Tick底部添加如下代碼:


const float TimeBetweenCameraChanges = 2.0f;
const float SmoothBlendTime = 0.75f;
TimeToNextCameraChange -= DeltaTime;
if (TimeToNextCameraChange <= 0.0f)
{
    TimeToNextCameraChange += TimeBetweenCameraChanges;

    // Find the actor that handles control for the local player.
    APlayerController* OurPlayerController = UGameplayStatics::GetPlayerController(this, 0);
    if (OurPlayerController)
    {
        if ((OurPlayerController->GetViewTarget() != CameraOne) && (CameraOne != nullptr))
        {
            // Cut instantly to camera one.
            OurPlayerController->SetViewTarget(CameraOne);
        }
        else if ((OurPlayerController->GetViewTarget() != CameraTwo) && (CameraTwo != nullptr))
        {
            // Blend smoothly to camera two.
            OurPlayerController->SetViewTargetWithBlend(CameraTwo, SmoothBlendTime);
        }
    }
}

This code will cause us to switch the default player's view between two different cameras every three seconds.

這段代碼將使我們每三秒在兩個攝像機之間切換


完整代碼:

CameraDirector.h

// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once

#include "GameFramework/Actor.h"
#include "CameraDirector.generated.h"

UCLASS()
class HOWTO_AUTOCAMERA_API ACameraDirector : public AActor
{
    GENERATED_BODY()

public: 
    // Sets default values for this actor's properties
    ACameraDirector();

    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

    // Called every frame
    virtual void Tick( float DeltaSeconds ) override;

    UPROPERTY(EditAnywhere)
    AActor* CameraOne;

    UPROPERTY(EditAnywhere)
    AActor* CameraTwo;

    float TimeToNextCameraChange;
};

CameraDirector.cpp

// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#include "HowTo_AutoCamera.h"
#include "CameraDirector.h"
#include "Kismet/GameplayStatics.h"//裏面有一些有用的通用函數

// Sets default values
ACameraDirector::ACameraDirector()
{
    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

}

// Called when the game starts or when spawned
void ACameraDirector::BeginPlay()
{
    Super::BeginPlay();

}

// Called every frame
void ACameraDirector::Tick( float DeltaTime )
{
    Super::Tick( DeltaTime );

    const float TimeBetweenCameraChanges = 2.0f;
    const float SmoothBlendTime = 0.75f;
    TimeToNextCameraChange -= DeltaTime;
    if (TimeToNextCameraChange <= 0.0f)
    {
        TimeToNextCameraChange += TimeBetweenCameraChanges;

        //Find the actor that handles control for the local player.//找到這個actor
        APlayerController* OurPlayerController = UGameplayStatics::GetPlayerController(this, 0);
        if (OurPlayerController)
        {
            if ((OurPlayerController->GetViewTarget() != CameraOne) && (CameraOne != nullptr))
            {
                //Cut instantly to camera one.//直接切換到相機1
                OurPlayerController->SetViewTarget(CameraOne);
            }
            else if ((OurPlayerController->GetViewTarget() != CameraTwo) && (CameraTwo != nullptr))
            {
                //Blend smoothly to camera two.//平滑地切換到相機2
                OurPlayerController->SetViewTargetWithBlend(CameraTwo, SmoothBlendTime);
            }
        }
    }
}


    3. Place A Camera Director In The World  在世界中放置一個主導攝像機

           ①Once our code has compiled, we can drag an instance of our new class from the Content Browser into the Level Editor.

            編譯好代碼後,我們把CameraDirector拖進遊戲關卡中,這就創建了一個實例了

               ②Next, we'll need to set the CameraOne and CameraTwo variables. Find our CameraDirector in the World Outliner and edit it in the Details Panel.

                下面,我們需要設置CameraOne 和CameraTwo 這兩個變量.在World Outliner (世界大綱視圖)中找到我們的實例,然後編輯:

然後編輯


          ③If we press Play, we will see the camera snap to this view:

           按Play,觀察效果圖:


We now have a system that moves the player's camera based purely on game logic. This code can be modified for use in any game where the player does not have direct control over the camera, or where blending between camera views is useful.

現在我們有一個基於遊戲邏輯控制玩家攝像機移動切換的系統了,這些代碼能被修改用於一些玩家沒有直接控制相機的遊戲,或者對混合攝像機視圖方面非常有用的.


     4.On Your Own! 你自己做!

Using what you have learned, try to do the following:

學以致用,做下面的事情.

  • Attach a Camera to a moving Actor to create a crane or dolly shot.

  • 爲運動的對象添加攝像頭,從而創建一個吊杆或移動攝影車

  • Use a single array variable to store your cameras, instead of CameraOne and CameraTwo, so you can go through a sequence of any number of cameras, instead of just two.

  • 用一個數組保存你的攝像機們,而不是相機1,相機2,因此你能遍歷攝像機們的序列表,而不是僅僅兩個.

  • Instead of using Actor pointers to store your cameras, create a structure that holds the pointer, as well as time before changing the view, and blend time to the new view.

  • 用保存Actor的指針和改變之前的時間 和混合時間的結構體,而不用Actor指針來保存你的相機們

As for the specifics covered in this tutorial:

本節教程的詳細介紹:

//以下代碼爲本人的作業,僅供參考

      --------------------------------解決第一個: 運動的攝像頭的問題--------------------------------

步驟:1.打開player類 ,添加

            UPROPERTY(EditAnywhere)
            AActor* CameraOne;

         2.UE編輯器中,綁定動態物體到CameraOne

         3.在Tick每幀更新這個函數中,設置CameraOne爲主相機:


//獲取此player
APlayerController* OurPlayerController = UGameplayStatics::GetPlayerController(this, 0);
if (OurPlayerController)
{
	if ((OurPlayerController->GetViewTarget() != CameraOne) && (CameraOne != nullptr))
	{
		// 設置CameraOne爲主相機
		OurPlayerController->SetViewTarget(CameraOne);
	}
}

--------------------------------解決第二個: 數組保存相機們的問題--------------------------------

用數組代替上面的.

然後就可以添加任意多個相機了.

當然,程序中CameraOne  要用下標的形式訪問,變成m_Cameras[0];CameraTwo變成m_Cameras[1]

(數組下標從0開始)


--------------------------------解決第三個: 用結構體保存數據的問題--------------------------------

解:定義一個結構體嘛,誰不會.但是我爲什麼三天都做不出來呢???

定義的結構體如圖所示:

好,分分鐘定義好結構體,可是,我擦咧,怎麼編譯不過?

因爲本人習慣看錯誤列表,所以,我看到的是這樣的:

爲了解決這個問題,我拜訪了很多羣,親口嘗過百草,未能解決,後來三巫社區的三叔找到了問題的本質.

修改了下,注意看好:

struct CameraAndTime
{
	GENERATED_BODY()

	UPROPERTY(EditAnywhere,BlueprintReadOnly,Category = "Myct")
	AActor*	camera;		//攝像機
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Myct")
	float	showTime;	//攝像機顯示的時間
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Myct")
	float	blendTime;	//相機混合的時間
};

這樣就編譯不過!!!


struct FCameraAndTime
{
	GENERATED_BODY()

	UPROPERTY(EditAnywhere,BlueprintReadOnly,Category = "Myct")
	AActor*	camera;		//攝像機
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Myct")
	float	showTime;	//攝像機顯示的時間
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Myct")
	float	blendTime;	//相機混合的時間
};

這樣就編譯過了!!!

看到上面兩段代碼的區別沒?(坑爹啊...注意結構名!!!)

UE4連名字都不讓隨便取,這不是武則天麼?下面是UE4家族的姓.

(都不好意思說這個問題坑了我三天了...)

好了,結構體定義完了,在裏面添加

class HOWTO_AUTOCAMERA_API ACameraDirector : public AActor
{
 GENERATED_BODY()

UPROPERTY(EditAnywhere, Category = "My")
 TArray<FCameraAndTime> CameraTimes;

 int CameraIndex; //相機索引
 float ShowTimeAdd; //顯示了多少時間?

}

在構造函數中,CameraIndex = 0;//從第一個相機開始

ShowTimeAdd = 0.0f;//顯示的時間累加

我們的目的就是:每個攝像機顯示自己的showTime時間後,花blendTime時間切換到下一個攝像機,如此循環

那麼,在循環函數Tick中添加如下代碼:

void ACameraDirector::Tick( float DeltaTime )
{
	Super::Tick( DeltaTime );

	//獲取player
	APlayerController* OurPlayerController = UGameplayStatics::GetPlayerController(this, 0);

	if (CameraTimes[CameraIndex].camera != NULL)//如果相機不爲空
	{
		if (ShowTimeAdd >= CameraTimes[CameraIndex].showTime)//如果顯示的時間到了 該相機要顯示的時間
		{
			CameraIndex++;//切換到下一個(相機)
			if (CameraIndex >= CameraTimes.Num())//如果已經是最後一個相機
				CameraIndex = 0;				 //切換到第一個相機

			if (CameraTimes[CameraIndex].camera != NULL)//如果相機不爲空
			{
				OurPlayerController->SetViewTargetWithBlend(CameraTimes[CameraIndex].camera, CameraTimes[CameraIndex].blendTime);//切換活動的相機
				ShowTimeAdd = 0.0f;//時間清0
			}
			else                                        //相機爲空 
			{
				CameraIndex++;
				if (CameraIndex >= CameraTimes.Num())
					CameraIndex = 0;

				ShowTimeAdd = 0.0f;
			}		
		}
		else 
		{
			ShowTimeAdd += DeltaTime;//累加時間
		}
	}
	else    //相機爲空
	{
		CameraIndex++; //下一個(相機)
		if (CameraIndex >= CameraTimes.Num())//如果已經是最後一個相機
			CameraIndex = 0;				 //切換到第一個相機

		ShowTimeAdd = 0.0f;//混合時間清0
	}
}

編譯,在UE4裏面添加三個攝像機指定好Camera,設定好時間

第一個參數:攝像機

第二個參數:攝像機顯示多少秒後切換

第三個參數:需要多少時間來平滑過度切換

好了,最終效果就會在攝像機之間一直切換鏡頭了.

-------------------------------------------------------------------------------------------------------------------

3.Variables, Timers, and Events 變量,定時器和事件

4.Player-Controlled Cameras 玩家控制攝像機

5.Components And Collision 組件和碰撞



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章