(UE4) Is there a method of getting all actors in camera view? - trace

Like the title says, i want to be able to get all actors that are within the camera view in Unreal Engine 4.
I have thought of two ways i could do this: 1) using a shape trace in the form of a "boxtracebyobject" which works but seems to be glitchy at times and has trouble recognizing multiple overlapping actors. 2) using a "BoxOverlappingActors", though i havent quite figured out how to use it yet.
If anyone knows of a proper method to getting actors in cameria view, my ears are open!

Update
A much better answer has been posted on Unreal Answers by Rama:
Use the AActor::GetLastRenderTime() to find out for each actor when last drawn or UPrimitiveComponent::LastRenderTime for the primitive itself. His answer explains how you can use this.
Original answer:
As you suggested, it seems weird that you would have to do something to do with collision volumes when Unreal must be checking to do culling so I found the following method to query that information:
First we have to create a FSceneView from the camera. This code is taken from the UE Answers question.
APlayerCameraManager* Manager = World->GetFirstPlayerController()->PlayerCameraManager;
ULocalPlayer* LocalPlayer = World->GetFirstLocalPlayerFromController();
FSceneViewFamilyContext ViewFamily(FSceneViewFamily::ConstructionValues(
LocalPlayer->ViewportClient->Viewport,
World->Scene,
LocalPlayer->ViewportClient->EngineShowFlags)
.SetRealtimeUpdate(true));
FVector ViewLocation;
FRotator ViewRotation;
FSceneView* SceneView = LocalPlayer->CalcSceneView(&ViewFamily, /*out*/ ViewLocation, /*out*/ ViewRotation, LocalPlayer->ViewportClient->Viewport);
Once we've created the view we can iterate through all primitive components (includes meshes) and then we can use the bounds from the SceneProxy of the Static Mesh and the bounds of the view to do our own culling.
for (TObjectIterator<UPrimitiveComponent> ScenePrimitsItr; ScenePrimitsItr; ++ScenePrimitsItr)
{
// Using the Object iterator so we have to skip objects not in the
// relevant world
if (ScenePrimitsItr->GetWorld() == World)
{
FPrimitiveSceneProxy* Proxy = ScenePrimitsItr->SceneProxy;
if (Proxy)
{
bool bIsShown =
SceneView->ViewFrustum.IntersectSphere(Proxy->GetBounds().Origin, Proxy->GetBounds().SphereRadius)||
SceneView->ViewFrustum.IntersectBox(Proxy->GetBounds().Origin, Proxy->GetBounds().BoxExtent);
}
}
}
The frustrum check came from SceneVisibility.cpp in the method FrustumCull This method isn't ideal as a) involves duplicating that check and b) performing the test twice. However, I couldn't find a way to actually query the result. It appears to be stored in a bit array in the FViewInfo. Unfortunately this info is not exposed outside of the renderer module.

You could try this to create an array of actors:
But I don't know if it's good performance wise if there are too many actors of the class you want.

Related

Are UE4 Blueprints the same with a C++ class? If so, how will I implement a class design?

Good day! I am new to using Unreal Engine 4 and I have a few questions about how exactly blueprints work. From my understanding of it, every blueprint works like a class. By that I mean one blueprint is much like one class in an OOP programming language.
Please educate me as to - if my assumption is correct or wrong. If wrong, then maybe you could help me achieve what I want in a different method/perspective. I am willing to learn and accept suggestions.
If at some point my understanding is correct - that blueprints are actually individual classes - I would really appreciate it if you could (please) guide as to where to go and how to implement a design that I want to create. This is from a programmers perspective (PHP OOP Programming). Forgive the approach, I'm just using PHP to logically express how I want the class to work. Plus, it is the only OOP programming I know atm.
I want to create a class named: Items. class Item {}
This class is going to handle everything item related, thus we will have to give it a lot of properties/variable. (Below is just an example; Again I'm using PHP as an example.)
class Item {
var $id;
var $name;
var $description;
var $type;
var $subType;
var $mesh;
var $materials;
}
3.) I would like to initiate this class by having two variables as its construct arguments. (We will require itemID and itemType). This is because I will use these two variables to retrieve the item's data which is already available in a data table. I will use those data in the table to populate the class properties/variables. (I'm not sure if I said that right. I hope you understood my point anyway.)
class Item {
var $id;
var $name;
var $description;
var $type;
var $subType;
var $mesh;
var $materials;
function _construct($cons_itemID, $cons_itemType) {
/*-- Start getting the item Data here based on what item and type provided. Then, push that data into the class properties/variables. We will use individual methods/functions to fill other properties/variables later. --*/
}
}
4.) Basically with that design I could easily pass on an item ID to the class and then get the item's name, description, mesh, materials and etc using pointers.
Example:
$weapon = new Item('10001','Weapon');
$weaponMesh = $weapon->getMesh();
$armor = new Item('12345','Armor');
$armorName = $armor->getName();
I'm just having a lot of trouble working with blueprint and achieve this method or even something similar to it. I'm not trying to avoid C++, I would love to learn it but I just don't have the time freedom right now.
Few things I have tried to make it work:
Casting / Casting to class (But I couldn't figure out what the target object will be and how was I going to add input arguments into the class that way? There isn't any input there that I could use.)
Spawn Actor (This one is very promising, I need to dig in deeper into this)
Blueprint Macros? Blueprint Interfaces? (I'm just lost.)
For all those who will help or answer. Thank you!
~ Chris
So far as I know, yes, we can assume that each blueprint can be viewed as class. (Moreover, since UE 4.12 (in UE 4.11 that functionality is marked as experimental I think) you can check Compile blueprints under Project settings -> Packaging. That will create native class for each blueprint.)
You can create either Blueprint or C++ class based on Object (UObject in C++). Then you can specify all properties (or variables in UE editor terminology). In BP you have small advantage: you can mark some properties as Visible at spawn (they must be Public and Visible). So when you are creating new instance of that class, you can explicitly pass values to that properties.
And in BP Construct event, that properties are correctly filled, thus you can set another properties values based on given ID and Type.
In C++ class having different arguments than FObjectInitializer is not possible, thus you don't have that values in time when constructor is executed. But it is not so hard to achieve same functionality, you can find example here: https://answers.unrealengine.com/questions/156055/passing-arguments-to-constructors-in-ue4.html.
Something about list of what you had tried:
Spawn actor - derive from actor only if you intend to have that BP in scene. Actors are subjects to game updates and rendering, so having actor only as data container is very wrong.
BP Macro is same as BP Function except function will be called just like function (so executing necesary actions by function call conventions) and macro will replace it's implementation in place, where you are calling that macro. More exhausting explanation here.
If I would implement your code, I'd do it like I said and then I'll have that class as property in some component and that component would be attached to some actor, which would be placed in scene.

How to reference a stage instance of a MovieClip from a non-document Class without causing Error 1120?

I have a basic AS3 question that has to do with the relationship between object on the stage and objects that are created and controlled by AS3 script. This question has already been addressed tons of times, and I've researched it for hours, but I found drastically different answers, many which were really complicated. I'm looking for the simplest, most general solution to this issue that is humanly (or perhaps I should say computerly) possible.
I want to be able reference an instance of an object on the stage inside a class that is not the main document class. Before I try to explain in my own terms, it might be better to view one of these posts, which cover the exact topic I'm confused about. If any of you understand the issue, and understand the solutions to one of these posts, perhaps you could translate one of the correct answers into n00banese for me. Rather than just focusing on how they did it, you could explain WHY it was necessary to do it that. I would be very thankful if someone could do that much, and if you can it is not necessary to read any further into this post.
AS3 - Access MovieClip from stage within a class
How do I access a MovieClip on the stage from the Document Class?
AS3 Modify stage Objects from a class
how do I make non-document-class classes 'aware' of stage components in Flash AS3?
Accessing ActionScript3 Nested Movie Clips from Class
Since it's highly possible that all of the above-mentioned situations are too complicated for me, I recreated the problem in the simplest, most general way possible in hopes that it would be easier to explain in this case.
I have a MovieClip on the stage with instance name scene_mc. scene_mc does nothing except separate one scene from another. It's linked to a .as file named Scene. Nested inside scene_mc there is a movieclip called thing_mc, linked to .as file Thing. I want to move thing_mc across the scene. I could easily do this by changing its coordinates in the main document class, something like this:
thing_mc.x = thing_mc.x + 100;
But since thing_mc is nested inside of scene_mc, I would like to control thing_mc's position inside the SCENE class so that the coordinates are relevant to other nested symbols in this class. And because in more complicated projects, it just makes sense to control a nested symbol in the code of its parent. So inside Scene.as, I might create this method:
public function moveThing() {
thing_mc.x = thing_mc.x + 200;
}
This causes this error: "1120: Access of undefined property thing_mc."
Error 1120 happens any time one tries to reference a stage instance of a symbol a .as file that is not the main document class.
So to reiterate my question, how can I let the Scene class know what thing_mc is? Or how can I let any class know what any stage instance is? How do you reference a stage instance of an object through a non-document class?
Oh! This might be helpful. The Actioscript 3.0 docs say this- Note: Children instances placed on the Stage in the Flash authoring tool cannot be accessed by code from within the constructor of a parent instance since they have not been created at that point in code execution. Before accessing the child, the parent must instead either create the child instance by code or delay access to a callback function that listens for the child to dispatch itsĀ Event.ADDED_TO_STAGEĀ event.
So I mean, really I get why what I'm trying to do would cause an error, but I still don't get how to work around it.
Anyone who actually read this far into my gibberish, thank you. You are a kind and patient soul, haha. This issue is really consuming me so any attempt to help me understand the theory of how this works would be IMMENSELY appreciated. :D
...From what I understood after an all nighter (and sorry if this isn't the answer you're looking for)
You need to link Scene (the object in your library in Adobe Flash (or Adobe Animate if you're using that)) to your class. (Export for Actionscript) BUT (and here's the kicker) you need to also check export for frame 1 and make sure it's loaded on frame 1.
I run into issues like this when I'm not paying attention. Make sure the movieclip nested inside your main movieclip, somehow, gets loaded. Be it through the constructor, or on frame 1. Say your nested movieclip is on frame 2. Well, flash hasn't loaded frame 2. Therefor, it hasn't constructed anything inside frame 2. So it has no idea what you're talking about.
At times, i've had to do a gotoAndStop(2) and then right back to 1 just so that an object on frame 2 was named and ready to be handled in the future.

Does Unity have a constructor when loading a scene?

I would like to populate the UI when I load a scene, with the correct data, instead of placeholders.
When I call "LoadSceneAsync", what would be the first object that is called, so I can fill the UI label with the correct data? I know that there is a scene GameObject, but I am not sure if that would fit my needs.
I am looking for some sort of constructor, called when a new scene object is loaded; to plug in my setup function.
You say
Indeed I did use "onlevelwasloaded" but the UI element may not be there, ready to go, when I invoke it, which lead to errors
That would be an incredibly sever bug in Unity! :)
Could it be that you are mixing-up Awake and Start somewhere?
One way to think of it is once you call Start, you know all the Awake have already run.
When I call "LoadSceneAsync", what would be the first object that is called, so I can fill the UI label with the correct data
You are still within the same frame.
Once you see LoadSceneAsync you can be absolutely assured everything is Awake 'd.
Or indeed once you use Start you can be absolutely assured everything is Awake 'd.
1) could it be that in some of your UI elements (or whatever) you are doing something in Start which you should do in Awake?
2) if (for some reason) you want to "wait until the next frame", perhaps just during development - then do that, wait a frame. You'll see a flicker, but if that's what you want to do (for some reason) do that.
3) note that if you mean you want to go to the net to get something, well of course you have to wait frames (use Update/coroutine) until the information comes back from the net, obviously. (How else could it be?)
Note that in practice, one should be using UnityEngine.Events.UnityEvent everywhere.
Maybe this is what you are looking for http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnLevelWasLoaded.html
Relying on Unity internal functioning is not always the way to go. Particularly when dealing with RESTApi (which is somehow what you are dealing with here).
You cannot assume one object will be ready before another except if you control it.
Add a Controller script that uses Awake. In the Awake, call all the methods you are needing and use some callback to generate secondary code when primary is ready.
public class MyController: MonoBehaviour{
private ServerRequestController serverCtrl = null;
private UIController uiCtrl = null;
private void Awake(){
serverCtrl = this.gameObject.AddComponent<ServerRequestController>();
uiCtrl =this.gameObject.AddComponent<UIController>();
serverCtrl.GetData(uiCtrl.SetUI);
}
}
public class UIController:MonoBehaviour{
public void SetUI(Data data)
{
SetTopImage(data.topImage);
SetBottomImage(data.bottomImage);
// And so on
}
}
public class ServerRequestController:MonoBehaviour{
public void GetData(Action onCompletion){
// This may be a coroutine if you fetch from server
Data data = GetDataFromSomewhere();
// At this point, your data is ready
onCompletion(data);
}
}
Thanks to this, you are now able to know exactly when a piece of code is ready.

How do you dynamically render quads in UE4?

There are some hand wavey answers for this on answers.unrealengine.com, but they seem to lack any detail or examples.
Specifically, and in detail, if you wanted to implement a set of dynamic textured quads which rendered in the 3d game world, how would you do it?
For use case, consider a 2dish side scroller that uses Spriter animations. The 2D animations are loaded from XML easily enough, but how do you then render this 2D set of textured, rotated and scaled quads dynamically on the scene?
Is the problem you are facing concern spawning the mesh or with obtaining the right orientation? (i.e. orthographic projection, facing the camera)
Spawning the mesh is easy enough, can be done either through Blueprints or in code.
In Blueprints, you would set up certain preconditions and then choose to spawn actors based on the conditions.
The actual coding solution would look much the same.
If it is regarding orientation, then this answer will be of help to you, found on the UnrealEngine forums:
https://answers.unrealengine.com/questions/62126/how-do-i-render-a-dynamic-mesh-with-orthographic-p.html
EDIT:
After much hair pulling and documentation surfing, here's the code that made things work.
ADynamicMeshSpawner::ADynamicMeshSpawner()
{
// 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;
// Using a SphereComponent is not particularly necessary or relevant, but the cube refused to spawn without a root component to attach to, or so I surmise. Yay Unreal. =/
USphereComponent* CubeComponent = CreateDefaultSubobject<USphereComponent>(TEXT("RootComponent"));
RootComponent = CubeComponent;
CubeComponent->InitSphereRadius(40.0f);
CubeComponent->SetCollisionProfileName(TEXT("Pawn"));
// Create and position a mesh component so we can see where our cube is
UStaticMeshComponent* CubeVisual = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("VisualRepresentation"));
CubeVisual->AttachTo(RootComponent);
static ConstructorHelpers::FObjectFinder<UStaticMesh> SphereVisualAsset(TEXT("StaticMesh'/Game/StarterContent/Shapes/Shape_Cube.Shape_Cube'"));
if (SphereVisualAsset.Succeeded())
{
CubeVisual->SetStaticMesh(SphereVisualAsset.Object);
CubeVisual->SetRelativeLocation(FVector(-200.0f, 0.0f, 100.0f));
CubeVisual->SetWorldScale3D(FVector(2.0f));
}
// Create a material to be applied on the StaticMeshComponent
static ConstructorHelpers::FObjectFinder<UMaterial> Material(TEXT("Material'/Game/StarterContent/Materials/M_Tech_Hex_Tile_Pulse.M_Tech_Hex_Tile_Pulse'"));
if (Material.Object != NULL)
{
TheMaterial = (UMaterial*)Material.Object;
}
CubeVisual->SetMaterial(0, TheMaterial);
}
The headerfile looks like this:
UCLASS()
class MYPROJECT_API ADynamicMeshSpawner : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ADynamicMeshSpawner();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick( float DeltaSeconds ) override;
// Pointer to the material that needs to be used
UMaterial* TheMaterial;
};
The final output looked like this in the editor:
I set it up so that an instance of my class 'DynamicMeshSpawner' would be spawned everytime I hit 'P' on the keyboard. When the instance of this class is created, it calls the constructor, which spawns the cube with the material applied. I did the class instance spawning stuff in BluePrints using the SpawnActor node.
The conditions that you require for spawning stuff would obviously depend on the application.
This method works for normal Materials but NOT Material Instances. I believe you would have to make changes to the type of TheMaterial, the ConstructorHelper call, and the cast from the material reference into TheMaterial in order to make it function.
I'm confident that this would work with Animated materials as well, meaning that the 2D animations would need to be converted into a Material of some sort.
Perhaps the link below would help.
https://forums.unrealengine.com/showthread.php?6744-Flipbook-material-to-recreate-an-animated-gif
EDIT 2:
Below are a very good set of examples on how to procedurally create objects in Unreal. Leaving it here for posterity and in case anyone comes looking.
https://github.com/SiggiG/ProceduralMeshes/

Is inheritance the right choice for this 'story and option' based adventure application?

A friend and myself are creating a Goosebumps-style adventure game, where at each stage the user is presented with a potential set of 4 choices, and the user's choice affects the outcome of the story.
What data structure should I use for this?
This is my main idea -- Objects
In trying to keep the game as close to the real life idea of these cards as possible, create one 'card' base class, and have lots of other cards inherit from this - superclass would contain Stringx5( x1story x4choiceStories) intx5 (x1CardIDNumber x4CardIDChoices).
This would then allow me to pump out objects easily with the material we already have, and have a system class controlling all the processing for user choices and displaying information onscreen. And again with the system in place and a base card class, it would allow for different stories in the future and whatnot. Trying to make this as reusable as possible and write as little code as possible (I'm not writing over a thousand if Statements.)
One thing that isn't clear to me (and the actual reason I'm posting this question in my inability to find the answer): isn't inheritance meant to be for other classes that are similar but with slight differences, e.g. managers and employees, making my idea completely wrong and a massive waste of memory?
I have looked into the following:
Hash tables: the examples seem to be more phone book oriented, and I don't think it would suit my needs
Abstraction to define a story type: also doesn't seem to suit my needs
No real need for inheritance as the cards are exactly the same, just the data on them changes. I'd use inheritance if there were special cards that need to behave differently to all the rest.
You can do what you want with something like this pseudo code:
class Card {
Card getChoice(int i); // returns choices[i]
string storyText;
Card[] choices; // Use an stl collection rather than an array for ease of addition.
}
Basically you create each card so it links to all the other cards (trick here is making sure you create the cards in the right order - easy solution: create them with no choices and add the different choices via an addChoice(Card) method later.
Your Game class starts with the first card (basically the head of a tree to all the cards), and does something like:
Card runCard(Card card)
{
Card nextCard = null;
showStoryText(card);
// Display a line for each choice in the card and get the user's response.
// Convert the response to the correct index.
int selection = promptForAction(card);
if (selection >= 0 && selection < card.numChoices()) {
nextCard = card.getChoice(selection);
}
return nextCard;
}
void run()
{
Card card = firstCard;
while(card != null) {
card = runCard(card);
}
}
This shouldn't be too bad. Essentially you need a tree structure.
Your main class could look like (forgive my lack of knowledge of c++)
class Node {
Node option1;
Node option2;
Node option3;
Node option4;
}
So your Node instances can point to other instances of Node.
It's probably better to have some sort of collection of Node instances, that way you can have as many or as few as you want. You can add a field to Node that indicates which option it is (1, 2, etc).
The only other thing you need is reference to the initial Node.