I have a player class and a planet class and the functions depend on variables from both classes,
Question is: what is the best way to connect the two classes, should it be done via the game mode or should I make a direct connection
I have a player class and a planet class and the functions depend on variables from both classes,
Question is: what is the best way to connect the two classes, should it be done via the game mode or should I make a direct connection
Where is the function that uses variables of both the player and planet class?
In the planet class because the variables of the planet class should be changed depending on the function output. The idea is to get the owning player and get a variable from there, then execute the function and change the planet class’ variables
An easy way to do this would be by including the .h of the player class in the planet.cpp. If you do this, you can do a function similar to the following:
void AMyProjectile::ReceiveHit(class UPrimitiveComponent* MyComp, AActor* Other, class UPrimitiveComponent* OtherComp, bool bSelfMoved, FVector HitLocation, FVector HitNormal, FVector NormaImpulse, const FHitResult & Hit)
{
Super::ReceiveHit(MyComp, Other, OtherComp, bSelfMoved, HitLocation, HitNormal, NormaImpulse, Hit);
AMyCharacter* placeholder = Cast<AMyCharacter>(Other);
if (placeholder)
{
placeholder->ReceiveDamage(ProjectileDamage);
}
}
To explain what is going on in the above code; This is a overloaded function of ReceiveHit, which is called whenever an object collides with another. In this case, it’ll be called when this projectile collides with anything. In the top of the file that this function is being defined in, MyCharacter.h is being included so that I can make a pointer of that type. I then use ‘Other’, which is the object that the projectile is colliding with, to cast to AMyCharacter to see if that is indeed what it collided with. I then use the placeholder to call a function that only exists in the AMyCharacter class. This could also be used to access the variables of that class as long as they are set to public.
Hope this helps!
Ok, and how do I know which actor is hit
You get that inside the HitResult.
That is the point of the following line:
AMyCharacter* placeholder = Cast<AMyCharacter>(Other);
This creates a pointer that can point to a variable of the type ‘AMyCharacter’ and attempts to cast to the ‘AMyCharacter’ class using Other (Other is being passed into this function as the object that is being collided with.) If this works, then it’ll store a reference to Other in memory, otherwise it’ll remain a nullptr. I then used the if statement right after to determine if I should act on this or not, as I wouldn’t want to try to run ReceiveDamage if placeholder wasn’t pointing to a AMyCharacter variable.