UE4 Character 人物移动和摄像头的旋转

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "SCharacter.generated.h"

class UCameraComponent;
class USpringArmComponent;

UCLASS()
class TSHOOTERGAME_API ASCharacter : public ACharacter
{
	GENERATED_BODY()

public:
	// Sets default values for this character's properties
	ASCharacter();

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

	void MoveForward(float value);
	void MoveRight(float value);

	UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category="Component")
	UCameraComponent* CameraCom;

	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Component")
	USpringArmComponent* SpringArmComponent;

public:	
	// Called every frame
	virtual void Tick(float DeltaTime) override;

	// Called to bind functionality to input
	virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;


};
// Fill out your copyright notice in the Description page of Project Settings.

#include "Public/SCharacter.h"
#include "Camera/CameraComponent.h"
#include "GameFrameWork/SpringArmComponent.h"

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

	SpringArmComponent = CreateDefaultSubobject<USpringArmComponent>(TEXT("SpringArmComponent"));
	SpringArmComponent->SetupAttachment(RootComponent);
	//设置character控制弹簧臂的旋转, 相机的UsePawnControlRotation要设置成false,如果要有勾
         // 选,要取消勾选
	SpringArmComponent->bUsePawnControlRotation = true;

	CameraCom=CreateDefaultSubobject<UCameraComponent>(TEXT("CameraCom"));
	//只有设置为true 才能调用下面BindAxis绑定的函数,才会被控制旋转
	//CameraCom->bUsePawnControlRotation = true;
	CameraCom->SetupAttachment(SpringArmComponent);//设置成弹簧臂的子物体

}

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

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

}

// Called to bind functionality to input
void ASCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

	//第一个参数 轴的名称
	//第二个参数 作用的物体
	//第三个参数 要调用的函数
	PlayerInputComponent->BindAxis("MoveForward",this,&ASCharacter::MoveForward);
	PlayerInputComponent->BindAxis("MoveRight", this, &ASCharacter::MoveRight);

	PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);
	PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);
}

void ASCharacter::MoveForward(float value)
{
	AddMovementInput(GetActorForwardVector(),value);
}

void ASCharacter::MoveRight(float value)
{
	AddMovementInput(GetActorRightVector(), value);
}

猜你喜欢

转载自blog.csdn.net/m0_37981386/article/details/90174449