Gun.cpp
#include "Gun.h"
#include "Components/SkeletalMeshComponent.h"
#include "kismet/GameplayStatics.h"
#include "DrawDebugHelpers.h"
// Sets default values
AGun::AGun()
{
// 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;
Root = CreateDefaultSubobject<USceneComponent>(TEXT("Root"));
RootComponent = Root;
mesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("Gun"));
mesh->SetupAttachment(Root);
}
void AGun::PullTrigger()
{
UGameplayStatics::SpawnEmitterAttached(MuzzleFlash, mesh, TEXT("MuzzleFlashSocket"));
APawn* OwnerPawn = Cast<APawn>(GetOwner());
if (OwnerPawn == nullptr) return;
AController* OwnerController = OwnerPawn->GetController();
if (OwnerController == nullptr) return;
FVector Location;
FRotator Rotation;
OwnerController->GetPlayerViewPoint(Location, Rotation);
FVector End = Location + Rotation.Vector() * MaxRange;
FHitResult Hit;
bool bSuccess = GetWorld()->LineTraceSingleByChannel(Hit, Location, End, ECollisionChannel::ECC_GameTraceChannel1);
if (bSuccess)
{
FVector ShotDirection = -Rotation.Vector();
UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), ImpactEffect, Hit.Location, ShotDirection.Rotation());
}
}
// Called when the game starts or when spawned
void AGun::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AGun::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
Gin.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Gun.generated.h"
UCLASS()
class SIMPLESHOOTER_API AGun : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AGun();
void PullTrigger();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
private:
UPROPERTY(VisibleAnywhere)
USceneComponent* Root;
UPROPERTY(VisibleAnywhere)
USkeletalMeshComponent* mesh;
UPROPERTY(EditAnywhere)
UParticleSystem *MuzzleFlash;
UPROPERTY(EditAnywhere)
UParticleSystem *ImpactEffect;
UPROPERTY(EditAnywhere)
float MaxRange = 1000;
};