Advertisement
TheRedPixel

AntiGravityEngine

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