We all know that the ray in UE is very important. We will use blueprint to add components
But I will not use C + + to add. Today, I will teach you how to use C + + code to realize it
IDE:VS2017
UE version: 4.17
First rendering:
We create a C + + project to give empty
After startup, press F8 to select the default pawn and add a blueprint script
We call it "DB" pawn
Add a C + + component, the system will automatically open our VS
The first step is to write the following code in. 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; //Ray starting point FRotator PlayerRotator;//Face to face float lang = 100000.0f; //Length of ray };
Write the following code from 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);//Define the start and direction of the ray FVector LineEnd = PlayerLocation + PlayerRotator.Vector()*lang;//Define the end point of the ray //Call the draw ray function DrawDebugLine( GetWorld(), PlayerLocation, LineEnd, FColor::Blue, false, 0.0f, 0.0f, 10.0f ); }
Then go back to the editor and set the written DB [pawn] to the default PawnClass. If it can't be set, create a new game mode,
Compile and play
If you can't see it, move left and right