UE4用代碼畫一條射線


我們都知道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,如果不能設置,就新創建一個游戲模式,
這里寫圖片描述

編譯播放,即可
這里寫圖片描述

如果看不見,就左右移動移動


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM