CARLA
Loading...
Searching...
No Matches
VehicleVelocityControl.cpp
Go to the documentation of this file.
1// Copyright (c) 2026 Computer Vision Center (CVC) at the Universitat Autonoma
2// de Barcelona (UAB).
3//
4// This work is licensed under the terms of the MIT license.
5// For a copy, see <https://opensource.org/licenses/MIT>.
6
9
10#include <util/ue-header-guard-begin.h>
11#include "Kismet/KismetMathLibrary.h"
12#include <util/ue-header-guard-end.h>
13
14UVehicleVelocityControl::UVehicleVelocityControl()
15{
16 PrimaryComponentTick.bCanEverTick = true;
17}
18
19void UVehicleVelocityControl::BeginPlay()
20{
21 Super::BeginPlay();
22
23 SetComponentTickEnabled(false);
24 SetTickGroup(ETickingGroup::TG_PrePhysics);
25
26 OwnerVehicle = GetOwner();
27 ACarlaWheeledVehicle* CarlaVehicle = Cast<ACarlaWheeledVehicle>(OwnerVehicle);
28 if (CarlaVehicle && CarlaVehicle->GetMesh())
29 {
30 PrimitiveComponent = Cast<UPrimitiveComponent>(CarlaVehicle->GetMesh());
31 }
32 if (PrimitiveComponent == nullptr)
33 {
34 PrimitiveComponent = Cast<UPrimitiveComponent>(OwnerVehicle->GetRootComponent());
35 }
36}
37
38void UVehicleVelocityControl::Activate(bool bReset)
39{
40 Super::Activate(bReset);
41
42 TargetVelocity = FVector();
43 SetComponentTickEnabled(true);
44}
45
46void UVehicleVelocityControl::Activate(FVector Velocity, bool bReset)
47{
48 Super::Activate(bReset);
49
50 TargetVelocity = Velocity;
51 SetComponentTickEnabled(true);
52}
53
54void UVehicleVelocityControl::Deactivate()
55{
56 SetComponentTickEnabled(false);
57 Super::Deactivate();
58}
59
60void UVehicleVelocityControl::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)
61{
62 TRACE_CPUPROFILER_EVENT_SCOPE(UVehicleVelocityControl::TickComponent);
63 if (PrimitiveComponent == nullptr)
64 {
65 return;
66 }
67 PrimitiveComponent->WakeRigidBody(NAME_None);
68 const FTransform Transf = OwnerVehicle->GetActorTransform();
69 // Force only the component along TargetVelocity; physics keeps the perpendicular
70 // part so the tyres can corner and the vehicle follows the ground. Zero stops it.
71 FVector Local = FVector::ZeroVector;
72 const FVector Dir = TargetVelocity.GetSafeNormal();
73 if (!Dir.IsZero())
74 {
75 const FVector Current = Transf.InverseTransformVectorNoScale(PrimitiveComponent->GetPhysicsLinearVelocity());
76 Local = Current - FVector::DotProduct(Current, Dir) * Dir + TargetVelocity;
77 }
78 PrimitiveComponent->SetPhysicsLinearVelocity(Transf.TransformVectorNoScale(Local), false, "None");
79}
Base class for CARLA wheeled vehicles.