Advertisement
Guest User

C++ "Antigravity Engine" Vite Project

a guest
Aug 10th, 2023
437
0
98 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 12.79 KB | Gaming | 0 0
  1. /*by Vila Carlos for Vite23 Project*/
  2.  
  3. #include "VRacer.h"
  4. #include "DetailLayoutBuilder.h"
  5. #include "VectorTypes.h"
  6. #include "GameFramework/Actor.h"
  7. #include "Components/BillboardComponent.h"
  8. #include "Particles/ParticleSystemComponent.h"
  9. #include "Math/UnrealMathUtility.h"
  10. #include "Physics/ImmediatePhysics/ImmediatePhysicsShared/ImmediatePhysicsCore.h"
  11. // Sets default values
  12. AVRacer::AVRacer()
  13. {
  14.     // Set this pawn to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
  15.     PrimaryActorTick.bCanEverTick = true;
  16.  
  17.     SphereCollision = CreateDefaultSubobject<USphereComponent>("SphereCollision");
  18.     SetRootComponent(SphereCollision);
  19.  
  20.         CamRotator = CreateDefaultSubobject<UBillboardComponent>("CamRotator");
  21.         CamRotator->SetupAttachment(RootComponent);
  22.             SpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("SpringArm"));
  23.             SpringArm->SetupAttachment(CamRotator);
  24.                 Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera"));
  25.                 Camera->SetupAttachment(SpringArm);
  26.  
  27.         ShipMesh = CreateDefaultSubobject<UStaticMeshComponent>("ShipMesh");
  28.         ShipMesh->SetupAttachment(RootComponent);
  29.             BackCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("BackCamera"));
  30.             BackCamera->SetupAttachment(ShipMesh);
  31.  
  32.             AirbrakeRight = CreateDefaultSubobject<UBillboardComponent>("AirbrakeRight");
  33.             AirbrakeRight->SetupAttachment(ShipMesh);
  34.                 RightAirbrakeMesh = CreateDefaultSubobject<UStaticMeshComponent>("RightAirbrakeMesh");
  35.                 RightAirbrakeMesh->SetupAttachment(AirbrakeRight);
  36.            
  37.             AirbrakeLeft = CreateDefaultSubobject<UBillboardComponent>("AirbrakeLeft");
  38.             AirbrakeLeft->SetupAttachment(ShipMesh);
  39.                 LeftAirbrakeMesh = CreateDefaultSubobject<UStaticMeshComponent>("LeftAirbrakeMesh");
  40.                 LeftAirbrakeMesh->SetupAttachment(AirbrakeLeft);
  41.  
  42.             PointLight = CreateDefaultSubobject<UPointLightComponent>("PointLightComponent");
  43.             PointLight->SetupAttachment(ShipMesh);
  44.  
  45.             ParticleEffects = CreateDefaultSubobject<UBillboardComponent>("ParticleEffects");
  46.             ParticleEffects->SetupAttachment(ShipMesh);
  47.                 AirflowLeft = CreateDefaultSubobject<UParticleSystemComponent>("AirflowLeft");
  48.                 AirflowLeft->SetupAttachment(ParticleEffects);
  49.                 AirflowRight = CreateDefaultSubobject<UParticleSystemComponent>("AirflowRight");
  50.                 AirflowRight->SetupAttachment(ParticleEffects);
  51.                 ExhaustRight = CreateDefaultSubobject<UParticleSystemComponent>("ExhaustRight");
  52.                 ExhaustRight->SetupAttachment(ParticleEffects);
  53.                 ExhaustLeft = CreateDefaultSubobject<UParticleSystemComponent>("ExhaustLeft");
  54.                 ExhaustLeft->SetupAttachment(ParticleEffects);
  55.     SphereCollision->SetSimulatePhysics(true);
  56.     SphereCollision->SetNotifyRigidBodyCollision(true);
  57.     SphereCollision->BodyInstance.SetCollisionProfileName("BlockAllDynamic");
  58.     SphereCollision->OnComponentHit.AddDynamic(this, &AVRacer::OnHit);
  59. }
  60.  
  61. void AVRacer::OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit)
  62. {
  63.     if (Hit.PhysMaterial.Get() != nullptr  )
  64.     {
  65.         if (Hit.PhysMaterial.Get()->GetFName().ToString() == "WallCollision")//WallCollisionMaterial
  66.             {
  67.             const FVector Force = GetVelocity()* (FMath::Max(WallDeceleration, 0)*-1);
  68.             SphereCollision->AddForce(Force, NAME_None, true);
  69.             }
  70.     }
  71. }
  72.  
  73. // Called when the game starts or when spawned
  74. void AVRacer::BeginPlay()
  75. {
  76.     Super::BeginPlay();
  77.  
  78. }
  79.  
  80. void AVRacer::LookBack(float value)
  81. {
  82.     if (value > 0.5f)
  83.     {
  84.         BackCamera->SetActive(true,false);
  85.         Camera->SetActive(false,false);
  86.     } else
  87.     {
  88.         BackCamera->SetActive(false,false);
  89.         Camera->SetActive(true,false);
  90.     }
  91. }
  92.  
  93. void AVRacer::InputActionTurbo()
  94. {
  95.     if (IsLocallyControlled())
  96.     {
  97.         if (HasAuthority())//Should Do Event to run on Server
  98.         {
  99.             if (bIgnition && bTurboAvailable)
  100.             {
  101.                 //run timeline
  102.                 Turbo();
  103.             }
  104.         }
  105.     }
  106. }
  107.  
  108.  
  109. bool AVRacer::LineTraceSingleForObjects(const FVector Start, const FVector End, FHitResult& OutHit) const
  110. {
  111.     FCollisionQueryParams Params;
  112.     Params.AddIgnoredActor(this);
  113.     Params.bReturnPhysicalMaterial = true;
  114.     FCollisionObjectQueryParams ObjectParams;
  115.     ObjectParams.AddObjectTypesToQuery(ECC_WorldStatic);
  116.     ObjectParams.AddObjectTypesToQuery(ECC_WorldDynamic);
  117.     bool const bHit = GetWorld()->LineTraceSingleByObjectType(OutHit, Start, End, ObjectParams, Params);
  118.     return bHit;
  119. }
  120.  
  121. bool AVRacer::LineTraceSingleForObjectsStatic(const FVector Start, const FVector End, FHitResult& OutHit) const
  122. {
  123.     FCollisionQueryParams Params;
  124.     Params.AddIgnoredActor(this);
  125.     Params.bReturnPhysicalMaterial = true;
  126.     FCollisionObjectQueryParams ObjectParams;
  127.     ObjectParams.AddObjectTypesToQuery(ECC_WorldStatic);
  128.     bool const bHit = GetWorld()->LineTraceSingleByObjectType(OutHit, Start, End, ObjectParams, Params);
  129.     return bHit;
  130. }
  131.  
  132. void AVRacer::ShipControls(float DeltaTime, float Steering, float Thrust, float LeftAirbrake, float RightAirbrake, float Pitch)
  133. {
  134.     SteeringValue = FMath::FInterpTo(SteeringValue, Steering, DeltaTime, SteeringInterpSpeed);
  135.     ThrustValue = FMath::FInterpTo(ThrustValue, Thrust, DeltaTime, ThrustInterpSpeed);
  136.     LeftAirbrakeValue = FMath::FInterpTo(LeftAirbrakeValue, LeftAirbrake, DeltaTime, AirbrakeInterpSpeed);
  137.     RightAirbrakeValue = FMath::FInterpTo(RightAirbrakeValue, RightAirbrake, DeltaTime, AirbrakeInterpSpeed);
  138.     PitchValue = FMath::FInterpTo(PitchValue, Pitch, DeltaTime, PitchInterpSpeed);
  139. }
  140.  
  141. // Called every frame
  142. void AVRacer::Tick(float DeltaTime)
  143. {
  144.     Super::Tick(DeltaTime);
  145.     if (IsLocallyControlled() && bIgnition) {
  146.         ShipControls(DeltaTime, GetInputAxisValue("Steering"), GetInputAxisValue("Thrust"), GetInputAxisValue("LeftAirbrake"),
  147.                     GetInputAxisValue("RightAirbrake"), GetInputAxisValue("Pitch") );
  148.     }
  149.    
  150.     /*Vehicle Physics*/
  151.     //Get Linear & Angular Velocity
  152.     const FTransform T = SphereCollision->GetComponentToWorld();
  153.     RelativeLinearVelocity = T.InverseTransformVectorNoScale(SphereCollision->GetComponentVelocity());
  154.     RelativeAngularVelocity = T.InverseTransformVectorNoScale(SphereCollision->GetPhysicsAngularVelocityInRadians());
  155.     SpeedRatio = RelativeLinearVelocity.X / (TopSpeed * 0.036);
  156.  
  157.     // LevitationTrace
  158.     FVector InverseTransformDir = GetActorTransform().InverseTransformVectorNoScale(GetActorLocation());
  159.     double PitchAngleRad = (DOUBLE_PI / 180.0) * PitchValue * PitchAngle;
  160.     FVector EndDir = FVector(InverseTransformDir.X + LevitationHeight * PitchAngleRad,
  161.         InverseTransformDir.Y,
  162.         InverseTransformDir.Z - (bMagneticSurface ? LevitationHeight * 2 : LevitationHeight));
  163.     FVector End = GetActorTransform().InverseTransformVectorNoScale(EndDir);
  164.     FHitResult OutHit;
  165.     LineTraceSingleForObjectsStatic(GetActorLocation(), End, OutHit);
  166.     LevitationFactor = 1.0 - OutHit.Time;
  167.    
  168.     if (OutHit.PhysMaterial.Get() != nullptr)  {
  169.         const FString HitPhysMaterialName = OutHit.PhysMaterial.Get()->GetFName().ToString();
  170.         bMagneticSurface = HitPhysMaterialName == "MagneticSurface";
  171.         bLevitationTraceObstructed = bMagneticSurface || HitPhysMaterialName == "LevitationSurface";
  172.     } else {
  173.         bLevitationTraceObstructed = false;
  174.         bMagneticSurface = false;
  175.     }
  176.    
  177.     //Align Traces
  178.     TArray<FVector> AlignTraceDirectionsFromCenter; //= {FVector(0,0,-1), FVector(), FVector(),FVector()};
  179.     AlignTraceDirectionsFromCenter.Add(FVector(0,0,-1));
  180.     AlignTraceDirectionsFromCenter.Add(FVector(0,1,0));
  181.     AlignTraceDirectionsFromCenter.Add(FVector(0,-1,0));
  182.     AlignTraceDirectionsFromCenter.Add(FVector(1,0,0));
  183.     AlignTraceDirectionsFromCenter.Add(FVector(-1,0,0));
  184.     AlignTraceDirectionsFromCenter.Add(FVector(0,0,1));
  185.    
  186.     int32 NumTraceDirections = AlignTraceDirectionsFromCenter.Num();
  187.     FTransform ActorTransform = GetActorTransform();
  188.     FVector ActorLocation = GetActorLocation();
  189.     for (int32 i = 0; i < NumTraceDirections; i++)
  190.     {
  191.         FVector AlignTraceDir = AlignTraceDirectionsFromCenter[i].GetSafeNormal(0.0001);
  192.         FVector LineTraceEnd = ActorTransform.TransformVectorNoScale(ActorTransform.InverseTransformVectorNoScale(ActorLocation) + AlignTraceDir * (bMagneticSurface ? LevitationHeight * 2 : LevitationHeight));
  193.  
  194.         FHitResult Out;
  195.         if (LineTraceSingleForObjects(ActorLocation, LineTraceEnd, Out))
  196.         {
  197.             UPhysicalMaterial* PhysMaterial = Out.PhysMaterial.Get();
  198.             if (PhysMaterial)
  199.             {
  200.                 FName MaterialName = PhysMaterial->GetFName();
  201.                 if (MaterialName == FName("LevitationSurface") || MaterialName == FName("MagneticSurface"))
  202.                 {
  203.                     bAlignTraceObstructed = true;
  204.                     FloorSurfaceNormal = Out.Normal;
  205.                     break;
  206.                 }
  207.             }
  208.         }
  209.     }
  210.    
  211.     //Set Levitation Force
  212.     if (bLevitationTraceObstructed)
  213.     {
  214.         double LevForce;
  215.         if (bMagneticSurface)
  216.         {
  217.             LevForce = (LevitationFactor*2.0 -1.0)*(LevitationForce*1.0);//-1.0
  218.             UE_LOG(LogTemp, Warning, TEXT("bMagneticSurface True "));
  219.         } else
  220.         {
  221.             LevForce = pow(LevitationFactor,2.0)*LevitationForce;
  222.         }
  223.     } else
  224.     {
  225.         RelativeLevitationForce = FVector::ZeroVector;
  226.     }
  227.    
  228.    
  229.     //Set Sideways Stabilization Force
  230.     RelativeSidewaysStabilizationForce = FVector(0, RelativeLinearVelocity.Y*-1*SidewaysStability,0 );
  231.    
  232.     //Set Thrust Force
  233.     double GetReverseTrust;
  234.     ThrustValue > 0.0 ? GetReverseTrust = ThrustForce*ThrustValue : GetReverseTrust = ReverseThrustForce*ThrustValue;
  235.  
  236.     double MThrust = 1 - SpeedRatio * SpeedRatio;
  237.  
  238.     double LevitationMultiplier = bLevitationTraceObstructed ? 1 - FMath::Clamp(AirThrustReduction, 0.0, 1.0) : 1.0;
  239.  
  240.     RelativeThrustForce = FVector(GetReverseTrust * MThrust * LevitationMultiplier, 0, 0);
  241.  
  242.     RelativeBoostForce = FVector(BoostValue * BoostMultiplier + TurboValue * TurboMultiplier, 0, 0);
  243.  
  244.     double CombinedInputs = RelativeLinearVelocity.X > 0 ? (LeftAirbrakeValue + RightAirbrakeValue) * AirbrakeDeceleration * -1 : 0;
  245.     RelativeBrakeForce = FVector(CombinedInputs, 0, 0);
  246.  
  247.     double DownforceValue = DownforceMultiplier * FMath::Abs(SpeedRatio) * -1;
  248.     RelativeDownforce = GetActorTransform().InverseTransformVectorNoScale(FVector(0, 0, DownforceValue));
  249.  
  250.     if (bLevitationTraceObstructed && LeftAirbrakeValue > 0.9 && RightAirbrakeValue > 0.9 && RelativeLinearVelocity.Size() < (EBrakeMaxVelocity * 27.777))
  251.     {
  252.         RelativeEbrakeForce = RelativeLinearVelocity * (FMath::Abs(EBrakeForce) * -1);
  253.     }
  254.     else
  255.     {
  256.         RelativeEbrakeForce = FVector(0, 0, 0);
  257.     }
  258.    
  259.     // Set Downforce
  260.     float DownforceValue = DownforceMultiplier * FMath::Abs(SpeedRatio) * -1;
  261.     RelativeDownforce = GetActorTransform().InverseTransformVectorNoScale(FVector(0, 0, DownforceValue));
  262.  
  263.     // Set E Brake Force
  264.     if (bLevitationTraceObstructed && LeftAirbrakeValue > 0.9 && RightAirbrakeValue > 0.9 && RelativeLinearVelocity.Size() < (EBrakeMaxVelocity * 27.777))
  265.     {
  266.         RelativeEbrakeForce = RelativeLinearVelocity * (FMath::Abs(EBrakeForce) * -1);
  267.     }
  268.     else
  269.     {
  270.         RelativeAlignTorque = FVector::ZeroVector;
  271.     }
  272.  
  273.     // Set Align Torque
  274.     FVector RelativeAlignTorque(0, 0, 0);
  275.     if (bAlignTraceObstructed)
  276.     {
  277.         float Xterm = (FVector::DotProduct(SphereCollision->GetRightVector().GetSafeNormal(0.0001), FloorSurfaceNormal.GetSafeNormal(0.0001)) * -1) * UpdateTorqueAlign();
  278.         float Yterm = UpdateTorqueAlign() * GetPitchAngle();
  279.         RelativeAlignTorque = FVector(Xterm, Yterm, 0);
  280.     }
  281.  
  282.     // Set Steering Torque
  283.     float AirbrakeSteering = (LeftAirbrakeValue * -1 + RightAirbrakeValue) * AirbrakeSteeringSupport * SpeedRatio;
  284.     RelativeSteeringTorque = FVector(0, 0, SteeringTorque * SteeringValue + AirbrakeSteering);
  285.  
  286.     // Apply Linear Forces
  287.     FVector Sum = RelativeLevitationForce + RelativeLevitationDampingForce + RelativeSidewaysStabilizationForce
  288.         + RelativeThrustForce + RelativeBoostForce + RelativeBrakeForce + RelativeDownforce + RelativeDragForce + RelativeEbrakeForce;
  289.     if (Sum.SizeSquared() < 100.0f) // Adjust threshold as needed
  290.     {
  291.         Sum = FVector::ZeroVector;
  292.     }
  293.     FVector Force = GetActorTransform().TransformVectorNoScale(Sum);
  294.     SphereCollision->AddForce(Force, NAME_None, true);
  295.  
  296.     // Apply Angular Forces
  297.     FVector AngularSum = RelativeAlignTorque + RelativeSteeringTorque;
  298.     FVector Torque = GetActorTransform().TransformVectorNoScale(AngularSum);
  299.     SphereCollision->AddTorqueInRadians(Torque, NAME_None, true);
  300.  
  301.     // Set Gravity
  302.     SphereCollision->SetEnableGravity(!bMagneticSurface);
  303. }
  304.  
  305. double AVRacer::GetPitchAngle() const
  306. {
  307.     const FVector VectorToRotate = SphereCollision->GetComponentTransform().InverseTransformVectorNoScale(SphereCollision->GetForwardVector());//SceneComp->GetComponentToWorld().TransformVectorNoScale(SceneComp->GetForwardVector());
  308.     FVector Dir = FRotator(PitchValue*PitchAngle,0,0).RotateVector(VectorToRotate);
  309.     FVector Member1 = SphereCollision->GetComponentTransform().TransformVectorNoScale(Dir);
  310.     return FVector::DotProduct( Member1.GetSafeNormal(0.0001), FloorSurfaceNormal.GetSafeNormal(0.0001));
  311. }
  312.  
  313. double AVRacer::UpdateTorqueAlign() const
  314. {
  315.     return bMagneticSurface ? UseFixedAlignTorque()*600 : UseFixedAlignTorque()*300;
  316. }
  317.  
  318. double AVRacer::UseFixedAlignTorque() const
  319. {
  320.     return PitchValue !=0.0f ? 0.5f : FMath::Max(LevitationFactor,0.2);
  321. }
  322.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement