我们都知道UE里面的射线很重要,我们都会用蓝图去添加组件
但是不会用C++去添加,今天就教大家如何用C++代码去实现
IDE:VS2017
UE版本:4.17
首先效果图:
我们创建要给空的C++项目
启动之后按下 F8 选中默认的pawn添加一个蓝图脚本
我们命名成“DB_Pawn”
添加一个C++组件,系统会自动打开我们的VS
第一步我们在.h中写入如下代码
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "Engine/World.h"
#include "Public/DrawDebugHelpers.h"
#include "DrawDebugLine_Cpp.generated.h"
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class DRAWDEBUGLINE_API UDrawDebugLine_Cpp : public UActorComponent
{
GENERATED_BODY()
public:
// Sets default values for this component's properties
UDrawDebugLine_Cpp();
protected:
// Called when the game starts
virtual void BeginPlay() override;
public:
// Called every frame
virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
FVector PlayerLocation; //射线起点
FRotator PlayerRotator;//面朝的方向
float lang = 100000.0f; //射线的长度
};
在从cpp中写入如下代码
// Fill out your copyright notice in the Description page of Project Settings.
#include "DrawDebugLine_Cpp.h"
// Sets default values for this component's properties
UDrawDebugLine_Cpp::UDrawDebugLine_Cpp()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void UDrawDebugLine_Cpp::BeginPlay()
{
Super::BeginPlay();
// ...
}
// Called every frame
void UDrawDebugLine_Cpp::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
GetWorld()->GetFirstPlayerController()->GetPlayerViewPoint(PlayerLocation, PlayerRotator);//定义射线的起点和方向
FVector LineEnd = PlayerLocation + PlayerRotator.Vector()*lang;//定义射线的终点
//调用画射线函数
DrawDebugLine(
GetWorld(),
PlayerLocation,
LineEnd,
FColor::Blue,
false,
0.0f,
0.0f,
10.0f
);
}
然后回到编辑器,把写好的DB_Pawn设置成默认的PawnClass,如果不能设置,就新创建一个游戏模式,
编译播放,即可
如果看不见,就左右移动移动