TheRedPixel

Vite-AntiGravityEngine

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