# Question
Title: C++: Setup the basic Update function in different classes which all derive from GameObject
Im working on a little game-framework in c++. Currently i have a (base)class called "GameObject" from which all future in-game objects will derive from. Class enemy will be `class Enemy : public GameObject` and class Player will be `class Player : public GameObject`

This way, i can store all my gameobjects in an array of type GameObject and manage them easily and they will all have the basic game-object variables such as x/y/z coordinates, scale, etc. So what i eventually want is to be able to quickly create a new game-object by creating a new class and then simply inheriting from GameObject.

Know how in Unity every game-object monobehaviour script has a start function and an update method? That's what im trying to recreate, and my teacher has been able to recreate in the past using Java. (except he simply used the constructor instead of a "Start" method)

Here is where my problem comes in: I can't find a way to call the `Update()` method from all those classes that derive from GameObject. My teacher was able to get this working in a small java framework by putting this for-loop in the main-loop of the program:

```
if(_gameObjList.size() != null){
   for(int i = 0; i < _gameObjList.size(); i++)
   {
     _gameObjList.get(i).Update();
   }
}

```

Now im pretty sure that this is the correct c++ equilavent of that code:

```
if(_gameObjList.size() > 0){
   for(unsigned int i = 0; i < _gameObjList.size(); i++)
   {
     _gameObjList[i].Update();
   }
}

```

In the GameObject class of that java program there's an empty `Update()` method, which, if removed will break everything, and offcourse in every class that derives from GameObject there's also their own `Update()` method which for some reason gets called too, but does not give an error if removed. So this way all `Update()` methods from all classes that derive from GameObject get called even though from the code, it looks like it's just calling that `Update()` method from the GameObject class itself and not the classes that derive from it.

So now i wish to use this magic in my c++ program but it doesn't work. It just calls the Update method from the GameObject class and does nothing else :/ It won't call the Update functions of the classes that derive from it. So perhaps there are any sorcerers online on this forum who can explain this magic to me and how to use it? Or perhaps another way of executing all Update functions without calling all of them specifically?

Sidenote: if in the java program, i change the name of the `Update()` function in one of the classes that derive from GameObject, it won't be called/executed but doesn't give me any errors either. That specific object just won't be updated anymore.

Sorry for writing all this text, i just want to be as clear as possible.

# Answer
> 1 votes
You'd want to use polymorphism. In your case :

```
class GameObject {
  public:
    //=0 means that child classes will have to override Update, otherwise
    //they will be considered abstract
    //could be replaced with default logic
    virtual void Update() = 0;
    virtual ~GameObject() = default;
};

class Enemy : public GameObject {
  public:
    virtual void Update() override {
      //if GameObject implements default logic, add :
      //this->GameObject::Update();
    }
};

```

---
Tags: c++, architecture, data-structure, inheritance
---


# Question
Title: I've completed my mobile game - now what?
After months of development, I've finally finished my mobile app, but I have no idea what to do next. I want to publish my app to the Google Play Store and the App Store, yet I don't know how. I've done tons of research and every single website shows different methods and requirements. I've seen that I'm supposed to have some kind of license, a specific certificate, and all these other connections that I'm really confused on how I'm supposed to get them, and where to even start. I've gotten as far as getting Apple Developer and Google Developer, but that's basically it. I just want a simple step-to-step guide. I've already looked on StackExchange for an answer, but all have slightly different questions, such as marketing the app and updating the app, but nothing on how to get it out there.

I'm using Unity as an engine and X-Code via my Mac to test my app on my iPhone.

I appreciate any help in advance. Thank you!

# Answer
> 1 votes
I think official site is best guide, this may help:

https://developer.apple.com/ios/submit/

https://developer.apple.com/app-store/submissions/

https://developer.android.com/studio/publish/

---
Tags: unity, android, ios, mobile, publishing
---


title: How do you program diagonal movement?

text:
# Question
Title: How do you program diagonal movement?
I'm wondering how a diagonal element that moves along a diagonal path that hops at each tick of the computer clock is able to travel a greater distance along the screen than an element moving at each tick along left-right or up-down paths (since it's a square lattice and the diagonal element of a triangle is the same length of the two legs of a 45-45-90 triangle, or just take a square grouping of nine pixels, the diagonal is 3 pixels, and the left-right and up-down direction are 3 pixels also, a violation of the hypotenuse, but you can still measure the diagonal distance of a square pixel with a ruler), so things move faster along the diagonal, and you'd have to also take into account variations of lower angled paths that move at a lower angle diagonal (they still move faster than left-right elements). I'm wondering if that's a source of jitter in a character object that is composed of a large blob of pixels, has somebody already figured out a ratio in reducing the speed of the diagonal moving pixels while still maintaining the shape of the blob of the character moving.

# Answer
> 4 votes
Vector mathematics is used to create motion in nearly every game these days. Said method uses fractional values typically calculated using floating-point or fixed-point arithmetic representations.

DMGregory correctly points out that `sqrt( 1*1 + 1*1) = sqrt(2) = 1.414`. So if you are moving an object by `1` pixel in both `x` and `y` each frame, then yes, the total distance travelled is roughly `1.4` units. But that's *not* the way we typically move things in games (these days) as pixels are no longer the primary basis for calculation of movement in most cases; and in any case, this approach was always wrong if you were then only moving `1.0` pixels in either `x` or `y`.

Instead, regardless of the direction being moved, a direction vector is always *normalized* before being multiplied by some scalar speed. Normalization means that we divide a vector's components (`x`, `y`) by the vector's overall magnitude, resulting in a magnitude of `1.0`. So in our given case, a diagonal vector of length / magnitude `1.414` will have each of its components of length `1.0` divided by `1.414` resulting in absolute `x` and `y` values (talking about 2D here) of about `0.707` which results then in a vector magnitude of `1.0` rather than `1.414`. You can see, on the other hand, how if a vector `(1.0, 0.0)` is normalized, it *still* has a magnitude of `1.0`.

And no, you don't notice any jitter moving on the diagonal compared to moving on the horizontal or the vertical, especially on today's high-resolution displays; if that were ever the case, it may have been so in the days of 320x200 or lower resolutions, but even there, the human eye doesn't tend to pick such things up that easily, being more absorbed in the *smoothness* of the motion itself.

# Answer
> 0 votes
It sounds like you are trying to make the grid based algorithms of cellular automata match a real world concept of space. While the two worlds are quite different spatially you could try to balance the weights of diagonal cells by multiplying them by the normalized difference in distances as described by Arcane Engineer. (ie. scaling the propagation rate by .707)

# Answer
> 0 votes
You could accelerate the presentation of the cells in how they are presented -no change in underlying cellular automata rule ie the timing of presentation-, in certain directions, like vertical, with the horizont. no accel., and diagonal faster naturall to create larger rotations of pixels. Overlay that with one that has a faster presentation in vertical and horizontal, no faster presentation in diagonal (it already is fast) and you get fixed points. Now have a genetic algorithm mutating the two, and you should get those fixed points mixed in the larger clouds of rotation, and the large clouds getting caught up in something more complicated, -----no change in underlying rule---- in any subset of interacting ones in the genetic algorithm.

---
Tags: movement
---


# Question
Title: Unity move Vector3 position with transform
How can I move a new Vector3 position with a Transform? Like the transform is the parent the vector.

Example if I want to push the x position for example by 10 value and I rotate the transform its push in world coordinate but I want to push by the rotation too.

```
    void Update () {
    temp = transform.Find("Transform").position;
    temp = new Vector3(temp.x + 10.0f, temp.y, temp.z);

    Debug.DrawLine(transform.Find("Transform").position, temp);
}

```

# Answer
This is what the `transform.TransformPoint` method does: takes a position in local coordinates and transforms it to world coordinates as though it were a child of the transform.

So you can do something like this:

```
// First, transform the point into a local offset.
Vector3 localSpacePoint;

public void SetFollowingPoint(Vector3 worldSpacePoint) {
     localSpacePoint = transform.InverseTransformPoint(worldSpacePoint);
}

// Then move your transform, and get the new position with:

public Vector3 GetFollowingPoint() {
     return transform.TransformPoint(localSpacePoint);
}

```

You'll notice there are also `transform.[Inverse]TransformVector/Direction`, too. These are for...

* **Direction**: things that should be affected by rotation, but not scale or translation (eg. a heading direction)
* **Vector**: things that should be affected by rotation and scale, but not by translation (eg. the relative offset between two objects that move together)
* **Point**: things that should be affected by rotation, scale, and translation (eg. positions on your object, like attachment points)
> 2 votes

---
Tags: unity, rotation, transformation
---


title: GLFW - Camera rotation system

text:
# Question
Title: GLFW - Camera rotation system
I need to make a camera rotation system similar to the one here

http://madebyevan.com/webgl-path-tracing/

To rotate, press the Left mouse button and drag. So far I figured a basic idea of how this could be implemented.

Note that although it looks like the scene is rotating in front of the camera but in my case I want to rotate the camera instead. Since the scene contains hundreds of thousands of triangles and I wouldn't wanna apply a matrix operation to each of them.

I have represented my camera by a 4x4 matrix. The columns from 1 to 4 are side, up, look at and eye respectively.

So here's what I thought so far.

1) Subtract old cursor position from new cursor position. Doing this for X and Y we get a direction vector as to where the mouse is headed.

2) Invert this direction. And translate the camera a little in this direction. So if the mouse is headed right, the camera heads left. This is done by checking the components of the direction vector.

```
if (dir.x < 0)
    cam.eye += side
if(dir.x > 0)
    cam.eye -= side
if (dir.y < 0)
    cam.eye += up
if(dir.x > 0)
   cam.eye -= up

```

Note the translations are inverse. If less than zero than add the side vector instead of subtracting it.

3) Now find a vector perpendicular to it. So if the mouse was headed left or right the vector perpendicular to it is the Y axis. I calculate this by taking the `cross(vec(0,0,1), direction_vector)`. Note this is not the inverse but the actual direction vector.

4) Rotate the camera a little along this perpendicular axis a little.

If you imagine these operations for the X axis. This feels like the camera is moving in some sort of circle around the scene. That is, the camera translates a little, then rotates. Next time it translates by adding the side (which was changed when it first rotated) it moves a little diagonally. In this way it feels like it rotates in a circle.

So this works somewhat fine for pure X and Y rotation and upto a certain extent. Fails when i move the mouse diagonally or in Pure X/Y rotation when I go beyond a certain point probably 90 degrees.

Any advice or suggestions? I am not using OpenGL instead doing this with GLFW and GLM. The renderer is a raytracer/pathtracer.

# Answer
---

## About the linked Demo

The linked demo uses **euler angles**, has a locked target on the center of the scene, and you drag left aqnd right to move the first euler angle, or up and down right to move the second one. The third euler angle is not controlled and remains where it starts.

It is geographic coordinates: the first angle is the rotation on the horizontal axis (Longitude), and second angle is the angular elevation from that plane (Latitude). The first angle can do a full rotation, while the second is limited to minus one quarter rotation to plus one quarter rotation. You can confirm on the demo.

---

To implement it, store the two angles I mention above in varialbes, update them based on the drag gesture, and use them to compute the position of the camera (and the up vector too, given the way you represent your camera).

---

## Camera Representation

A virtual camera has `position`, `orientation` and a `viewing volume` (usually a perspective projection, can be orthogonal, skwed or something else).

At the end a position and orientation becomes a matrix transformation.

I will not be talking about the viewing volume.

---

What you have is a lookat matrix. It is a valid transformation matrix.

However, I am not a fan of it, because it sticks you to the vectors (`side`, `up`, `lookat` and `eye`). It gives you the idea of modifying the vectors directly, which is error prone. For instance, you may end up with a combination of `side`, `up` and `lookat` that does not make sense. We always need to move `side`, `up` and `lookat` together.

We can acomplish that by treating them as a matrix instead of treating them as vectors. I am suggesting to forget about `side`, `up`, `lookat` and `eye`. I am suggesting to not treat those components of the matrix as vector and to not operate on them directly. Use them as a matrix. Or rahter, I should say, *just* as a matrix.

**Addendum**: To move the camera, you can create a translation matrix and apply it to the one of the camera. Similarly to rotate it. However to replicate the demo, recompute the the matrix transformation of the camera each time the user drags.

**Note**: Whatever the vectors are columns or rows is convention. OpenGL (which GLFW uses internally) only cares about the order in memory. This can also be a source of confusion. *In fact, I didn't think you had it right, just because last time I was working with them, I was considering them rows.*

---

## Camera Control

There are many models for camera control. There is the static camera that does nothing. The fixed camera that does not move but changes orientation to follow the action. There are cameras that follow the action at a fixed distance. There are variants that are controlled by the player. There are scripted sequences where the camera follows a predefined trajectory...

A common idea is to have the camera follow a object that is affected by physics and collisions (that is effectively what you would do in a FPS). However, if this is physic object is on itself separate from the avatar (for example a third person camera), it also means that the camera can bumb or even get stuck due to collisions. And we do not want that... we would use ray cast checks to anticipate and avoid the collisions. And we want this collision avoidance to be smooth and to keep the action in view.

There is then the problem of objects obscuring the view of the avatar. Some games will have those objects appear translucid, or will render silhouettes, etc.

Futhermore, I have been saying "*the action*", because the camera may not only be following the player's avatar. For instance you may offset it to show points of interest or to keep nearby enemies in frame.

*Sorry, I do not have any books to suggest. Hopefully the presentation "50 Game Camera Mistakes" can help you.*

---

**Orbit Camera**

What we have in the linked demo is an orbit camera. As I said at the start, it is controlled by euler angles. I will be refering to the point around which the camera orbits as the "target".

Start by declaring your first and second euler angles. Then each time the player drags, you increment the euler angles accordingly to the drag distance, horizontally and vertically respectively. *Note that you can do both movements in the same drag gesture.*

The position of the camera will be an initial position that you rotate by the euler angles... And the orientation of the camara will be dictated by that same rotation.

**Note**: I am assuming that you pick an starting position and orientation that is at desired distance from the target and looking at it. Then all you need to do is to get the correct rotation from the euler angles.

To get that rotation, your library has an utility to create a rotation transformation over one of the main axis. Use it to create two rotation matrix (one for each angle) and combine them (multiply them together).

**Note**: Remember that the order matters in matrix multiplication.

*Again, forget about `side`, `up`, `lookat` and `eye`.*
> 1 votes

---
Tags: camera, rotation, glm, glfw
---


# Question
Title: How can I deploy and unreal engine windows exe build to the cloud?
I don’t have a coding background, so I am struggling with this. Someone will have to dumb down a lot of the language for me.

I’m trying to deploy my unreal engine game to a cloud computing service using the .exe file I built. I would like to do this in order to maintain the maximum quality of the game and have multiple users access the game simultaneously by a hyperlink. I don’t need the users interacting with each other. I was able to get this to work with x.io but that service is kind of limited. I also messed around with AWS but all of that was too confusing for me. Please let me know if the community can guide me.

# Answer
# How to do it (in simplified steps)

1. Setup your game in a VM or docker like system
2. Make a website (or application) that will render a stream of video from the cloud game
3. Make that website send the player commands to the cloud game
4. Manipulate the game according to the player commands
5. Repeat 4 until the game session is done

---

# Why you don't want to stream (most games)

Look at reviews of a service called "OnLive" which did this concept almost a decade ago...

**Latency**

In order for the players view to update they need to do something with controls but then that input needs to be sent to the cloud (taking time) that then needs to be processed by the actual game (ok, but every game needs todo that), then the image needs to be compressed and sent to the player (with takes more time)...

Normal game:

```
Player input -----------------> Process input --------------------> view update
  (0ms)                            (1-30ms)                           (0ms)

```

Streaming game:

```
Player input -> Send to cloud -> Process input -> compress & send -> view update
  (0ms)           (1-1000ms)       (1-30ms)         (1-1000ms)         (1-30ms)

```

Now if your building a strategy game where almost everything is slow moving and the important game controls stay in the same place you might be able to get away with it since drops in frame rate aren't as noticeable.

**Poor bandwidth**

Your server might have the worlds best connection to the internet, but what about your players what about the people in places where internet is just terrible (like rural areas or Australia) they have limited upload/download speeds. What happens when your trying to watch a video and can't download it as fast as your watching it? It buffers... you don't want that for your game since it needs to be constantly updating. So you can go and compress the video down to something which uses less bandwidth, this is like reducing the quality of a youtube video so it doesn't have to buffer.

Great! but now the game looks like crap. Certain Ui elements like text will become unreadable and if your game requires keen eyes in order to see enemies which are far away the player likely won't see them. This depends on your game again, maybe you're making something that is extremely easy to see and play at low resolution? like MiniMetro. Alternatively you could build your game around having scalable UI elements and gameplay systems which take into account the current visibility of the player.

**Unreliable connection**

So you have your game and it plays perfectly for you and your friends. Someone comes along who has an excellent connection however their packet loss is extremely high resulting in 50% of upload packets being lost. How will your game cope when it only receives half the input data? or only intermittently gets input commands? Are you prepared for a player who is clicking the play button and nothing happens?

There isn't much you can do about this other than letting the player know that your not receiving all of their commands. You might be able to resolve this by connecting them to a different data center but in the end the problem could be with their ISP, Computer, your server, your datacenter infrastructure, etc.

**Cloud computing prices**

Since your in the cloud your going to need computers. Luckily you have plenty of providers to choose from Azure, AWS, Google Cloud. But the majority of VMs that they have available to rent don't have GPUs! Not even integrated GPUs. In order to render you either have to do it on the CPU (like downloading a picture via dial-up speeds) or pay for a special GPU instance.

GPU VMs come in 2 flavours:

* Built in GPU
* Remote GPU

The built-in GPU instances are expensive costing $15.84 per hour which doesn't sound like a lot until you realize that you may need multiple instances and they may be running 24/7. I personally don't know much about remote GPU instances, the GPU is located in a seperate computer and your VM accesses it remotely so I imagine that latency will be even higher for those, but they are a lot cheaper costing $0.05 per hour for the cheapest.

Maybe you don't care about money, know something I don't or have the ability to get a deal with a cloud provider/Nvidia Grid.

**Summary**

There are many more examples of possible problems but ultimately if you think that this doesn't really affect you... go ahead and make the game but study how packets work and look at ALL the edge cases that the designers of TCP have overcome and how every edge case could affect the game/user experience.

Good luck with your game, if it succeeds it may become a case study for the gaming industry on how to stream games.
> 1 votes

---
Tags: architecture, client-server, web, cloud-computing, virtual-machines
---


title: Unity + Admob - EEA checking

text:
# Question
Title: Unity + Admob - EEA checking
The Admob plugin for Unity - Android does not supply an EEA permission request form like the standard Android plugin does. So, I have created my own and it works great.

My only problem is how do I check if I am in the EEA and need to request permission? Again, this feature is supplied for a standard Android app.

I know I can make a simple Android plug-in and call it but that seems a bit over the top.

# Answer
Using AdMob’s Consent SDK, which you can import using the Jar Resolver (see below) or as a line in the mainTemplate.gradle override, you can interact with Java classes using a set of classes:

* AndroidJavaObject which is a class that can instantiate and act as a Java object
* AndroidJavaClass which is similar but works for calling static methods on Java classes
* AndroidJavaProxy which can act as a Java interface in C#. Implement the Java interface’s methods by duplicating the correct name and method signatures (using AndroidJavaObject for any Java object arguments)
* AndroidJavaRunnable lets you pass in a C# method or anonymous delegate as a `java.lang.Runnable`.

For example, converting the first block of code in the Consent SDK integration guide from Java to C#:

```
        ConsentInformation consentInformation = ConsentInformation.getInstance(context);
        String[] publisherIds = {"pub-0123456789012345"};
        consentInformation.requestConsentInfoUpdate(publisherIds, new ConsentInfoUpdateListener() {
            @Override
            public void onConsentInfoUpdated(ConsentStatus consentStatus) {
                 // User's consent status successfully updated.
            }

            @Override
            public void onFailedToUpdateConsentInfo(String errorDescription) {
                 // User's consent status failed to update.
            }
        });

```

Becomes

```
        AndroidJavaClass playerClass = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
        AndroidJavaObject context = playerClass.GetStatic<AndroidJavaObject> ("currentActivity");
        AndroidJavaObject consentInformation = new AndroidJavaClass("com.google.ads.consent.ConsentInformation").CallStatic<AndroidJavaObject>("getInstance",context);
        string[] publisherIds = new[] {"pub-0123456789012345"};
        consentInformation.Call("requestConsentInfoUpdate", publisherIds, new ConsentInfoUpdateListener());

//...

class ConsentInfoUpdateListener : AndroidJavaProxy {
    public ConsentInfoUpdateListener() : base("com.google.ads.consent.ConsentInfoUpdateListener") {}

    public void onConsentInfoUpdated(AndroidJavaObject consentStatusObj) {
        // User's consent status successfully updated.
        // Note that Java Enums are syntax sugar for objects, so we need to get the index to figure out which one it is:
        int consentStatus = consentStatusObj.Call<int>("ordinal");
        //for clarity, you could declare your own copy of the enum in C#, but you can also just compare to the int value of the original (0,1,2 for PERSONALIZED, NON_PERSONALIZED, UNKNOWN)
    }

    public void onFailedToUpdateConsentInfo(string errorDescription) {
         // User's consent status failed to update.
    }
}

```

If you want to use the jar resolver to integrate the consent SDK, assuming you are using any recent version of said resolver that uses xml files for dependency definitions, you can add this xml file to your project (probably in an Editor folder, but anywhere should technically work):

```
<dependencies>
  <androidPackages>
    <androidPackage spec="com.google.android.ads.consent:consent-library:1.0.6" />
  </androidPackages>
  <!-- you can also include the iOS version here, although interacting with that version is outside the scope of this answer, and if you are targeting Android only, this section is not necessary: -->
  <iosPods>
    <iosPod name="PersonalizedAdConsent"/>
  </iosPods>
</dependencies>

```
> 2 votes

---
Tags: unity, android, admob
---


# Question
Title: How to set a box2d body to follow a strict path
I'm making an infinite runner type game and I want one of my enemies (when it's created) to swoop down in a sort of U motion where it'll hit the player if they don't react quick enough once the enemy (bat) leaves the screen it'll be destroyed and created again once certain requirements are met . The path will be the same each time so I don't need anything to do with AI. Unfortunately I'm only in grade 10 so calculus makes no sense to me and neither does the pathfinding libgdx documentation. I either need something similar to this (But written for libgdx) or some way to get a box2d body to move in an exact way.

My game is structured like this:

in Bat.java:

```
public class Bat extends Sprite {

private World world;

public Bat(GameScreen screen) {

    this.world = screen.getWorld();
}

```

In GameScreen.Java

```
public class GameScreen implements Screen {

private Bat bat = new Bat(this);

public World getWorld(){
    return world;
}

```

# Answer
> 3 votes
If you don't need the bat to be a **Box2D** `Body` then an easy way to achieve this is just to use a `Spline`, `BSpline` or `CatmullRomSpline` and let that be the path of the bat.

If you need the bat to be a **Box2D** `Body` then I would still use one of the splines to define the path, then use a kinetic **Box2D** `Body` and set the linear velocity to be the delta between the bat's current position and the target position.

For example, in the animation below the small square is the player, the tiny circle is the bat, the six-sided shape is the target position for the bat and the path is the bendy thing.

As the player gets close to the bat's X position the bat starts following the path.

Full working example code:

```
package com.bornander.playground3d;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.CatmullRomSpline;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;

public class Playground3DGame extends ApplicationAdapter {
    private OrthographicCamera camera;
    private ShapeRenderer shapeRenderer;
    private World world;
    private Box2DDebugRenderer debugRenderer;

    private Body player;
    private Body bat;
    private boolean batIsHunting = false;
    private float batTime = 0.0f;

    private CatmullRomSpline<Vector2> batPath;
    private Vector2 batTargetPosition = new Vector2();

    @Override
    public void create() {
        float aspectRatio = (float)Gdx.graphics.getHeight() / (float)Gdx.graphics.getWidth();
        float width = 60;
        float height = width * aspectRatio;
        camera = new OrthographicCamera(width, height);

        world = new World(new Vector2(0,-20), false);
        debugRenderer = new Box2DDebugRenderer();

        shapeRenderer = new ShapeRenderer();

        // Floor
        BodyDef floorDefinition = new BodyDef();
        floorDefinition.type = BodyType.StaticBody;

        PolygonShape floorShape = new PolygonShape();
        floorShape.setAsBox(20, 2, Vector2.Zero, 0f);

        FixtureDef floorFixture = new FixtureDef();
        floorFixture.shape = floorShape;
        floorFixture.friction = 0.5f;

        Body floor = world.createBody(floorDefinition);
        floor.createFixture(floorFixture);

        // Player
        BodyDef playerDefinition = new BodyDef();
        playerDefinition.type = BodyType.DynamicBody;

        PolygonShape playerShape = new PolygonShape();
        playerShape.setAsBox(1, 1, new Vector2(0, 8), 0f);

        FixtureDef playerFixture = new FixtureDef();
        playerFixture.shape = playerShape;
        playerFixture.friction = 0.5f;
        playerFixture.density = 1.0f;

        player = world.createBody(playerDefinition);
        player.createFixture(playerFixture);

        // Bat
        BodyDef batDefinition = new BodyDef();
        batDefinition.type = BodyType.KinematicBody;

        CircleShape batShape = new CircleShape();
        batShape.setRadius(0.5f);
        batShape.setPosition(new Vector2(0, 0));

        FixtureDef batFixture = new FixtureDef();
        batFixture.shape = batShape;
        batFixture.friction = 0.5f;
        batFixture.density = 1.0f;

        bat = world.createBody(batDefinition);
        bat.setTransform(16, 10, 0);
        bat.createFixture(batFixture);

        batPath = new CatmullRomSpline<Vector2>(new Vector2[] {
                new Vector2(16, 10),
                new Vector2(10, 2),
                new Vector2(0, 10)
        }, true);
    }

    @Override
    public void render() {
        // Control the player using input
        if (Gdx.input.isKeyPressed(Keys.LEFT))
            player.applyForceToCenter(-200, 0, true);
        if (Gdx.input.isKeyPressed(Keys.RIGHT))
            player.applyForceToCenter(200, 0, true);
        if (Gdx.input.isKeyJustPressed(Keys.SPACE) && Math.abs(player.getLinearVelocity().y) < 0.1f)
            player.applyForceToCenter(0, 4000, true);

        // Control the bat
        if (!batIsHunting && (player.getPosition().x > 8 && player.getPosition().x < 9)) {
            batIsHunting = true;
        }

        if (batIsHunting) {
            batTime += Gdx.graphics.getDeltaTime();
            final float maxHuntTime = 4.0f; // Hunt will last for 4 seconds, get a fraction value of this between 0 and 1.
            float f = batTime / maxHuntTime;
            if (f <= 1.0f) {
                Vector2 bodyPosition = bat.getWorldCenter();
                batPath.valueAt(batTargetPosition, f);
                Vector2 positionDelta = (new Vector2(batTargetPosition)).sub(bodyPosition);

                bat.setLinearVelocity(positionDelta.scl(10));
            }
            else {
                batTime = 0;
                batIsHunting = false;
                bat.setLinearVelocity(0, 0);
            }
        }

        camera.update();
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
        world.step(Gdx.graphics.getDeltaTime(), 8, 4);
        debugRenderer.render(world, camera.combined);

        // Debug draw the path of the bat
        int k = 100;
        Vector2[] points = new Vector2[k];
        for(int i = 0; i < k; ++i)
        {
            points[i] = new Vector2();
            batPath.valueAt(points[i], ((float)i)/((float)k-1));
        }

        shapeRenderer.setProjectionMatrix(camera.combined);
        shapeRenderer.begin(ShapeType.Line);
        for(int i = 0; i < k-1; ++i)
        {
            shapeRenderer.line(points[i], points[i+1]);
        }

        shapeRenderer.circle(batTargetPosition.x, batTargetPosition.y, 1.0f);
        shapeRenderer.end();
    }
}

```

The advantage with this approach is that it's easy to define complex paths using splines.

---
Tags: java, libgdx, box2d
---


# Question
Title: Looking for a square-to-hex pixel coords algorithm
So as the headline suggests, I am looking for an algorithm/algorithms used for square-to-hex and hex-to-square pixel coordinates convertion.

I have an image which looks kinda "interpolated", meaning some pixels are of one colour, while some have a slightly different shade etc. So pixel colour kinda stores offset or whatever. If you're interested, it's here

It has to do with pathfinding, the logical part of map is made of hexmap while the visual part of map is made of squares. Here, size of the square = 1 pixel, same hex size is equal to 1 pixel.

So basically I will be trying to convert an image with hex pixel coords to image with square pixel coords and vise versa.

I'm sorry if this was answered already somewhere, I couldn't find it anywhere.

P.S. I reverse engineered the image, so in binary it was only X and Y coords stored plus a third byte value which I took as a greyscale colour (later compared with another image and it matched)

Image:

# Answer
> 1 votes
Convert in-hex coordinates to screen space and work therein, as that is the common pixel space.

To know where your pixel-in-a-hex is in screen space, just get the hex's offset (which I presume you have specified?) from top left (or bottom left in OpenGL) of the screen, then get your pixel offset into the hex (multiplying by scale if you are zoomed out or in - i.e. not rendering at 1:1 scale), and add them. That gives you your screen-space co-ords.

To go back to hex space from screen space, reverse the process: Subtract the hex's offset from the coordinates, and divide by scale.

---
Tags: algorithm, path-finding, grid, pixel, hexagonal-grid
---


# Question
Title: Does destroying body also destroys the sprite?
Suppose a sprite is attached to a box2d body. And `world.destroyBody(b);` is getting called then the sprite also get destroyed or it stays there in memory. In my situation lots of box2d bodies are getting created and destroyed and after a delay of few seconds the sprite disappears. Here's the snippet of where body is getting destroyed:

```
    @Override
public void act(float delta) {
    super.act(delta);
    camera.update();
    world.step(1/60f, 6, 3);
    if (enemy_destroy) {
        Array<Body> bodies = new Array<Body>();
        world.getBodies(bodies);
        for(int i = 0; i < bodies.size; i++) {
            Body b = bodies.get(i);
            if (b.getUserData() instanceof Boolean) {
                world.destroyBody(b);
                b.setActive(false);
            }
        }
    }
}

```

# Answer
No; destroying the body does *not* automatically destroy the sprite. You have to remove it manually. Assuming you're using LibGDX's `Sprite` object you simply call `dispose()` on the texture object linked to the sprite: `sprite.getTexture().dispose();`. **Note that this will render the `Texture` object unusable!**

As for the sprites randomly disappearing: The only reason that I can see that destroying a body would also destroy any sprite attached to it is if the body is holding the last reference to the sprite, so when the body is garbage collected so is the sprite. Although more likely is that there is simply a result of some code you wrote. Try using a debugger to find out why that is happening.
> 1 votes

---
Tags: libgdx, collision-detection, sprites, box2d
---


title: Authoratitive server for Enemy AI

text:
# Question
Title: Authoratitive server for Enemy AI
I am writting a real time game which contains Enemy AI I need write Enemy AI on server to send action( move, attack, .. ) to clients? or any way to do that? If i write Enemy AI on client? how to be authoritative enemy's actions?

# Answer
> 0 votes
Enemy AI is one of those things which should always be handled on the server.

Remember that anything which happens on the client can be manipulated by a hacked client. If you let the client handle enemies, the client can just claim that the ultimate raid boss just committed suicide and dropped the rarest item in the game.

But even if you assume that all your clients play fairly (you can't), that you can just slap an anti cheat tool on it and it will fix any cheating problems (it won't) or that you can detect cheating heuristically (will cause you more problems than it solves), you still need to deal with synchronization problems. What do you do if multiple clients fight the same monster and they come to different conclusions about how the fight turned out? Due to network latency, this is quite likely to happen.

---
Tags: mmo
---


# Question
Title: How to store and retrieve user data in a multiplayer game
I am building a multiplayer game with a team and each player will have a multiplayer rank, a matchmaking rating (MMR), a username, and possibly a picture, a description etc. We are planning on delivering the game on multiple platforms such as Steam, itch.io and GoG.

Since I am using Unity, how can I store and retrieve such data independently of the platform ? Is there a builtin service provided by Unity or do I have to create some SQL database and code all of the logic to use it ?

# Answer
> 4 votes
Unity does not include a server side persistence solution out of the box. As far as I can tell the only storage solution Unity includes is PlayerPerfs, but that is client side.

However that does not mean you have to create a SQL database. Some games use services that provide a nice interface for NoSQL databases (for example MongoDB via GameSparks or DynamoDB via Amazon). You may also get a web hosting with a SQL database and build a custom API. You may also setup your own servers if you have the know-how.

From a security stand point, if you are accessing the database directly, you will have the credentials in the client, and there could be ways to intercept the traffic. Intead use (or create) an API that allows players to authenticate with an account, and allows the client to call function or microservices with the session of the player. Then in the server side, you will have the database access logic. Also, make sure you are getting a connection to the server over a secure channel.

If you are getting a web hosting or setting up your own server, make sure to get a domain, setup HTTPS (you can get a certificate from Let's Encrypt), you will need to implement access control and of course the database abstraction.

With GameSparks you would setup their authentication system, and use Cloud Code (JavaScript) to access the server database (tutorials available on their website, start with the Unity Setup).

With Amazon, you can use Cognito for authentication and user data, and if you need something more involved you can use AWS Lambda (JavaScript, C#, Java, Go or Python) to access DynamoDB (see the AWS SDK for .NET, nugets available).

Whatever it is you choose, it is common wisdom to abstract it and isolate it, make sure it is easy to replace.

---
Tags: unity, multiplayer, databases, unity-networking
---


title: Java Slick2d image depth/layering

text:
# Question
Title: Java Slick2d image depth/layering
I'm making a topdown 2d game, and I've made a decent entity system so far. But I want to do the following with it: I want to have drawing depth, so if, for instance, a tree is above another tree, then it should be drawn underneath the other tree. Here is basically a picture of what I mean.

**This is what I'm trying to avoid:**

**Instead of that I want something like this:**

If you have any idea how to do this, please tell me. If you need any code, here's basically what I do: In my main class I call a generate entities class. In that then I add Tree class-es to an arraylist through which it renders them. Thanks.

# Answer
I like the other answers but I think they are too verbal. What you can do is simple:

* Make an array that holds all the objects that are meant to be drawn depending on their Y. Add any object that can either walk in front of other object, or that it can hide objects behind it. For example, don't add the ground as it always drawing below them, but add the trees, probably a house (assuming you can walk behind it) and characters.
* Sort the array based on the `Y` of those objects, from lower to higher. Now when you draw these objects, draw them from `0` to `array.length`, objects with low value will be drawn first, then objects with higher value will be drawn on top of them.

Sorting can be resource-intensive if you are sorting the whole array every frame, especially with having more and more objects in it. Considering that the array is initially sorted based on the `Y` value, every time an object's `Y` coordinates change, move them up/down the array based on its neighbours, no need to sort the rest of the array.
> 1 votes

# Answer
It's quite simple, you're already sort of doing it with your terrain, right? You draw your terrain first and then you draw your entities. Whatever is drawn first will be drawn further back in the depth. What you can do for your drawable entities is give them a depth sorting index. Then when you tell them to draw you sort them into collections based on their depth and actually draw them from lowest depth to highest depth.

If entities draw immediately when you tell them to you may need to reorganize that. What I do in my engine is I have a Rendering Manager class. When I want to draw something I pass what I want to draw to my Rendering Manager which sorts them into different collections based on their properties and then draws them in the right order with the right properties. The Rendering Manager is the class that actually executes the draw logic; when Entities "Draw" they just alert the Rendering Manager that they want to be drawn.

I don't know how in-depth you've gotten with Slick and frankly I'm not really familiar with the API but it appears to mostly expose OpenGL. If you represent your entities with a world matrix you can simplify this process quite a bit. You're working in 2D but OpenGL always has a concept of all 3 dimensions. The Z axis can act as a depth ordering axis of sorts. The further back something is positioned on the Z axis from your camera, the further back in the scene it will be drawn. If you do this you don't have to worry about the order of your draw calls at all but rather objects should naturally be drawn behind other objects if they're positioned further away on the Z axis. If you're not directly doing any OpenGL calls this won't really be possible unless Slick2D gives you a way to represent position on the Z axis.
> 0 votes

# Answer
If you need dedicated layering of graphical entities and you already have a kind of an entity system, you can introduce the layering easily within the rendering.

I think you have already something like a "Transform" component for an entity that has the x/y axis position of the entity and also some other orientation information stored. just add a layer information there. This can be a simple number from 0 to 100 for example and defines the the layer on witch this entity has to paint to.

Then on the renderer or renderer system you can sort the entities within the layer and paint them in the right layering order. Or if you have a proper event system, you can simply fire render-events for every layer within layer order and the renderer system that receives this events paints the entities for that layer.

But this doesn't solve your problem right? because all the trees are probably on the same layer but the tree in the back should be rendered first, before the tree in the front. So what kind of perspective do you really have in your game? It seems like a tile map where the things painted in the upper rows are behind the things painted in the following rows.

Instead (or additional to) the layer information you can have a grid position information for sorting the entities on rendering to get the right order. Or maybe in your case it would be enough to just sort the entities to paint within the y-axis position. The important thing for you is to think about the perspective your game should have or has and with what kind of sorting you can get the expected result on rendering.
> 0 votes

---
Tags: java, slick
---


# Question
Title: How to implement ECS in a videogame with C++?
What do I need to know in order to implement ECS in a video game? I'm developing a video game and so far I wasn't using any complete architecture, I was just using inheritance but I don't like it because the code became messy. So far, I've seen so many articles in which the subject is treated, but I don't understand how to implement it. All what I get is there is that a component is a bunch of information, an entity is a bunch of components, and each system deals with the logic of its own components. But I've got a question about it, they're a bunch of IDs, how do those IDs store data? How to retrieve data from it? I've got a problem, since I was trying to implement components, in order to do it all what I did was declare a parent abstract class in which I'd store members of that class and then I would be able to access to those members. The problem came when I was trying to declare children of that abstract class, since that parent class can't have all the members of all the another components (and I need a way to iterate all the components in a vector). So... I want to keep the things as simple as possible. Any advice for someone like me? How can I implement ECS in a simple platformer? Please, Thanks in advance!

# Answer
Keep in mind that ECS is at its core not an object-oriented design pattern. It is more suitable for structures and functions.

> \[entities are\] a bunch of IDs, how do those IDs store data?

In an ECS-by-the-book architecture, entities do not store any data. Components store data. Also, neither entities nor components contain any logic. All logic is in the systems.

So you don't have an entity with a collision box. You have a vector of collision box components and some data structure which maps IDs to collision boxes (the article mentioned in the question calls these "Component Managers"). What kind of data structure is an optimization problem. But a good default solution is to use `std::map<int, CollisionBox*>`. You then have a CollisionSystem which detects and handles intersections between those collision boxes.

Sometimes it can be useful when components contain the ID of the entity they belong to so you can more easily find other components of the same entity. But not all components will need this.

---

However, this is a very C-ish style of creating an ECS system. If you feel more comfortable with a more object-oriented design, then you can also have a `class Entity` which contains pointers to all its components. You can even have a class hierarchy of entities which differ by what components they have and how they initialize them.

But the concrete instances of the components should be stored in large arrays (which you can abstract as a `std::vector` if you like) with one array for each type of component. Systems should operate on these arrays whenever possible to benefit from memory locality (iterating through an array is much faster than dereferencing a pointer).

Just don't forget about the basic principles of ECS:

* Components contain all the data
* Systems contain all the logic
* Entities say which components belong to each other
> 2 votes

# Answer
Entities don't have to be a bunch of ID's. Just create an Entity Class that will contain a list of components and that will have some methods that will help you add, remove, get, and check if the entity has certain components.

For component, just make an empty interface called component and use it for polymorphism. That way make more classes that extend Component and store data in them. Put them in the list of components that you have in your entity.

Then make systems. The way systems work is, you give your entity to your system and the system checks if that entity should be operated in that system by checking if the entity has components that the system requires. If yes, retrieve the components from the entity and make the logic in some kind of an update method that will run every time your game updates!

Also, you asked how the ID can store those components. Well, it doesn't, but in your engine class, you just store it in a HashMap. The hash map has the entity ID as a key and the List of components as the value, but as I said, better just make an Entity class that will contain the ID and the list of components! It's easier

There are many ways you can do this, this is just how I did it. There is also one tutorial series on Youtube by BennyBox who makes a 3D engine in C++. There he uses ECS and he even programs the ECS system there. You can do the rest of the stuff by your way and just copy his ECS if you don't want to make your own or the way I explained.

Here is the link:

https://www.youtube.com/watch?v=Y6he35HfDmA&t=1183s
> 0 votes

---
Tags: c++, game-design, architecture, design-patterns
---


title: Transforming a 2D Grid in 3D Space

text:
# Question
Title: Transforming a 2D Grid in 3D Space
Hi everyone,

I'm trying to implement a 2D Grid in a simple 3D Editor. Here are some debug-rays I already implemented:

Everything is working as intended as long as the object is not rotated. For demonstration purpose the box is aligned with the grid center (the purple box).

(I can move the object along the grid without changing the grid location):

Now if I rotate the large white cube I want the grid to rotate as well.

Here is the problem: I dont want the origin of the grid to change it's relativ location. The grid location of the green line should still align with the upper left corner of the large white box.

And I just cannot figure out the offset I have to translate the grid :(

Here is what I've tried: Calculate the difference between the two collision points (Yellow and Green) and use this as offset but on rotation the offset is too large and the grid is shifting.

Here is the data I have available:

```
Vector3 Origin = new Vector3();
Vector3 GridPlaneNormal = new Vector3(0, 0, 1);
Plane GridPlane = new Plane(Origin, GridPlaneNormal);
Plane objectPlane = /*.... (it's the plane of the cubes front)*/

Vector3 GridNormalInDirectionOfObject = Vector3.TransformNormal(GridPlaneNormal, Matrix.RotationQuaternion(Object.RotationQuaternion));

float angle = GridPlaneNormal.SignedAngle(GridNormalInDirectionOfObject, GridPlane.Normal);
Vector3 rotationAxis = Vector3.Normalize(Vector3.Cross(GridPlane.Normal, objectPlane.Normal));

```

Please help me! :)

# Answer
> 1 votes
This is why we use matrices for all of this stuff.

Create a world matrix (aka, model matrix) for your grid, including its rotation, translation and scale.

Create a similar matrix for the cube, *relative to the transform of the grid*.

When drawing the cube, multiply the cube's model matrix with the grid's model matrix. Use the resulting matrix to draw the cube.

In this way, the cube will be translated, rotated, etc. relative to its own origin, and then transformed to follow anything you do to the grid.

Depending on which graphics API you're using, it'll either be gridMatrix * cubeMatrix (HLSL) or cubeMatrix * gridMatrix (GLSL). (Google row-major vs column-major graphics api for more information.)

For instance, you might do something like this:

```
class GameObject
{
    public GameObject Parent = null;
    public Vector3 Rotation;
    public Vector3 Translation;
    public Vector3 Scale;

    public Matrix GetTransform()
    {
       // you should really cache this as it can take a bit of time to build.
       var xform = Matrix.CreateScale(Scale) * Matrix.CreateFromRollPitchYaw(Rotation.Z, Rotation.X, Rotation.Y) * Matrix.CreateTranslation(Translation);

        if (null != Parent)
            xform = Parent.GetTransform() * xform;

        return xform;
    }

}

var grid = new Grid();
var cube = new Cube();
cube.Parent = grid;

// etc...

```

Then, when drawing your object, pass the result of GetTransform() to your shader. (That'll also, of course, get multiplied by your view and projection matrices in the shader.)

Of course, you can do all of this without matrices, but you have to manually rotate your vertex, then translate and scale by the cube's transform, then by the grid's transform - again, rotating first, then translating and scaling - all the way through your hierarchy. It gets messy. The matrix method lets you combine all operations into a single matrix. It's the simplest and most efficient solution.

If you can tell which API, engine, library (SDL? Monogame? XNA? Unity? OpenTK?) you're using, we can provide a more detailed response.

---
Tags: c#, 3d, mathematics
---


# Question
Title: Player with navmeshagent keeps moving back to the last mouse position clicked
On my FPSController I have two scripts, Player Controller and Agent Controller.

**Player Controller** is for using the keys WSAD for moving the player around.

**Agent Controller** uses a NavMeshAgent to move the player to a position clicked with the mouse (like point and click ).

Everything is working fine, or was working fine until I tried to move the player around using the keys WSAD after clicking the mouse.

I clicked the mouse on the ground (terrain) or on a cube no matter what I clicked on and the player is moving to this position. Now at that position the player stops. Now I'm trying to move the player with the keys WSAD, but even if I click on S for example long time the and player is far away from the last mouse clicked position when I leave the S key the player automatically moves back to the mouse clicked position.

The player should stay at where I move him with the keys WSAD but he keeps moving back to the last clicked mouse position.

On the FPSController I have a Rigidbody and NavMeshAgent and the two scripts Player Controller and Agent Controller.

The original Agent Controller script was:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class AgentController : MonoBehaviour
{
    public Camera camera;
    public NavMeshAgent agent;
    public bool agentControl = false;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update ()
    {
     if (Input.GetMouseButtonDown(0) && agentControl == true)
        {
            Ray ray = camera.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit))
            {
                agent.SetDestination(hit.point);
            }
        }
    }
}

```

And the Player Controller script:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float speed = 10.0f;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        float translatioin = Input.GetAxis("Vertical") * speed;
        float straffe = Input.GetAxis("Horizontal") * speed;
        translatioin *= Time.deltaTime;
        straffe *= Time.deltaTime;

        transform.Translate(straffe, 0, translatioin);

        if (Input.GetKeyDown("escape"))
            Cursor.lockState = CursorLockMode.None;
    }
}

```

The main goal is to use either the Agent Controller for point and click with the navmeshagent or using the keys WSAD to move around.

# Answer
> 1 votes
When you call `NavMeshAgent.SetDestination(Vector3 destination)`, you're telling it "your job from now on is to move toward this point. You don't give it a time limit or an interrupt condition or even an instruction to forget its destination once it arrives. It will just keep heading toward that spot until you tell the NavMeshAgent you want it to do something else.

So, tell it you want it to do something else.

When you get nonzero input on the horizontal or vertical axes (ie. from the WASD keys), call `NavMeshAgent.ResetPath()` so it knows you've cancelled the last move order and it should stop trying to move to the last clicked point until you give it a new destination.

---
Tags: unity, c#, navmesh
---


# Question
Title: Check whether a vector is to the left or right of another position
I don't know how to decide if my point is on the left or right side of another object.

My first thought was to check if x-axis of object1 is bigger or smaller than object2's, but if my objects rotate then that isn't working.

In the picture above we have two states where object2 is on the left side of object1. In one case its x coordinate is greater, in the other, its x coordinate is less.

# Answer
> 1 votes
If you're in 2D, with the x+ axis to the right and y+ axis up, then given a direction vector `v`,

```
v_perp.x = -v.y;
v_perp.y =  v.x;

```

gives you a vector `v_perp` that's equal to `v` rotated 90 degrees to the left. Flip the signs to get a vector 90 degrees to the right.

So, you can do a check like this:

```
Vector2 positionOffset = object2Position - object1Position;
Vector2 rightward = new Vector2(object1FacingDirection.y, -obect1FacingDirection.x);

bool object2IsToTheRight = Vector2.Dot(positionOffset, rightward) > 0;

```

Of course, in Unity, if your two objects have transforms, then it's even easier since the rightward vector is pre-caclulated for you:

```
bool object2IsToTheRight = Vector2.Dot(
          object2.transform.position - object1.transform.position,
          object1.transform.right
     ) > 0;

```

---
Tags: unity, mathematics, vector, linear-algebra
---


# Question
Title: When does "frustum culling" actually happen?
So I am a little bit confused, and hopefully not too far off, about when frustum culling actually occurs. Let's suppose that I already have my objects in camera space, and then I have applied the perspective matrix onto it which puts everything into a cube AKA the canonical volume. From there, do I immediately do the "culling" and then simply drop the "z" axis of each point to draw it on 2D image plane? How exactly do I do the culling in the canonical cube volume?

# Answer
Frustum culling happens whenever you (or the higher-level graphics engine you're using) implement it.

The idea behind culling is to *completely exclude* objects from being processed when they will be *completely outside* the view frustum. As such, the *earlier* in the rendering process you can discard objects the better. If you wait to cull an object until you've already transformed it through the geometry stages (the vertex shader), you're only really saving the raster costs that the built-in clipping functionality would save you anyway.

Given a combined view-projection matrix, you can extract the equations of the clip planes from it. The extract planes will be in world space. That means you can test your game objects against them before submitting them be rendered at all; all you need to know is where the object is in the world and how big it is in the world, which is information generally readily available to you.

So in short, you should implement frustum culling before you even think about drawing an object.

Often you will want to do frustum culling in conjunction with a broader-phase spatial partitioning system in order to reduce the number of checks. Grids, quadtrees or octrees, as mentioned in the comments, are typical candidates.

(Note of course that if there is any *logic* associated with an object, such as ticking forward its animation pose, you will still want to do that even if the object is just outside the view and you don't end up actually *drawing* it.)
> 3 votes

---
Tags: frustum-culling
---


# Question
Title: Working in large play-area maps, what are the performance and practical differences between Unreal Terrain and a subdivided OBJ mesh terrain?
I've managed to reliably use SRTM Geotiff Raster Data with some modifications to create decent terrains in unreal, but there is a small problem with how I go about city-building when I'm not using the actual terrain from unreal in my modelling program, especially with roads and other wide-area constructs. If I were to convert my heightmap to a mesh object for use and manipulate in modelling programs instead of using the unreal terrain, what sort of difference in performance or stability would it make? What about load times?

Would it make a large impact with object meshes for building exteriors included in the object mesh for the terrain, thus reducing the amount of information needed to load both the buildings and terrain by a small amount?

EDIT: title, player should have been play-area

# Answer
You need to profile and see, but in general you'd want to use dedicated terrain rendering techniques for rendering terrain. Not a bunch of static meshes imported from model files.

There are optimizations that can be made for terrain rendering that take advantage of the constraints of the terrain: it is height-map based, and it's on a regular grid, et cetera. Terrain rendering typically uses a subsection of this overall grid as the unit of optimization for falling back to lower-LOD versions, and the geometry for the terrain can be produced on-demand on the GPU as a consequence of the same.

Static meshes are themselves a unit of optimization, and usually aren't as easy to LOD efficiently and automatically in a shader (in the general case). So while in theory you could implement some of these optimizations yourself, you'd be implementing them yourself. They come "for free" with systems that are dedicated to terrain rendering.

The cost of a mesh is fixed, and generally large for something high-resolution enough to be a reasonable-sized terrain chunk. In contrast, the cost of the mesh data for terrain is effectively 0 (it can be generated, since it's based on a height map). The texture cost for the heightmap isn't too onerous; even though it's probably larger dimension-wise, it's probably smaller channel-wise. So it's very possible that the dedicated terrain approach will both load faster *and* use less memory, depending on how you subdivide your world, your resolution choices, et cetera.

You will find similar tradeoffs in the authoring tools. Unreal's terrain tools allow you to do complex tasks like placing spline-based features over the terrain that are snapped to the terrain (or deform the terrain around it). These splines can have tailored optimizations to processing and rendering just like the terrain can. Static meshes don't, and so you may find yourself with a tedious content-re-authoring pipeline to make any kind of changes to these kinds of features because you need to "bake" them into the meshes themselves.

Every game is different, and only you can do the analysis on your game to determine how the pros and cons balance out. But if I were to bet, I'd bet you'll have better results by using Unreal's terrain tools, both in terms of performance and in terms of ergonomics in the editor.
> 1 votes

---
Tags: blender, terrain, 3d-meshes, unreal-4, terrain-rendering
---


# Question
Title: What legalese is required in a game installer?
So I've seen a lot of installers, and on almost (if not every one, I don't keep track), all of them, there is a EULA, and specific items that are seen on all installers. However, I'm going to be making my own installer for a game, and I'm wondering if there's certain things that *need* to be included. Do I need a License Agreement? *Should I have a license agreement?* Etc.

# Answer
> 2 votes
It depends, as noted in the comments, on the agreement you want to make with users. It may also depend on the jurisdiction where you distribute the game, which may require you to grant (or deny) certain rights to users. If you use certain middleware or tools to build the game, they may require you to require certain things of users or present certain legal disclaimers.

You should *absolutely* consult a lawyer.

You generally do need some kind of license agreement; if nothing else you need to be granting the user the permissions to use, in limited form, the intellectual property you have distributed to them (by running the game's executable).

From a practical perspective you probably also want to disclaim certain responsibility (e.g., if the software deletes their hard drive because of a bug).

---
Tags: legal, installer
---


# Question
Title: Licensing classic (vintage) car models for game
I know that I cannot use real car models in a game without permission. However, I am interested in a classic (vintage) cars from era before 1950. Some of the companies no longer exist, or were bought by some other company and this by some other company etc. Some cars had custom-made chasis on top of a "skelet".

How is licensing for those cases? Same as for "today" cars, or is there any exception? Something like books where from certain date there are no longer copyrights.

# Answer
> 2 votes
The licensing issues are almost certainly basically the same; copyright law is older than 1950 *and* there are issues of trademarks, design patents, and trade dress to potentially account for as well.

Working within them will likely be harder, because tracking down who actually *owns* the rights to older, seemingly-abandoned car designs will probably be difficult.

If you can find and document (or get an expert to do so, preferably) that some car design and associated IP was transferred into the public domain, you can use it. But you should not assume that just because it is "old" or that the company "no longer exists" that the car is in the public domain. Usually when companies cease to exist, whatever assets (physical and intellectual) they had at the time are transferred or sold to other parties.

---
Tags: models, legal, licensing
---


# Question
Title: How do you create hitboxes that will detect stationary targets too?
I've created a basic attack combo system that chains 3 attacks together.

When the player clicks the mouse button, it enables a boxCollider2D attached to the player.

The boxCollider is a trigger and will cause damage to a valid target using OnTriggerEnter2D.

This doesn't seem to be very responsive, and often will not work if the target is stationary. I've thought about trying Raycasts as an alternative but am looking for advice on how to handle this properly.

```
public class Attack : MonoBehaviour
{
     private int comboIndex;
     public float lastAttack;
     private Animator _animator;
     private string[] attackName;
     private float comboResetTimer;
     private BoxCollider2D _hitbox;

     private void Awake()
     {
         attackName = new[] {"Attack1", "Attack2", "Attack3"};
         _animator = GetComponent<Animator>();
         _hitbox = GetComponent<BoxCollider2D>();
     }

     private void Update()
     {
         var canAttack = Input.GetMouseButtonDown(0);

         if (canAttack && comboIndex < attackName.Length)
         {
             _animator.SetTrigger(attackName[comboIndex]);

             _hitbox.enabled = true;
             comboIndex++;
             comboResetTimer = 0f;
         }

         if (comboIndex > 0)
         {
             comboResetTimer += Time.deltaTime;
             if (comboResetTimer > lastAttack)
             {
                 _animator.SetTrigger("Reset");
                 comboIndex = 0;
                 _hitbox.enabled = false;
             }
         }
     }
 }

```

# Answer
> "will not work if the target is stationary"

Exactly. The physics engine checks for collision when something moves. If you don't have movement, it doesn't think it needs to check.

In particular, Rigidbodies can go to sleep if they're not moving, meaning the physics engine will skip processing them until another moving object hits them, or a script applies force/velocity/other physics effect to them. This can save a lot of processing in complex scenes.

You can force your player's Rigidbody2D to wake up by calling body.WakeUp() at the same time that you enable the hitbox. That ensures physics checks will run on that object this frame, even if all the objects nearby are stationary.

Or, to manually check for overlaps in a box on specific frames, use the OverlapBox method.
> 1 votes

---
Tags: unity, collision-detection
---


# Question
Title: POST JSON method does not work when project has been exported to WEBGL and uploaded to firebase hosting
I have a database set up on firebase and when i run my game in the unity edtitor and as a standalone exported Windows .exe file, the call gets made correctly to the database and JSON data gets posted correctly. However when I export the exact same project to WEBGL and upload it to my firebase hosting server, the JSON call does not work. Here is my code, could someone please help?

```
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

 public class GameOverMenu : MonoBehaviour
{
 public InputField nameInputField;

 public void MainMenu()
 {
     SceneManager.LoadScene("Menu");
 }

 public void SubmitScore()
 {
     StartCoroutine(SendScore());
     SceneManager.LoadScene("Menu");
 }
 // Use this for initialization
 void Start()
 {

 }

 // Update is called once per frame
 void Update()
 {

 }

 public IEnumerator SendScore()
 {
     Scoreboard s = new Scoreboard(nameInputField.text, PlayerPrefs.GetInt("Score"), PlayerPrefs.GetInt("Seed"));
     Dictionary<string, string> headers = new Dictionary<string, string>();
     headers.Add("Content-Type", "application/json");
     Hashtable data = new Hashtable();
     data.Add("name", s.Name);
     data.Add("score", s.Score);
     data.Add("seed", s.Seed);

     UnityHTTP.Request postRequest = new UnityHTTP.Request("post", "https://alexclearythesisgame.firebaseio.com/Scoreboard.json", data);
     postRequest.Send();
     yield return postRequest.isDone;
 }

}

```

# Answer
> 0 votes
I had to use the following free rest api as with the current package I was using , webgl wasn’t transferring the .dlls correctly : https://github.com/proyecto26/RestClient/blob/master/README.md

---
Tags: unity, client-server, json, http
---


title: Base class undefined?

text:
# Question
Title: Base class undefined?
I have no idea why I'm getting this error except that it has to do with the includes.

Base class header file:

```
#pragma once

#include "Player.h"
#include "TestObject.h"
#include <glm\glm.hpp>
#include <GL\glew.h>

class GameObject
{
//unrelated code
};

```

Derived class header file:

```
#pragma once

#include "GameObject.h"
#include <glm\glm.hpp>
#include <glm\gtc\matrix_transform.hpp>
#include <glm\gtc\type_ptr.hpp>

class Player : public GameObject
{
//unrelated code
};

```

error message:

```
Error   C2504   'GameObject': base class undefined

```

And here are the includes for both cpp files:

base:

```
#include "GameObject.h"
#include "Player.h"
#include <iostream>
#include <glm\glm.hpp>

```

derived:

```
#include "Player.h"
#include "GameObject.h"
#include <iostream>
#include <glm\glm.hpp>

```

# Answer
When the compiler goes to compile your `base.cpp` file, it runs the preprocessor to perform *textual substitution* of all `#include` directives with their contents. This substitution is "dumb," it is effectively a copy-and-paste operation that you can control slightly with other preprocessor directives like `#pragma` or `#ifdef`, et cetera.

The first part of this process is to replace `#include "GameObject.h"`, which has a `#pragma once`. The compiler hasn't copied this file into the resulting TU yet, so it does so, records that it has (for later `#pragma once` checks) and recursively continues on.

This means the next thing it does is copy in `Player.h`, which also has a `#pragma` but also hasn't yet been seen, and thus the copy continues. Then it continues on recursively.

This means the *next* thing it does is try to replace the `#include "GameObject.h"` copied in by `Player.h`. But it has already seen `GameObject.h` so it skips this line and continues on.

The net result is that after pre-processing your source file is arranged roughly like:

```
class Player : public GameObject
{
//unrelated code
};

class GameObject
{
//unrelated code
};

```

This is the actual code the compiler ends up seeing, and naturally can't be compiled because by the time you are defining `Player` you have not yet defined the base class `GameObject`.
> 3 votes

---
Tags: c++, inheritance
---


title: Decouple GUI from Logic

text:
# Question
Title: Decouple GUI from Logic
*I don't have an educational background in the programming-world; however, I've been working on a programm in my spare time for the last two years.*

I'm currently struggling with how to decouple the GUI (or the drawing-logic in general) from the internals. More precisely, how to retrieve the data that's needed to display all information on screen.
For example: There is a collection of items that I want to display in some sort of inventory.
Should there be a copy of the collection in both the modules that use these items and the GUI-module or should all of them referece to the same container?
Should the implementation already provide methods that are needed in the UI logic? (e.g. the game only needs to check if you can use an item, the UI would show why you cannot use it - should several functions be provided in the logic, even though the game doesnt care for which reason?)

I have been reading up on MVC and MVP but the problem hasnt really been adressed: How does the View retrieve the data needed to display the model?

I'm not using any frameworks, engines, etc. Just plain code - I'm more focused in the design than finishing the project.

# Answer
> 1 votes
There a a number of ways to do this, but I will go into the way I solve this in my own games.

Firstly, the Icons/UI elements are a visual manifestation of the status of the item. Just a representation, but you need something to glue that to your items. In this case a container that contains a object that references both the GUI elements and the inventory items. I do stress REFERENCE, not copy because if you copy,then you have to manage status updates across multiple copies of the same object.

For container design, this should be a baseclass, with functions that are overridden based on the item there in. For example, you may want to show a cooldown on a sword or item in game, your container class could have an inherited class to deal with that AND also manage how that is displayed in your UI component, say with a colour or timer overlay. Another could be a potion, that is represented as full or empty. That can be a separate inherited class to do the logic for that also (single use instead of cooldown).

What i'm basically getting at is, that firstly address the loose coupling of UI to game object through a class that manages the logic of displaying on screen. Functions such as game logic are in the referenced object class and you don't need to pull that up into the container class, its taken care of where it should be.

You then wrap the container class up within a collection class, that container class could also be an abstracted class, Say Bag, Chest, Safe, etc that itself organises how it is displayed on screen.

Each layer then takes care of itself, is extensible. base class design is the key here, and ensuring that everything is in a logical place in your object hierarchy.

Hope that is a a start

---
Tags: c++, gui
---


# Question
Title: How to determine if an object is within field of view given xyz of object, player position, and 3D vector for player view?
I only have the object's position, the player position, and the vector representing the player's view, and I have the FoV (120 degrees horizontal/60 on each side, and 60 degrees vertical/30 on each side).

As I'm dealing with data that has already been recorded, I cannot use any Unity built-in functions and have to calculate it manually. My thoughts were to convert the 3D coordinates into 2D vectors, so that I can calculate if an object is in the horizontal plane first (by taking the X and Z values) and then if it is, check if it is in the vertical plane (take the Y and Z coordinates).

After, I calculate the the angle between the object and the player view to see if the absolute value of that is within the field of view (for example, if the object is on the left side of the player view, and the horizontal FOV is 120 degrees, then if the absolute value of the angle is less than or equal to 60 degrees it is within view).

Is this on the right track? I've been getting strange results (like only one of the four objects I'm looking for shows as visible throughout a log of values even though they should all at some point be visible).

Here is some code to show what I'm doing:

```
    public static Double angle(Vector2D obj, Vector2D bodyPos, Vector2D headDir) {

    Double result = 0.0;

    // Get the vector between the body position and the object
    Vector2D temp = Vector2D.subtract(obj, bodyPos);

    // First find dot product
    Double dotProduct = Vector2D.dotProduct(headDir, temp);

    // Now find the length of each vector and get the product of them
    Double lengthProduct = Vector2D.vectorLength(headDir)*Vector2D.vectorLength(temp);

    // Find the intermediary result
    result = dotProduct / lengthProduct;

    // Apply arc cos to find the angle between the vectors
    result = Math.acos(result);

    // Convert angle to degrees
    result = (result * 180)/Math.PI;
    System.out.println("The angle is: " + result);

    return result;
}

```

And here is the code that determines if something is in view by using that angle function:

```
    public static boolean isInView(bodyPosition objPos, bodyPosition bodyPos, headDirection headDir){

    boolean inView = false;

    Double h_angle = 0.0;
    Double v_angle = 0.0;

    // Create 2D vectors for both the horizontal and vertical FOV measurements
    Vector2D h_objPos = new Vector2D(objPos.getDirectionX(), objPos.getDirectionZ());
    Vector2D v_objPos = new Vector2D(objPos.getDirectionY(), objPos.getDirectionZ());

    Vector2D h_bodyPos = new Vector2D(bodyPos.getDirectionX(), bodyPos.getDirectionZ());
    Vector2D v_bodyPos = new Vector2D(bodyPos.getDirectionY(), bodyPos.getDirectionZ());

    Vector2D h_headDir = new Vector2D(headDir.getDirectionX(), headDir.getDirectionZ());
    Vector2D v_headDir = new Vector2D(headDir.getDirectionY(), headDir.getDirectionZ());

    // determine angle of FOV+
    Double iHFOV = FOV_H_MID * 0.5;
    Double iVFOV = FOV_V_MID * 0.5;

    // Check horizontal FOV first; if it is within that, then check the vertical
    // If both pass, then it is in view
    h_angle = Vector2D.angle(h_objPos, h_bodyPos, h_headDir);
    v_angle = Vector2D.angle(v_objPos, v_bodyPos, v_headDir);
    if ( Math.abs( h_angle ) <= iHFOV) {
        if ( Math.abs( v_angle ) <= iVFOV) {
            inView = true;
        }
    }

    return inView;
}

```

I found some resources that I will be reviewing in the mean time, but any help is appreciated. I haven't done any linear algebra courses so I'm trying to wrap my brain around it.

# Answer
> 1 votes
To be honest, you're best to test using bounding boxes and the camera frustum if you can get hold of those.

I've attached my code for generating the frustum. You then should test each corner of your bounding box against this frustum (code below).

```
  [MethodImpl(MethodImplOptions.AggressiveInlining)]
        void GenerateFrustumPlanes()
        {
            if (m_disableFrustrumUpdates)
                return;

            Matrix matrix;

            // Create the frustum matrix from the view matrix and updated projection matrix.
            matrix = m_wvp;

            m_planes[0] = new Vector4(matrix.M13,
                 matrix.M23,
                 matrix.M33,
                matrix.M43); // near
            m_planes[1] = new Vector4(matrix.M14 - matrix.M13,
                matrix.M24 - matrix.M23,
                matrix.M34 - matrix.M33,
                matrix.M44 - matrix.M43);

            m_planes[2] = new Vector4(matrix.M14 + matrix.M11,
                matrix.M24 + matrix.M21,
                matrix.M34 + matrix.M31,
                matrix.M44 + matrix.M41); // left
            m_planes[3] = new Vector4(matrix.M14 - matrix.M11,
                matrix.M24 - matrix.M21,
                matrix.M34 - matrix.M31,
                matrix.M44 - matrix.M41);//right

            m_planes[4] = new Vector4(matrix.M14 - matrix.M12,
                matrix.M24 - matrix.M22,
                matrix.M34 - matrix.M32,
                matrix.M44 - matrix.M42); // top
            m_planes[5]  = new Vector4(matrix.M14 + matrix.M12, matrix.M24 + matrix.M22, matrix.M34 + matrix.M32, matrix.M44 + matrix.M42); // bottom

            for (int i = 0; i < s_frustrumPlanes; i++)
            {
                m_planes[i].Normalize();
            }
        }

```

code to test the points of the bbox against the frustrum.

public bool IsInViewableArea(List a\_cornerLIst) { // this is a simpler occlusion test where we basically don't even need to test frustum as the the extents are outside the camera view distance. But you need to test extents + width because we only hold 2 corners and squares are 4

```
    int iTotalIn = 0;

    Vector4[] pList = GetFrustumPlanes();  // this should only be called once.

    // test all 8 corners against the 6 sides
    // if all points are behind 1 specific plane, we are out
    // if we are in with all points, then we are fully in
    Vector4 temp;
    float dotvector;
    for (int p = 0; p < Camera3d.s_frustrumPlanes; ++p)
    {

        int iInCount = 8;
        int iPtIn = 1;

        for (int i = 0; i < a_cornerLIst.Count; ++i)
        {
            //Vector3 a = pList[i].
            // test this point against the planes
            //   if (pList[p].SideOfPlane(vList[i]) == BEHIND)
            //Vector4.Dot()
            temp = (Vector4)(a_cornerLIst[i] );
            temp.W = 1;

            dotvector = Vector4.Dot(pList[p], temp);

            if (dotvector < 0.0f)
            {
                iPtIn = 0;
                --iInCount;
            }
        }

        // were all the points outside of plane p?
        if (iInCount == 0)
        {
            return false;
        }
        // check if they were all on the right side of the plane
        iTotalIn += iPtIn;
    }

    // so if iTotalIn is 6, then all are inside the view
    //    if (iTotalIn == 6)
    //       return true;

    // we must be partly in then otherwise
    return true;
}

```

# Answer
> 0 votes
Yes, your approach is valid. If z is up, then first do in xy plane, and then check vertical, taking into account that the camera may be tilted up or down.

Note that to do tests in 2D, I simply use 3D vectors, but set z to zero.

Note that it doesn't handle special case of camera looking straight up (0,0,1) or straight down (0,0,-1), which would cause the normalize() to fail.

Note that this vertical test also won't work if camera tilt approaches straight up or down, where tilt + 0.5 vertical fov exceeds 0.5 pi, or tilt - 0.5 vertical fov is below -0.5 pi.

```
bool inview( vec3 campos, vec3 camdir, bodypos )
{
    // First test if in our horizontal field of view.
    vec3 tobody = bodypos - campos;
    vec3 tobody2d = tobody;
    tobody2d.z = 0;
    vec3 camdir2d = camdir;
    camdir2d.z = 0;
    tobody2d = tobody2d.normalize();
    camdir2d = camdir2d.normalize();
    float dp = tobody2d.dot( camdir2d );
    if ( dp < cosf( horizontal_fov ) )
        return false; // body too far to left or right of camera.
    // Check if in vertical fov (Note that camera may be tilted up/dn.)
    float tiltcam = asinf( camdir.z );
    tobody = tobody.normalize();
    float tilttobody = asinf( tobody.z );
    if ( tilttobody < tiltcam - 0.5 * vertical_fov )
        return false; // body too low to see.
    if ( tilttobody > tiltcam + 0.5 * vertical_fov )
        return false; // body too high to see.
    return true;
}

```

# Answer
> 0 votes
ErnieDingo's got a pretty good answer, what with using frustum planes. I had a similar problem I wanted to solve a few years back: calculating a field of view *as if* an object had a camera without needing a rendering `Camera` component.

So this is pretty similar, but my code is different.

```
public static Plane[] CalculateFrustum(Vector3 origin, Vector3 direction, float fovRadians, float viewRatio, float distance) {
    Vector3 nearCenter = origin + direction * 0.3f;
    Vector3 farCenter  = origin + direction * distance;
    Vector3 camRight   = Vector3.Cross(direction,Vector3.up) * -1;
    Vector3 camUp      = Vector3.Cross(direction,camRight);

    float nearHeight = 2 * Mathf.Tan(fovRadians / 2) * 0.3f;
    float farHeight  = 2 * Mathf.Tan(fovRadians / 2) * distance;
    float nearWidth  = nearHeight * viewRatio;
    float farWidth   = farHeight * viewRatio;

    Vector3 farTopLeft  = farCenter + camUp*(farHeight*0.5f) - camRight*(farWidth*0.5f);//new Vector3(-camRight.x * (farWidth*0.5f), (farHeight*0.5f), -camRight.z * (farWidth*0.5f));
    //Vector3 farTopRight = farCenter + camUp*(farHeight*0.5f) + camRight*(farWidth*0.5f);//new Vector3( camRight.x * (farWidth*0.5f), (farHeight*0.5f),  camRight.z * (farWidth*0.5f));
    Vector3 farBottomLeft  = farCenter - camUp*(farHeight*0.5f) - camRight*(farWidth*0.5f);//new Vector3(-camRight.x * (farWidth*0.5f), -(farHeight*0.5f), -camRight.z * (farWidth*0.5f));
    Vector3 farBottomRight = farCenter - camUp*(farHeight*0.5f) + camRight*(farWidth*0.5f);//new Vector3( camRight.x * (farWidth*0.5f), -(farHeight*0.5f),  camRight.z * (farWidth*0.5f));

    Vector3 nearTopLeft  = nearCenter + camUp*(nearHeight*0.5f) - camRight*(nearWidth*0.5f);//new Vector3(-camRight.x * (nearWidth*0.5f), farCenter.y + (nearHeight*0.5f), -camRight.z * (nearWidth*0.5f));
    Vector3 nearTopRight = nearCenter + camUp*(nearHeight*0.5f) + camRight*(nearWidth*0.5f);//new Vector3( camRight.x * (nearWidth*0.5f), farCenter.y + (nearHeight*0.5f),  camRight.z * (nearWidth*0.5f));
    //Vector3 nearBottomLeft  = nearCenter - camUp*(nearHeight*0.5f) - camRight*(nearWidth*0.5f);//new Vector3(-camRight.x * (nearWidth*0.5f), farCenter.y - (nearHeight*0.5f), -camRight.z * (nearWidth*0.5f));
    Vector3 nearBottomRight = nearCenter - camUp*(nearHeight*0.5f) + camRight*(nearWidth*0.5f);//new Vector3( camRight.x * (nearWidth*0.5f), farCenter.y - (nearHeight*0.5f),  camRight.z * (nearWidth*0.5f));
    Plane[] planes = {
        new Plane(nearTopLeft,farTopLeft,farBottomLeft),
        new Plane(nearTopRight,nearBottomRight,farBottomRight),

        new Plane(farBottomLeft,farBottomRight,nearBottomRight),
        new Plane(farTopLeft,nearTopLeft,nearTopRight),

        new Plane(nearBottomRight,nearTopRight,nearTopLeft),
        new Plane(farBottomRight,farBottomLeft,farTopLeft)};

    return planes;
}

```

Which calculated the `Plane[]` needed for this extension function:

```
public static class GameObjectExtensions {
    public static bool IsVisibleFrom(this GameObject obj, Plane[] planes) {
        Bounds b = obj.GetComponent<Collider>().bounds;
        b.Expand(0.5f);
        return GeometryUtility.TestPlanesAABB(planes, b);
    }
}

```

I could now call `someGameObject.IsVisibleFrom(...)` and pass in the necessary values, including the return from `CalculateFrustum()` which would even take in a field of view (in Radians), view ratio, and max view distance (I also had an `IsVisibleFrom()` that took in a Camera object as well, which uses `GeometryUtility.CalculateFrustumPlanes(camera);` to get its `Plane[]`).

As far as I remember, the `CalculateFrustum()` method I have is identical to what `CalculateFrustumPlanes()` does.

---
Tags: linear-algebra
---


# Question
Title: Should LOD models be used in mobile games?
LOD models are widely used in PC and console games, to optimize performance by reducing the vertex count and texture size for distant objects. However, I'm having a harder time finding out if they are typically used to increase performance in mobile games.

I've seen a few people in forums suggest that the CPU overhead for LOD models might actually outweigh the GPU gains on mobile devices. Another consideration is the more limited storage space on mobile, and LOD models/textures necessarily increase the total size of a game. Other than that, I can't find much information on the subject. The Unity documentation on LOD models doesn't mention mobile, and the Unity documentation on optimizing for mobile doesn't mention LOD models.

I know the first answer to any performance question is usually "profile it and find out for yourself"; however, in this case, I am helping to optimize a game that doesn't currently have LOD models, so profiling it would first require commissioning the artists to create enough LOD models that we can realistically profile the performance change.

**Does the usage of LOD models typically provide noteworthy performance gains in 3D mobile games, or does the overhead for LOD cancel out any gains?**

The specific title in question is a racing game.

# Answer
> 2 votes
One of the things that makes it hard to answer this question is the quickly evolving diverse landscape of mobile devices. Not only are they getting more powerful and higher resolution, there are still lower-end phones and tablets that proliferate the market. If your target is only the high powered devices which have large screen sizes, then it makes sense. If you want to target a wide audience, then low-end devices may just need to use lower LOD models, without the runtime overhead of switching based on distance from the camera.

In short, LOD’s make sense for newer devices with higher power CPUs, which are slowly going to become the majority. However, note that whatever the resolution of a phone may be, it still has to fit in somebody’s pocket, so getting crazy with the level of detail in a model is not necessarily worth the overhead in that case. That may be left just to tablets. The best option is of course to check visually whether using lower LOD’s overall is visually acceptable on smaller physical screen sizes.

---
Tags: unity, performance, models, level-of-detail
---


# Question
Title: Unexpected positioning when programmatically instantiating objects in Unity?
I'm creating a simple match three game in Unity. I've opted to use Unity's UI system as it takes care of resolution scaling for me. The project is quite simple, at runtime I am programmatically creating an 8x8 grid of tiles via the script below. This script is attached to an empty Game Object residing within a canvas.

```
public class GameBoard : MonoBehaviour
{

    public int BoardSize = 8;
    public List<GameObject> TileSet;

    void Start ()
    {
        for (float y = 0; y < BoardSize; y++)
        {
            for (float x = 0; x < BoardSize; x++)
            {
                int tileIndex = Random.Range(0, TileSet.Count - 1);
                Vector3 position = new Vector3(x, y, 0.0f);
                GameObject newTile = Instantiate(TileSet[tileIndex], position, this.transform.rotation, this.transform);

            }
        }
    }

}

```

As you can see, the first tile is being positioned at a Vector3 of `0, 0, 0`. The second at `0, 1, 0`, and so on. At runtime this translates to Rect Transforms of `0, 0, -9720`, and `108, 0, -9720` respectively.

Where is 108 coming from, and why is the Z an arbitrary -9720 when it should be a constant zero?

I suspect this must be due to canvas scaling, so I have attached an image of the canvas's settings.

# Answer
> 0 votes
I tried every different way of instantiating a game object and the value of pos z would only be correct for the first one instantiated. The only thing that would work for me is Instantiating the Game Object and then setting the localPosition.

It would look something like this.

```
int tileIndex = Random.Range(0, TileSet.Count - 1);
Vector3 position = new Vector3(x, y, 0.0f);
GameObject newTile = Instantiate(TileSet[tileIndex], position, this.transform.rotation, this.transform);
newTile.transform.localPosition = position; // Don't set position, set localPosition

```

---
Tags: unity
---


# Question
Title: Confusion about Sprite Size in World Space (Unity)
I have a Sprite with 1080x1920 resolution. And I set the Game View Resolution also to 1080x1920. What I was thinking is that the sprite (1080x1920) should fit correctly within the Camera View.

But when I drag that sprite, the sprite is enlarged and goes out of the camera view.

What adjustments do I need to do to make sure this sprite is 100% fit within the camera view. I could have changed the Sprite Transform Scale. But that will cause problems because I've a lot of other sprites to deal with and they should be proportional.

# Answer
This makes sense when you recall that sprites aren't just being blitted pixel-for-pixel onto your screen (which would make it a nightmare to get the same look on screens with different resolutions, since they'd all crop your art differently), but rather they're part of your 3D world in a device-agnostic gameplay coordinate system that you can control.

Like everything else in that gameplay world, the portion that ends up mapping to the screen is determined by how you've configured your Camera object.

So, there are four parts that decide how large your sprite is shown:

1. The **source resolution** of the sprite.
2. The **Pixels per Unit** setting chosen in its import settings inspector.

This sets a conversion factor for transforming sizes from pixels in texture space to units in world space (ie. the space in which all your gameplay & physics calculations happen)

Height in World Units = Source Height in Pixels / Pixels per Unit

You should generally choose this number to align with some relevant gameplay metrics in your game. eg. if you have a tile grid with a spacing of 135 pixels, choosing Pixels per Unit = 135 will make each cell of your grid exactly 1 unit wide in the game's coordinate system, making your calculations more convenient.
3. The **orthographic size** of your camera.

(Or, if using a perspective camera, a combination of the camera's field of view and the depth from the camera to your sprite)

This determines how many units of your world your camera can see, from the center of its view to the top edge.

Portion of Camera Height Occupied = Height in World Units / (2 * Camera Ortho. Size)

So if we run with the 135 PPU value, 1920 pixel tall sprite will be 14.222222 units tall in the world, meaning we'll need a camera with a height of 7.111111 to capture the whole thing top to bottom (since camera height is measured from the middle out)
4. The **pixel size of your window / output screen resolution.**

By default, the camera's view will fill the screen vertically, so if your screen/window changes in height, the vertical crop of your scene won't change (an object at the top edge or bottom edge of the screen won't move or get cropped out, the whole scene will just get larger or smaller to fill the available height).

So the number of world units your camera can see from top to bottom maps to the number of pixels in your window/screen from top to bottom.

Output Pixel Size = Portion of Camera Height Occupied * Height of Window in Pixels

So if our screen is 1920 pixels tall, and our source sprite exactly fills the camera's view, then it will be output across the whole 1920 screen pixels in 1:1 alignment.
> 19 votes

---
Tags: unity, sprites
---