// Fill out your copyright notice in the Description page of Project Settings.
#include "Components/AudioComponent.h"
#include "Components/PrimitiveComponent.h"
#include "Engine/World.h"
#include "GameFramework/Actor.h"
#include "Math/UnrealMathUtility.h"
#include "OpenDoor.h"
// Sets default values for this component's properties
UOpenDoor::UOpenDoor()
{
// 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 UOpenDoor::BeginPlay()
{
Super::BeginPlay();
InitialYaw = GetOwner()->GetActorRotation().Yaw;
FindAudioComponent();
}
// Called every frame
void UOpenDoor::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
if (TotalMassOfActors() >= MassToOpenDoor)
{
OpenDoor(DeltaTime);
DoorLastOpened = GetWorld()->GetTimeSeconds();
}
else
{ if(PressurePlate)
{
if (GetWorld()->GetTimeSeconds() - DoorLastOpened > DoorCloseDelay)
{
CloseDoor(DeltaTime);
}
}
}
}
void UOpenDoor::OpenDoor(float DeltaTime)
{
DoorRotation = GetOwner()->GetActorRotation();
DoorRotation.Yaw = FMath::Lerp(DoorRotation.Yaw, TargetYaw, DeltaTime* 0.5f);
GetOwner()->SetActorRotation(DoorRotation);
}
void UOpenDoor::CloseDoor(float DeltaTime)
{
DoorRotation = GetOwner()->GetActorRotation();
DoorRotation.Yaw = FMath::Lerp(DoorRotation.Yaw, InitialYaw, DeltaTime* 1.5f);
GetOwner()->SetActorRotation(DoorRotation);
}
float UOpenDoor::TotalMassOfActors()
{
float TotalMass = 0.f;
TArray<AActor*> OverlappingActors;
PressurePlate->GetOverlappingActors(OverlappingActors);
for (AActor* Actor : OverlappingActors)
{
TotalMass += Actor->FindComponentByClass<UPrimitiveComponent>()->GetMass();
UE_LOG(LogTemp, Warning, TEXT("%s is overlapping"), *Actor->GetName())
}
return TotalMass;
}
void UOpenDoor::FindAudioComponent()
{
AudioComponent = GetOwner()->FindComponentByClass<UAudioComponent>();
if(!AudioComponent)
{
UE_LOG(LogTemp, Error, TEXT("%s missing audio component"), *GetOwner()->GetName())
}
}