-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBall.cpp
More file actions
95 lines (75 loc) · 2.04 KB
/
Ball.cpp
File metadata and controls
95 lines (75 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Fill out your copyright notice in the Description page of Project Settings.
#include "Ball.h"
#include "ParaPong_Final.h"
#include <Kismet/KismetMathLibrary.h>
// Sets default values
ABall::ABall()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
BallMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("BallMesh"));
SetRootComponent(BallMesh);
//in event collision, Call the function OnBallHit.
OnActorHit.AddDynamic(this, &ABall::OnBallHit);
}
// Called when the game starts or when spawned
void ABall::BeginPlay()
{
Super::BeginPlay();
Direction = GetRandomXYDirection();
//Read a current position ball
InitialLocation = GetActorLocation();
// Enable "Simulation Generates Hit Events".
BallMesh->SetNotifyRigidBodyCollision(true);
// Move the Ball only in XY plane.
BallMesh->SetConstraintMode(EDOFMode::XYPlane);
// Enable Physics simulation Physics in Ball.
StopMovement();
// Set Mass
BallMesh->SetMassOverrideInKg(NAME_None, 1.0f, true);
}
// Called every frame
void ABall::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
if (BallMesh && BallMesh->IsSimulatingPhysics())
{
FVector const Force = Direction * 900.0f;
BallMesh->AddForce(Force);
}
}
void ABall::OnBallHit(AActor* SelfActor, AActor* OtherActor, FVector NormalImpulse, const FHitResult& Hit)
{
Direction = UKismetMathLibrary::GetReflectionVector(Direction, Hit.Normal);
UE_LOG(LogParaPong, Log, TEXT("Direction: %s"), *Direction.ToString());
}
void ABall::StartMovement()
{
if(BallMesh)
{
Direction = GetRandomXYDirection();
BallMesh->SetSimulatePhysics(true);
}
}
void ABall::StopMovement()
{
if(BallMesh)
{
BallMesh->SetSimulatePhysics(false);
}
}
void ABall::ResetBall()
{
SetActorLocation(InitialLocation);
}
FVector ABall::GetRandomXYDirection()
{
FVector RandomDirection;
do
{
RandomDirection = UKismetMathLibrary::RandomUnitVector();
RandomDirection.Z = 0.0f;
}
while (!RandomDirection.Normalize());
return RandomDirection;
}