# Question
Title: Is there any way to keep the applied torques in the old planes, even if the ship's local plane has rotated?
I'm trying to make a space shooter game in Unity3D with realistic spaceship physics. I have a problem with correct rotations. When I apply torque in global coords system it will always apply them in the same global planes, even when the ship is eg. rolled to a side - if I now yaw, it will rotate it in the global system instead of yawing the ship in its local coords.

Now, when I use relative torque, I can apply yaw, then roll and it's screwed again because now the torque applied for yaw works in rotated (rolled) plane instead of the old plane.

Is there any way to keep the applied torques in the old planes, even if the ship's local plane has rotated?

Screenshots to explain the relative torque problem:

I start off with the ship aligned with the world axes. I apply relative torque to yaw.

The ship rotates in yaw plane (same as world horizontal plane).

I apply roll. The yaw is supposed to continue rotating the ship in the old plane same as world horizontal plane.

But it does not. Instead, the old yaw torque now continues in the new plane which is the local X-Z plane!

Here is the code I'm using to control the spaceship currently, using the relative torque strategy:

```
public class PlayerControl : MonoBehaviour
{
    private Rigidbody rb;
    public ManeuverEngineScript FrontRightManeuverEngine;

    void Start ()
    {
        rb = GetComponent<Rigidbody>();
    }

    void Update ()
    {
        if (Input.GetKeyDown(KeyCode.Q))
        {
            //rb.AddTorque(0f, 0f, 10f);
            rb.AddRelativeTorque(0f, 0f, 10f);
        }

        if (Input.GetKeyDown(KeyCode.W))
        {
            Debug.Log("W pressed");
            rb.AddRelativeTorque(0f, 0f, -10f);
        }

        if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            Debug.Log("LeftArrow pressed");
            //rb.AddTorque(0f, -10f, 0f);
            rb.AddRelativeTorque(0f, -10f, 0f);
        }

        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            Debug.Log("RightArrow pressed");
            rb.AddRelativeTorque(0f, 10f, 0f);
        }

        if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            Debug.Log("DownArrow pressed");
            rb.AddRelativeTorque(-10f, 0f, 0f);
        }

        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            Debug.Log("UpArrow pressed");
            rb.AddRelativeTorque(10f, 0f, 0f);
        }
    }
}

```

Here's a "stop-motion" explanation. The first set of frames shows how I expect the rotations to happen and the second one shows how it actually takes place in Unity.

The actual:

# Answer
First, your interpretation of what's happening in Unity is not accurate.

When you apply your roll torque, the axis of the continuing yaw drift does not shift to match the object's new local XZ plane, as we can see in this series of captures:

* The green line and ring show the object's local Y axis and local XZ plane, respectively.
* The cyan line and ring show the object's current axis and plane of rotation, respectively.
* The yellow line and ring show the object's axis and plane of rotation as they were just before the most recent torque was applied.

As we proceed from left to right, we see:

1. The object at rest, before I've applied any torques
2. After applying a yaw torque: the object yawing in its local XZ plane (green) - the cyan plane of current rotation matches this exactly.
3. After applying a roll torque: the object rotating on an inclined axis/plane (cyan) that is neither its local XZ plane (green) nor its previous plane of rotation (yellow)

And it turns out this is exactly what we expect from real physics.

After applying a torque of (0, 10, 0) for 0.02 seconds (Unity's default physics timestep), we expect to have an angular momentum of (0, 0.2, 0). Then we apply a torque of (0, 0, 10) for 0.02 seconds (assuming we waited until the forward axis was *exactly* parallel to the world z+ axis so we don't have to muck with coordinate systems), we expect to have an angular momentum of (0, 0.2, 0.2) - ie we should be rotating on an axis diagonal to our two torque vectors.

Although working with Euler/Tait-Bryan angles or yaw/pitch/roll terminology can get us used to the idea that rotation is separable into 3 independent components - so we might expect an object to "remember" its yaw speed and its roll speed in separate variables - in reality 3D rotation does not work that way.

An object in an inertial state (like a spaceship in a vacuum away from gravity wells and not currently firing its thrusters) has just one angular momentum vector - just one axis of rotation - and every torque we apply to it speeds/slows or moves that axis.

This change in the axis of rotation in response to torque is what's called precession. You may be used to it being a small/negligible effect for things like wheels, where the speed/torque spinning them up is much greater than the orthogonal torque deflecting them, and things like friction dampen the resulting movement. But in space with nothing to damp the motion, and with yaw thrusters exactly as strong as the roll thrusters, the combined effect is quite pronounced.

So, if your goal is realistic spaceship movement, I have good news for you: that's exactly what you're getting from this physics simulation!

But if this feels counter-intuitive as a control scheme for your game, then you'll need to come up with an alternative model. For instance, you could apply yaw and pitch using torques on the rigidbody, but apply roll using your own update script that just rotates a transform inside the body, without impacting its physics.
> 5 votes

# Answer
There are two methods to add torque to a rigidbody:

* `AddTorque` which interprets the vector in the world coordinate system
* `AddRelativeTorque` which interprets the vector in the local coordinate system.

You seem to want to rotate the object in the world coordinate system, so you should use `AddTorque`, not `AddRelativeTorque`.

By the way: The same applies to `AddForce` and `AddRelativeForce`.
> 3 votes

---
Tags: unity, c#, physics, rotation
---


# Question
Title: Unreal 4 - How to access and iterate through the polygons of a mesh?
I'm newbie with Unreal Engine 4. I need to create a function which calculates the volume of a mesh, based on the following example:

https://n-e-r-v-o-u-s.com/blog/?p=4415

To achieve that I created an actor blueprint containing a cone. I then created a function to calculate the volume of a tetrahedron composed by a polygon plus the center point of the scene, like that:

Now I want to iterate through each of the polygons composing the cone actor, one by one, and use the above function to calculate the total volume of the cone.

I found a possible beginning for a such iteration:

However I'm unable to find a way to create a loop which iterate through the Triangles array and extract the 3 vertices of each triangles composing the mesh.

I would be grateful if someone explained to me how to implement a such loop.

Or, if so, how to access correctly to the actor mesh vertex buffer object, and to iterate through each of the polygons composing it.

# Answer
> 2 votes
The triangles array is an array of integers indices that refer to vertices in the vertices array. Every three integers describes one of the triangles of the mesh.

Since the built-in "for each" Blueprint node doesn't support arbitrary step sizes, you can implement it yourself: initialize a local integer variable `Step` to 0, and use a "while loop" node attached to a condition for "step \< length of the Triangles array." For the body node of the loop, access the triangles array elements at `Step`, `Step + 1`, and `Step + 2`. Each of those will give you an integer you can then use to index into the Vertices array to get the triangle positions. Then increment step by three before moving to the next iteration of the loop.

This will, honestly, be a little clunky in Blueprint. It's probably easier to do in C++, not because it will be that much faster (reading the mesh data is probably the bottleneck here), but because it will be easier to express.

---

Note that `GetSectionFromStaticMesh` will not work on all meshes; it requires the mesh to be CPU-accessible, among other things. You will get warnings and empty result arrays in the cases where the operation isn't supported.

An arbitrary mesh may have more than one section in any given LOD level as well, which you'll ultimately want to decide if you care about or not.

---
Tags: unreal-4, mesh, vertex-buffer, blueprints, vertex-arrays
---


title: Move camera while dragging with mouse

text:
# Question
Title: Move camera while dragging with mouse
I'm currently trying to implement a move-to-drag behaviour in a 2d grid based game. I want to update the camera such that if follows the "head" of the trail being drawn - In this case, the nodes it is made up of some nodes returned from A\* pathfinding utility implementation.

```
AStarPathfind pather = new AStarPathfindAroundWalls(
    LayerMask.GetMask("Walls"),
    Camera.main.ScreenToWorldPoint(Input.mousePosition)
);
List<Vector2> trailPoints = pather.FindPath(new Vector2(this.transform.position.x, this.transform.position.y));
Camera.main.transform.position = new Vector3(
    trailPoints[ArrowTrailPoints.Count - 1].x,
    trailPoints[ArrowTrailPoints.Count - 1].y,
    Camera.main.transform.position.z
);

```

When I run this code, the camera sucessfully does indeed snap to the head of the path, but unfortunately, the mouse remains where it originally was, and since this code is ran during an update loop, it will simply keep adding to the path until it can no longer do so. Essentially I would like it to go to the next tile, update the camera, reset the mouse position and then await where the next part of the path should be drawn (of course, this is not possible, since I cannot modify the mouse position directly).

I've tried storing the trail points as a property in the object, and then removing the last known position from the calculation, like so

```
Camera.main.ScreenToWorldPoint(Input.mousePosition) - lastTrailPoints[lastTrailPoints.Count - 1]

```

so that the input position would be relative to the amount offset by the camera... but with no success, so I'm starting to think I'm way off using this method. If I do something like

```
Camera.main.ScreenToWorldPoint(Input.mousePosition) - (MovementNodes[MovementNodes.Count - 1] - this.transform.position)

```

Then things work almost as expected, but the mouse will still move off of the screen, and I want to keep it centered over the actual head of the trail (where the camera is).

(black cross = current mouse position, green cross = where I want the mouse pointer to be located, camera is centered over the arrow head/green cross)

Has anyone implemented something similar before and know of a solution?

# Answer
So, following on from DMGregory's comment, I was able to create a simple abstract class derived from `MonoBehaviour`, as below

```
public abstract class Cursor : MonoBehaviour {
    public void SetPosition(float x, float y){
        this.transform.position = new Vector3(
            x,
            y,
            this.transform.position.z
        );
    }
    public abstract Vector2 GetPosition();
    public abstract void UpdatePosition();
    public virtual void Start(){ }
    public virtual void Awake(){ }
    public void Update(){
        UpdatePosition();
    }
}

```

I was then able to extend this abstract class with an appropriate implementation for my input device (in this case, the mouse)

```
public class MouseCursor : Cursor {

    [SerializeField]
    private float MouseSensitity = 1f;

    public override void Awake(){
        UnityEngine.Cursor.lockState = CursorLockMode.Locked;
    }

    public override Vector2 GetPosition() {
        return this.transform.position;
    }

    public override void UpdatePosition(){
        SetPosition(
            this.transform.position.x + Input.GetAxis("Mouse X") * MouseSensitity,
            this.transform.position.y + Input.GetAxis("Mouse Y") * MouseSensitity
        );
    }
}

```

During runtime, I access the cursor implementation from a manager-type object, and am able to get

```
//Where LevelManager.GetCursor() returns an instance of Cursor
Vector2 cursorPosition = LevelManager.GetCursor().GetPosition();
AStarPathfindAroundWalls pather = new AStarPathfindAroundWalls(
    LayerMask.GetMask("Walls"),
    Camera.main.ScreenToWorldPoint(cursorPosition) //since the cursor gameobject lives in an screen-space overlay canvas, I must still convert it's coordinates here
);

```

and also set the cursor location appropriately

```
LevelManager.GetCursor().SetPosition(snapToCursorPosition.x, snapToCursorPosition.y);

```

Going forward, it would probably be best to create a `CursorAdapter` interface (rather than extending `MonoBehaviour` as an abstract class and using separate prefabs/gameobjects for each implementation), and instead make it a property of a more general `Cursor` gameobject, which could independently resolve which adapter implementation it should use, keeping it out of my `LevelManager` all together, but for now this resolves my issue of being able to set the "mouse" location manually
> 1 votes

---
Tags: unity, camera, mouse
---


# Question
Title: How could a NPC find items that appear randomly?
My main question is basically: What is the algorithm that CPU players use in smash bros to find items like the smash ball? I am trying to make a small ai character that will "look around" and once an item appears it will find it and walk to it. In all smash bros the cpu players are able to find items on the stage when they appear. How do they do this?

# Answer
> 3 votes
On spawn of the object, relevant "listeners" (your NPCs) should be pinged.

Once pinged, the listener can now use the distance from the object, line of sight of the object, the value of the object, the distance of other interested listeners from the object, and other useful variables to develop a weight or a metric that would prioritize any number of available decisions which may result in moving towards the object.

# Answer
> 1 votes
## How to find an object

When an object spawns, you could tell all listeners (i.e. NPCs) that the item has spawned and where it has spawned ("where" can be a simple vector point or a reference to a node. More on the latter later). This can be done using an **event emitter** of some sort, where entities create a listener on some event (e.g. 'onitemspawn') and then act upon it when the event is emitted.

## How to move the player towards the item

As soon as the AI agent sees the item, you can program it to move towards the item immediately or when it isn't engaging the player (or whenever really, this is all up to you). When you know where the item is, you can use a pathfinding algorithm like A\*. This will find the shortest path to the item quickly.

---
Tags: algorithm, ai, npc, search
---


# Question
Title: How do I convert degrees to radians and vice versa in Godot?
In a game I'm toying with in Godot engine I have angles given in degrees in some places and angles given in radians in other places. Sometimes I need to mix both angles (ie. add them).

What built-in function allows me to convert degrees to radians (and the other way around)? Or is there none?

P.S. I realize that converting those is not rocket science and I could code something on my own, but Godot is already doing such conversions internally, so I would venture a guess that such function already exists.

# Answer
> 18 votes
This can be achieved:

Each function takes a float (the value being converted) and returns a float (the converted value).

# Answer
> 0 votes
Some nodes in Godot 3.0 have a property `rotation_degrees` that you can use, i.e

```
# rotate the node a quarter turn using radians
my_2D_node.rotation += PI / 2
# read the current rotation in degrees
my_2D_node.rotation_degrees

```

The property rotation\_degrees can be read and set, so you can for example write the property as `.rotation` in radians where convenient and somewhere else in the script read the property as `.rotation_degrees` if degrees would be more convenient. The object will do the conversion for you

---
Tags: godot
---


# Question
Title: How would I properly flip a character when they reach the edge of a ground object in Unity 2D?
The idea here is that the raycast shoots downwards from an empty game object and when it detects that there is no ground below it the character should bounce back and walk the other way. When I get to the edge of my platform the character just gets stuck in place and keeps rotating on the Y axis.

```
public class npcAI : MonoBehaviour
{
public float speed;
public float distance;
private bool movingRight = true;
public Transform groundDetection; //raycast goes downward from this point

private Vector2 movementDirection;

void Start()
{
    //Initialise direction
    movementDirection = Vector2.right;
}

void Update()
{
    transform.Translate(movementDirection * speed * Time.deltaTime);
    RaycastHit2D groundInfo = Physics2D.Raycast(groundDetection.position, Vector2.down, distance);
    if (groundInfo.collider == false)
    {
        if (movingRight)
        {
            movingRight = false;
            movementDirection = Vector2.left;
      transform.localScale -= new Vector3(0.30F, 0, 0);

        }
        else
        {
            movingRight = true;
            movementDirection = Vector2.right;
      transform.localScale += new Vector3(0.30F, 0, 0);
        }

    }
}

```

The code above was edited to reflect the answer below. If you find yourself attempting to do the same thing and need to flip your sprite when you reach the edge change 0.30F to whatever double the X value of your sprite is in order to flip it. My sprites scale was (0.15, 0.15, 0) so I used 0.30F to flip my sprite. Be mindful of when you should use -= and when you should use +=.

# Answer
> 1 votes
It looks as though your if block is wrong:

```
if (groundInfo.collider == false)
{
    if (movingRight == true)
    {
        transform.eulerAngles = new Vector3(0, -180, 0);
    }
    movingRight = false;
}
else
{
    transform.eulerAngles = new Vector3(0, 0, 0);
    movingRight = true;
}

```

Try this instead:

```
if (groundInfo.collider == false)
{
    if (movingRight)
    {
        transform.eulerAngles = new Vector3(0, -180, 0);
        movingRight = false;
    }
    else
    {
        transform.eulerAngles = new Vector3(0, 0, 0);
        movingRight = true;
    }
}

```

Personally I would have done something like this:

```
public class npcAI : MonoBehaviour
{
    public float speed;
    public float distance;
    private bool movingRight = true;
    public Transform groundDetection; //raycast goes downward from this point

    private Vector2 movementDirection;

    void Start()
    {
        //Initialise direction
        movementDirection = Vector2.right;
    }

    void Update()
    {
        transform.Translate(movementDirection * speed * Time.deltaTime);
        RaycastHit2D groundInfo = Physics2D.Raycast(groundDetection.position, Vector2.down, distance);
        if (groundInfo.collider == false)
        {
            if (movingRight)
            {
                movingRight = false;
                movementDirection = Vector2.left;

            }
            else
            {
                movingRight = true;
                movementDirection = Vector2.right;
            }

        }
    }
}

```

---
Tags: unity, c#, raycasting
---


# Question
Title: Quaternion representing rotation from shoulder to hand
I am provided with 3 quaternions. One for the shoulder, one for the elbow, and one for the hand. What I want is to obtain a single quaternion representing the rotation from the shoulder to the hand, essentially removing the elbow in the process. I have a diagram below to better illustrate this.

Assuming that both of the above sections (forearm and upper arm) are of the same length, how could this be calculated?

# Answer
> Assuming that both of the above sections (forearm and upper arm) are of the same length

Then let 1 unit of our coordinate system be the length of one arm segment. Let's also assume the joint quaternions we have are arranged so they point a unit "forward" vector along the length of the bone.

```
elbowOffsetFromShoulder = shoulderRotation * forward;

handOffsetFromShoulder = elbowOffsetFromShoulder + shoulderRotation * elbowRotation * forward;

```

Now we can form a quaternion that orients the forward vector to point from the shoulder to the hand with a LookRotation convenience method. This still leaves us with one degree of freedom: the twist of the rotation about the shoulder-hand line. We can arbitrarily choose to try to align the up vector of our resulting rotation as close as possible with the shoulder's local up.

```
shoulderToHandRotation = Quaternion.LookRotation(handOffsetFromShoulder, up);

```

If you're in an engine like Unity you'll have a convenience method like this already. If not, you can implement your own version, or construct a matrix with the desired orientation (`eg. column 3 = normalize(handOffsetFromShoulder), column 2 = normalize(up - dot(up, column 3) * column 3, column 1 = cross(column 2, column3)`) and convert the matrix to a quaternion.

Note that this quaternion generally points in a different direction than the forearm's orientation, so if you then stack a hand or pointer with a particular orientation on the end, it will need adjustment to stay aligned with its new parent, ie.

```
newHandRotation = Inverse(shoulderToHandRotation) * shoulderRotation * elbowRotation * handRotation;

```
> 0 votes

---
Tags: mathematics, quaternion
---


# Question
Title: Unity / How to access my screen pixels outside of unity?
I want to run unity in background and get the pixel colors of my screen. i didnt find anything on the assetstore or somewhere else that could make that possible.

Texture.ReadPixels() also does only work for the game camera

What is the way to solve this?

# Answer
> 1 votes
Allright, so ive found this here:

https://github.com/hecomi/uDesktopDuplication

With that you can read pixels while running unity on background. :-) Just wanted to share this.

---
Tags: unity, screen
---


# Question
Title: Trying to find a function to calculate attribute changes in a game
I'm coding a game where after every year depending on results the attributes of characters change. The game is a movie business simulator and here is a example of the ugly code I have in place now:

```
        if (movie.Reviews.Avg > 8.5f)
        {
            movie.Producer.Reputation += 6f / movie.Producer.Reputation;
            return;
        }
        else if (movie.Reviews.Avg > 7.5f)
        {
            movie.Producer.Reputation += 5f / movie.Producer.Reputation;
            return;
        }
        else if (movie.Reviews.Avg > 6.5f)
        {
            movie.Producer.Reputation += 4f / movie.Producer.Reputation;
            return;
        }
        else if (movie.Reviews.Avg > 5)
        {
            movie.Producer.Reputation += 1f / movie.Producer.Reputation;
            return;
        }
        else if (movie.Reviews.Avg > 4.5)
        {
            return;
        }
        else if (movie.Reviews.Avg > 4)
        {
            movie.Producer.Reputation -= movie.Producer.Reputation / 6f;
            return;
        }
        else if (movie.Reviews.Avg > 3)
        {
            movie.Producer.Reputation -= movie.Producer.Reputation / 5f;
            return;
        }
        else if (movie.Reviews.Avg > 2)
        {
            movie.Producer.Reputation -= movie.Producer.Reputation / 4f;
            return;
        }
        else
        {
            movie.Producer.Reputation -= movie.Producer.Reputation / 3f;
            return;
        }

```

Few problems I have with this code: 1. Reputations balloon. Good AI producers make good choices so their movies get good reviews and their reputation goes even higher. 2. Because reputations keep growing the absolute changes in attributes get smaller and moving up in ranks gets way too slow and hard.

What I am looking from the function: 1. Range is 0-10. 2. At the top of the range growth is slow even with great reviews, but if your movie gets bad reviews the decline is sharp. And the opposite for the bottom of the range.

# Answer
> 0 votes
I'd recommend modelling your "reputation" stat as an "expected review score"

ie. A producer with a reputation of 8.5 is a producer I expect will produce movies that review around 8.5 on average.

That approach keeps your reputation bounded between 0 and 10, solving the ballooning problem, and giving a clear meaning to how good a particular reputation number is.

Then we can update the reputation like this:

```
newReputation = oldReputation + (movie.Reviews.Avg - oldReputation) * fickleness;

```

Here `fickleness` is a parameter that controls how quickly people change their minds about a producer:

* At 0, the producer's previous reputation stays fixed no matter what happens.
* At 1, the reputation changes to match whatever the producer's last movie rated.
* In-between, there's a balance you can control between the producer's past history and the latest info.

(You can even scale this parameter based on the producer's experience, making it high for newcomers quickly establishing their initial reputation, and lower for producers with many films under their belt, whose reputations are more stable)

The further the reviews are from what we expect from this producer's reputation, the more the reputation changes as a result. The closer it is to what we expect, the less the reputation changes.

A review above expectation will raise the producer's reputation, while one below expectation will lower it.

# Answer
> 2 votes
What you want to use is a sigmoid (logistic function) scaled between 0 and 10. There are a variety of formulas available. I would suggest using one that is parameterized for a midpoint.

Includes a basic logistic function in the explanation

---
Tags: c#, mathematics
---


# Question
Title: Can I apply a force to particles from a script?
I'm working on a game which involves streams of electrically-charged particles, being manipulated with electric and magnetic fields. Since I want a large number of small objects coming from an emitter and lasting a limited amount of time, a particle system seems like the way to go.

My only problem now is: how to apply the force? Suppose, for example, I have a charged object somewhere in the scene; I want to apply a force toward it, varying with the radius squared. If my particles were Rigidbodies, applying this force in the FixedUpdate would be easy; is there a way to do the same to an individual particle?

# Answer
In 2018.2, the only way to apply external forces is through Wind Fields or direct collisions with rigid bodies.

You will probably have luck by using the ShapeModule with a ShapeType of `Mesh` and MeshShapeType of `Edge`. You could then have the player manipulate the vertex positions of the mesh to create the field line along which the particle will travel.

If you're comfortable with using beta builds of Unity, the 2018.3b version introduces a new `GameObject` `Component` called ParticleSystemForceField. This allows you to define custom areas of forces to be applied to particle that enter the area.

A good demo of the experimental features is available in The Unity Particle System Update: Features, Tips and Beyond! recording of the Unite Seoul Conference, May 2018.
> 3 votes

---
Tags: unity, physics, particles
---


# Question
Title: Extracting individual components of a vector in the Source Shader Editor
I'm using the Source Shader editor and would like to mask a vector output to one or two values, yet there is no existing mask node, as far as I can see.

What HLSL code should I use to output what I need? The input would be in the format "x y z". Any help would be greatly appreciated

# Answer
> 0 votes
It sounds like you might be looking for the Swizzle node. According to Valve's documentation:

> **Swizzle** (Vectors)
>
> Uses arbitrary swizzling on a vector. You can also swizzle with constants and change the vector dimensions as you see fit. Use the properties dialog to define the swizzle operation, supports token channels.

So to take an input vector (x, y, z) and select just the y component, you'd place a Swizzle node by right-clicking and selecting `New node -> Math (Vectors) -> Swizzle`, then double-click it to access its properties and enter the string "y" to output just the y component as its own pin.

You can add additional Swizzle nodes to split out the x and z components too, to have three separate paths in your graph for the three components of the vector.

# Answer
> -3 votes
try using a float3 since that is the way to get x y z into a shader

---
Tags: shaders, hlsl, source-engine
---


# Question
Title: How many and which axes to use for 3D OBB collision with SAT
I've been implementing the SAT based on:

On page 7, in the table, it refers the 15 axis to test so we can find a collision, but with just Ax, Ay and Az, I'm already getting collisions.

Why do i need to test all the other cases? Is there any situation where just Ax, Ay and Az are not enough?

# Answer
You may be geting false positives. Collisions detected but not really colliding.

The number 15 comes from

* 3 axes from object A (face normals)
* 3 axes from object B (face normals)
* 9 axes from all the pairs of edges of A and edges of B (3x3)
* =15 in total

The 9 axes are made up of cross products of edges of A and edges of B

1. Ae1 x Be1 (Edge 1 of A cross edge 1 of B)
2. Ae1 x Be2
3. Ae1 x Be3
4. Ae2 x Be1
5. ... and so on

The first 6 axes (from the face normals) are used to check if there a corner of one object is intersecting a face of the other object. (or more correctly to eliminate these kinds of collisions)

The set of 9 axes formed by the cross products of edges are used to consider edge on edge collision detection, where there is not a vertex penetrating the other object. Like the 'almost' collision in the photo below. Lets assume for the rest of this answer that the two boxes in the picture are not actually colliding, but are separated by a tiny distance.

Lets look at what happens if we just use the 6 face normals for SAT. The first image below shows one axis from the blue box and 2 axes from the yellow box. If we project both objects on to these axes, we will get an overlap on all three. The second image below shows the remaining two axes of the blue box and the remaining axis of the yellow box. Again projecting on these axes will show overlaps on all 3.

So just only checking the 6 face normals will show overlaps on all 6 axes, which, according to the SAT, means that the objects are colliding, because we have not been able to find a separation. But of course, these object are not colliding. The reason we have not found a separation is because we have not looked hard enough!

So how are we to find this gap? The image below show an axis on which projection of both objects will reveal a separation.

Where do we get this axis from?

If you imagine sliding a piece of stiff card into the gap, that card will be part of the separating plane. If we project on to the normal of that plane (black arrow in picture above), we will see the separation. We know what that plane is because we have two vectors which lie on that plane) One vector is aligned with the edge of blue and the other vector is aligned with the edge of yellow and as we all know the normal to a plane is simply the cross product of two vectors lying on the plane.

So for OOBBs we need to check every combination(9 of them) of cross products of the edges of the two objects to make sure we are not missing any edge-edge separations.
> 69 votes

# Answer
Ken's answer notes:

> The 9 axes are made up of cross products of edges of A and edges of B

It's somewhat confusing to refer to the edges, as there are 12 edges compared to 6 normals, when you might as well use the three main normals for the very same output - the edges are all aligned with the normals, so I recommend using them instead!

Also note that normals pointing along the same axis, but in a different direction, are ignored, and thus we're left with three unique axes.

Another thing I'd like to add, is that you can optimize this calculation by exiting early if you find a separating axis, before you calculate all the axes you want to test. So, no, you don't need to test all axes in every case, but you do need to be ready to test them all :)

Here's a complete list of axes to test, given two OBBs, A and B, where x, y and z refer to the basis vectors / three unique normals. 0 = x axis, 1 = y axis, 2 = z axis

1. a0
2. a1
3. a2
4. b0
5. b1
6. b2
7. cross( a0, b0 )
8. cross( a0, b1 )
9. cross( a0, b2 )
10. cross( a1, b0 )
11. cross( a1, b1 )
12. cross( a1, b2 )
13. cross( a2, b0 )
14. cross( a2, b1 )
15. cross( a2, b2 )

There's also a little caveat, that you should be aware of.

The cross product will give you a zero vector {0,0,0} when any two axes between the objects point in the same direction.

Also, since this part was left out, here's my implementation to check whether or not the projection is overlapping. There's probably a better way, but this worked for me! (Using Unity and its C# API)

```
// aCorn and bCorn are arrays containing all corners (vertices) of the two OBBs
private static bool IntersectsWhenProjected( Vector3[] aCorn, Vector3[] bCorn, Vector3 axis ) {

    // Handles the cross product = {0,0,0} case
    if( axis == Vector3.zero )
        return true;

    float aMin = float.MaxValue;
    float aMax = float.MinValue;
    float bMin = float.MaxValue;
    float bMax = float.MinValue;

    // Define two intervals, a and b. Calculate their min and max values
    for( int i = 0; i < 8; i++ ) {
        float aDist = Vector3.Dot( aCorn[i], axis );
        aMin = ( aDist < aMin ) ? aDist : aMin;
        aMax = ( aDist > aMax ) ? aDist : aMax;
        float bDist = Vector3.Dot( bCorn[i], axis );
        bMin = ( bDist < bMin ) ? bDist : bMin;
        bMax = ( bDist > bMax ) ? bDist : bMax;
    }

    // One-dimensional intersection test between a and b
    float longSpan = Mathf.Max( aMax, bMax ) - Mathf.Min( aMin, bMin );
    float sumSpan = aMax - aMin + bMax - bMin;
    return longSpan < sumSpan; // Change this to <= if you want the case were they are touching but not overlapping, to count as an intersection
}

```
> 18 votes

# Answer
working c# example based on Acegikmo's answer (using some unity api's):

```
using UnityEngine;

public class ObbTest : MonoBehaviour
{
 public Transform A;
 public Transform B;

 void Start()
 {
      Debug.Log(Intersects(ToObb(A), ToObb(B)));
 }

 static Obb ToObb(Transform t)
 {
      return new Obb(t.position, t.localScale, t.rotation);
 }

 class Obb
 {
      public readonly Vector3[] Vertices;
      public readonly Vector3 Right;
      public readonly Vector3 Up;
      public readonly Vector3 Forward;

      public Obb(Vector3 center, Vector3 size, Quaternion rotation)
      {
           var max = size / 2;
           var min = -max;

           Vertices = new[]
           {
                center + rotation * min,
                center + rotation * new Vector3(max.x, min.y, min.z),
                center + rotation * new Vector3(min.x, max.y, min.z),
                center + rotation * new Vector3(max.x, max.y, min.z),
                center + rotation * new Vector3(min.x, min.y, max.z),
                center + rotation * new Vector3(max.x, min.y, max.z),
                center + rotation * new Vector3(min.x, max.y, max.z),
                center + rotation * max,
           };

           Right = rotation * Vector3.right;
           Up = rotation * Vector3.up;
           Forward = rotation * Vector3.forward;
      }
 }

 static bool Intersects(Obb a, Obb b)
 {
      if (Separated(a.Vertices, b.Vertices, a.Right))
           return false;
      if (Separated(a.Vertices, b.Vertices, a.Up))
           return false;
      if (Separated(a.Vertices, b.Vertices, a.Forward))
           return false;

      if (Separated(a.Vertices, b.Vertices, b.Right))
           return false;
      if (Separated(a.Vertices, b.Vertices, b.Up))
           return false;
      if (Separated(a.Vertices, b.Vertices, b.Forward))
           return false;

      if (Separated(a.Vertices, b.Vertices, Vector3.Cross(a.Right, b.Right)))
           return false;
      if (Separated(a.Vertices, b.Vertices, Vector3.Cross(a.Right, b.Up)))
           return false;
      if (Separated(a.Vertices, b.Vertices, Vector3.Cross(a.Right, b.Forward)))
           return false;

      if (Separated(a.Vertices, b.Vertices, Vector3.Cross(a.Up, b.Right)))
           return false;
      if (Separated(a.Vertices, b.Vertices, Vector3.Cross(a.Up, b.Up)))
           return false;
      if (Separated(a.Vertices, b.Vertices, Vector3.Cross(a.Up, b.Forward)))
           return false;

      if (Separated(a.Vertices, b.Vertices, Vector3.Cross(a.Forward, b.Right)))
           return false;
      if (Separated(a.Vertices, b.Vertices, Vector3.Cross(a.Forward, b.Up)))
           return false;
      if (Separated(a.Vertices, b.Vertices, Vector3.Cross(a.Forward, b.Forward)))
           return false;

      return true;
 }

 static bool Separated(Vector3[] vertsA, Vector3[] vertsB, Vector3 axis)
 {
      // Handles the cross product = {0,0,0} case
      if (axis == Vector3.zero)
           return false;

      var aMin = float.MaxValue;
      var aMax = float.MinValue;
      var bMin = float.MaxValue;
      var bMax = float.MinValue;

      // Define two intervals, a and b. Calculate their min and max values
      for (var i = 0; i < 8; i++)
      {
           var aDist = Vector3.Dot(vertsA[i], axis);
           aMin = aDist < aMin ? aDist : aMin;
           aMax = aDist > aMax ? aDist : aMax;
           var bDist = Vector3.Dot(vertsB[i], axis);
           bMin = bDist < bMin ? bDist : bMin;
           bMax = bDist > bMax ? bDist : bMax;
      }

      // One-dimensional intersection test between a and b
      var longSpan = Mathf.Max(aMax, bMax) - Mathf.Min(aMin, bMin);
      var sumSpan = aMax - aMin + bMax - bMin;
      return longSpan >= sumSpan; // > to treat touching as intersection
 }
}

```
> 4 votes

---
Tags: collision-detection, separating-axis-theorem
---


# Question
Title: What is the physics behind a 2D gravity tunnel?
In Portal 2, there is a concept of an "excursion funnel", a beam of light that moves physical objects in a certain direction.

Here is a link to a demonstration.

I added a simple implementation that lets me float upward against gravity (I can't give you an example I've tried as I've lost it due to the undo buffer size being too small), however I've been having a struggle generalizing it to work with any angle.

My code so far:

```
// on funnel collision with body:
    body->SetGravityScale(0);

// on each update, for each body that is in collision:
    float s = sin(this->body->GetAngle()), c = cos(this->body->GetAngle());

    b2Vec2 force = {body->GetWorld()->GetGravity().x * -s * 2.f, body->GetWorld()->GetGravity().y * -c * 2.f};
    for(ServerEnt* e : collidingWith) {
        e->body->ApplyForceToCenter(e->body->GetMass() * force, true);
    }

// on funnel end collision with body:
    body->SetGravityScale(1);

```

This almost works, except Portal 2 funnels don't let objects fall through it, they sort of push the objects toward the center of the nearest cross-section of the funnel, which is where my code fails, or rather doesn't do anything about.

# Answer
1. On collision with the field, set gravity to 0.
2. While colliding with the field, multiply your velocity by a number between 0 and 1, like 0.999; This is called "damping", it simulates being inside a viscous fluid.
3. While colliding with the field, apply a force along whatever vector you want to push the body in.This in combination with the damping should push the object along at a more or less constant velocity.
4. If you want to get fancy, add a restoring force toward the center of the field that increases proportionally with the distance of the object to the center of the field. This will prevent the object from falling out of the field. This basically models a spring between the body and the center of the field.

As an example of (4), if your field is a circle, you can do it like this:

```
// pos is the position of the body. The field is a circle, but only
// its center matters. Gain is a multiplier on the force.
Vector2 restoringForce(Vector2 pos, Circle field, float gain) {
    // Vector pointing from the middle of the circle to the player.
    Vector2 diff = pos - field.center;
    // The restoring force points toward the center of the circle
    // and is proportional to the distance.
    return -gain * diff;
}

```

If your field is a line, you can do it like this:

```
// Note this is totally untested and some signs might need to change.
Vector2 restoringForce(Vector2 pos, Line field, float gain) {
    // Direction of the line segment.
    Vector2 fieldDirection = (field.end - field.start).normalized();
    // Lift the direction to 3D.
    Vector3 fieldDirection3D = new Vector3(fieldDirection.x, fieldDirection.y, fieldDirection.z);
    // Find a vector pointing perpendicular to the field vector.
    Vector3 normal = (new Vector3(0, 0, 1)).cross(fieldDirection3D);
    // Project the normal back to 2D.
    Vector2 normal2D = new Vector3(normal.x, normal.y);
    // Define a point on the line.
    Vector2 center = (field.end + field.start) * 0.5f;
    // Find the difference between the body position and the point
    // in question.
    Vector2 diff = pos - center;
    // This is the distance along the normal to the line.
    float dist = diff.dot(normal2D);
    // The restoring force points toward the line segment along the
    // normal, and is proportional to the distance to the center.
    return -gain * dist * normal;
}

```
> 5 votes

---
Tags: physics, mathematics, box2d
---


title: Transform GameObject on Instantiate

text:
# Question
Title: Transform GameObject on Instantiate
So, I'm having a bit of an issue with transforming a GO after instantiation in the way that I want.

I have a main GO. On death, it spawns secondary GOs. All GOs involved are kinematic (because the AI controller moves them). So I use lerps to move the secondary GOs on instantiation in a sort of fountain pattern. However, because of the static movement, they get pushed through walls and other surfaces.

I thought I'd try using physics for this with a `ForceMode.Impulse` push, but to do that I have to make it non-kinematic. To do that, I also have to set it's mesh to be non-convex. Making the mesh convex causes a ~1000ms delay on instantiation while the PhysX engine parses the mesh.

So... what other options do I have? Is there any other way to use the basic transform lerps and still have it not pass through walls? I'm assuming that the direct transform is causing collision to not happen. Or maybe because I'm disabling the CharacterController until it reaches it's end position (otherwise it tries to move right away using AI).

# Answer
Food for thought but, 1) how are you detecting collision? If using OnCollisionEnter() try using OnTriggerEnter() and vice versa. Works for me sometimes. 2) Maybe try giving the secondary objects a ForceMode.Impulse away from the walls when they are near them? Try tracking the distance between walls and secondary objects and when the distance is near do \___. Slows down performance a bit (or a lot depending on how many secondary objects you have) but one out-of-the-box way to do it

My suggestion as per distance: create an array of gameObjects that stores the transform of each wall. Make a function that, each time it is called, iterates through the array of walls and calculates the distance from ith wall to the player. If distance between the two is less than 'x' then return true.

```
bool calculateDistance(gameObject[] wallArray){
for(int i = 0; i < wallArray.Length; i++){
if(distance between player and wallArray[i] < 'x') //x being arbitary value
 then return true;
}
return false;
}

```
> 1 votes

# Answer
It can be useful:

1) make a memory load of the objects you are going to use. This would be, if you are going to have to use the "Instantiate" for many objects and that causes you to lose FPS, it is common to load the level do the "Instantiate" of (for example) 10 GO and deactivate them, save them in a list and where you previously used the "Instantiate" call a method that searches the list in the first GO off and returns it activated. (this is used a lot and this method will become part of your toolbox)

2) Use physical layers to prevent objects that we do not want to collide, collide. Create layers in the Object inspector, and assign them that layer, then from the layers configuration table unselect the layers that we do not want them to collide. (When you have a pc with Unity available, edit the post, if you need help creating the physical layers)
> 0 votes

---
Tags: unity, physics
---


# Question
Title: Unity, tell matched players to go pick characters (Matchmaking)
I need to tell all the players in the match to go to some method that'd take them to character pick. The thing is that the pick happens inside the menu scene after the level get's preloaded (ascyncroneously). So the players stay in the same menu scene but they have to pick characters before the time runs out and the level itself starts. Is it possible to do that in multiplayer using the matchmaker? How can it be done if so?

Thanks in advance!

# Answer
> Is it possible to do that in multiplayer using the matchmaker?

It sure is!

> How can it be done if so?

Essentially you have to create your own NetworkManager, if you look at the source of the default NetworkManager or NetworkLobbyManager (Make sure you alter the branch to your Unity version) you'll find they are just using the Network Messages API to create the flow of creating players and moving scenes.

So for your custom network manager you would need to create a message:

```
public class GameMessageTypes
{
    public static short CharacterSelect = MsgType.Highest + 1;
}

public class CharacterSelectedMessage : MessageBase
{
    public int characterID;
    public int slotID; // Assuming you use the NetworkLobbyManager as a base, otherwise figure out your own slot system
    public bool isLocked;
}

```

then in both the client and server you would register to listen for it:

```
// In the server only register.
NetworkServer.RegisterHandler(GameMessageTypes.CharacterSelect, OnServerCharacterSelectInternal);

// In the client only register.
client.RegisterHandler(GameMessageTypes.CharacterSelect, OnClientCharacterSelectInternal);

```

You would ensure that you don't move \ load the next scene until all slots have selected a character or the timer to select has run out. In the server handler you would let other clients know of a clients selection and in the client handler you would update the UI \ view to show the player what the other players have selected.

One thing to note is that UNET is getting deprecated:

so you might want to look at your own system or use one of the forks of UNET that is community maintained like mirror. If you go the route of your own system you should look at the benchmark tests that a helpful community member made.
> 0 votes

---
Tags: unity, multiplayer, matchmaking
---


# Question
Title: How to zoom in and out the full tilemap from center in phaser?
I am developing a game where I need to zoom in entire map also I can be able zoom out. I have created a tilemap using tiled software and rendered it using phaser.js. How can I add this function to my game?

# Answer
> 1 votes
First you need to setup your camera like this:

```
this.camera = this.cameras.main.setBounds(0, 0, 640, 340);

// make the camera follow the player
this.camera.startFollow(this.player);

// set background color, so the sky is not black
this.camera.setBackgroundColor('#000000');

```

And you can set up the zoom like this:

```
this.camera.zoomTo(
2, //zoom distance
1000 // duration/speed of zoom
);

```

---
Tags: javascript, tilemap, phaser, tiled
---


# Question
Title: How to instantiate a sprite from a sprite sheet using script in unity?
We are creating a 2D top down rpg, and we have multiple textures, and we need to be able to change which sprite sheet its reading from in order to change the look of the walls and floor in each room. It has the same basic tiles just they need to look different. Like the corner of a cabin, to the corner of an office building.

At the moment we are taking the sprite sheet, splitting it up, and making prefabs out of it for placement by script in the game. Is there a way to do this automatically because we have a lot of textures, and its too many to make into prefabs.

# Answer
If the sprites are in your Assets/Resources directory, you can load them programmatically as follows:

```
Sprite[] spriteSheetSprites = Resources.LoadAll<Sprite>("spriteSheetName);

```

This will yield a `Sprite` array containing all of the sprites from your spritesheet, indexed by their order on the sheet.

A requirement to use this is that the image's import settings must be set to `Sprite (2D and UI)` and `Multiple`. The other settings should not matter. Also, the sprites must be somewhere inside of your `Assets/Resources` directory, though they can be in a subfolder. To access/load sprites in a subfolder, just append the name of the folder to the beginning of the string, as follows (this assumes that your tiles are in the `Assets/Resources/Tiles` directory:

```
Sprite[] roadSprites = Resources.LoadAll<Sprite>("Tiles/roadSpriteSheet");

```

Note that loading resources like this is quite heavy on hardware usage, so do not do this many times in your game. A way around this is to have a static `SpriteManager` class, or similar, that keeps references to sprites inside of itself, which classes can request, so that each sprite is loaded a maximum of once.

```
static class SpriteManager
{
    private Sprite[] _officeSprites;
    static SpriteManager {}
    public Sprite[] OfficeSprites
    {
        if(_officeSprites == null)
            _officeSprites = Resources.LoadAll<Sprite>("Tiles/officeSpriteSheet");
        return _officeSprites;
    }
}

```
> 3 votes

# Answer
pick your instantiated prefab, say

```
GameObject go = GameObject.Instantiate(yourPrefab) as GameObject;

```

and get for example a sprite

```
Sprite yourSprite = Resources.Load("sprite" typeOf(Sprite));

```

and change the prite

```
go.GetComponent<SpriteRenderer>().sprite = yourSprite;

```
> 0 votes

# Answer
In my project, I create **ScriptableObject** to store the sprite, and load the created asset at runtime, it quite convenient than prefab.

```
AssetDatabase.LoadAllAssetsAtPath("pathToPngfile")

```

This will load all the sprite at the specific path
> 0 votes

---
Tags: unity, 2d, sprites
---


# Question
Title: How to find the resulting angle of a ball hitting a wall in 2D
So there's a ball moving on a 2D plane with any vector. When it comes into contact with a collider, it should reflect in a linear fashion. What formula should be used in order to find the angle that this new direction should have? The pieces of information that are known are:

* The X and Y velocity of the ball when it was hit
* The angle it was travelling at when it was hit
* The point of contact

I've found many solutions for if the ball can only hit vertical or horizontal walls, but have yet to find a one for a general case.

# Answer
> 1 votes
Exit angle is equal to entry angle.

In the sketch, angles labeled X are equal to each other and angles labeled Y are equal to each other. The line is the normal (perpendicular) to the wall (rectangle)

However, if you are doing this programmatically (and I assume you are, since you are asking about Unity on the game dev so) you may be better off not worrying about what the resulting angle will be.

What I suggest you do, is take your balls velocity vector, rotate it by an amount equal to the slant of the wall, flip the x-component of the vector (assuming you rotated so your wall would lay flat), then rotate the resulting vector back again.

If your ball has no velocity, since you seem to only have an angle, simply create a vector of magnitude 1 (or whatever) and the correct angle, and apply process above.

---
Tags: unity, c#, 2d, physics
---


title: What are the cons of a 3 team FPS?

text:
# Question
Title: What are the cons of a 3 team FPS?
In creating a video game concept, there are very little video games that offer a 3 team multiplayer FPS (think like Overwatch/Call of Duty but with 3 teams instead of 2). The only 'mainstream' games that offer this are RTS games.

What are the cons of implementing a 3 team multiplayer FPS game?

# Answer
> 6 votes
* **Map design is harder.**

+ Spawning points

    Many FPS games have some predefined spawning points for each team.

    If you were to add another team, you may need to design new maps or, at the very least, figure out where to put the teams such that they're far enough from one another and about the same distance from each other team (otherwise the closest teams may just focus on each other, or the team in the "middle" may be focused by both other teams).
    + Symmetry

    Any symmetric map should give no team an advantage with 2 teams (although whether this is strictly true is another question).

    Designing perfectly equal maps for 3 teams is much harder.
    + Swapping teams

    With 2 teams, you could just play 2 games with the teams swapped around to even out unbalanced maps.

    With 3 teams, you'll need to play 6 games instead (that is one game for every permutation of positions for every team).
* **Game mode design is harder.**

2 teams naturally allows for various types of base defence modes (e.g. capture the flag or hostage rescue).

You may have a hard time designing a mode for 3 teams that's something other than "everyone murders everyone else" (even if there are also a few options there).
* **Ranking is harder.**

Many or most multiplayer games these days have ranking systems, and plenty have tournaments.

For 2 teams there are common ranking systems and tournament formats that can be used.

I'm not aware of similar systems or formats for 3 teams, but even if there are some, they may be less common and not so well tested or refined.

There would also be the problem that the two weaker teams, knowing they'd lose if they don't, can team up against the stronger team. This alone would likely be a significant hinderance to having a fair ranking system.

None of these are deal-breakers and it may be entirely possible to make a fun 3+-team FPS, but the question is **why**.

Would it make the game significantly more fun to go through the effort of allowing for another team?

For most FPS's, they decided that the answer to this question is "no".

# Answer
> 2 votes
I see this as less a matter of Pros v Cons as an application of the Zero/One/Infinity rule. The ZOI rule states that you can justify forbidding something, or limiting the something to 1. But once you start going above 1, whatever reasoning you used to justify 2 could be used to justify 3 or 4 or 5. And whatever reasoning you used to justify limiting it to 4 could be used for 3 or 2 or 1.

So consider your question from the player's perspective: the number of human opponents they face:

Zero: This is a single-player game.

One: This is a 1v1 game. The player is focused on a single, specific human opponent, much like any number of 1v1 real-life games.

Two: So, there is more than one human opponent. Why stop at 2? Why not allow 3 or 4? Or 20 human opponents? 1v1 has a specific flavor to it, where you're in a duel with a single opponent/team. But 1v1v1 is not all that different from 1v1v1v1. Which is why RTS games that allow more than one opponent typically have a large limit (and the limit is only there for resource/map-size reasons).

That's why you don't see a lot of 3-player games. It's either single-player, dueling, or free-for-all/Battle Royal.

Note that the above reasoning assumes that each player/team is playing the *same game*. That is, they're all operating under basically the same rules of play and using the same gameplay mechanics. Having a third player act in a 1v1 game with different abilities from the other two sides is a different concept, with a very different feel from merely 1v1v1. Like, if you have two teams that are hunting down a third player, but that third player is a super-powered player. You score points by attacks to the third player, but you also can attack the other team to prevent them from attacking the third player.

# Answer
> 1 votes
Such games did exist; a few custom Starsiege (mech sim game) maps were 3- or 4- team deathmatch or capture-the-flag modes. Before the dominance of DotA, there were a few wacky multi-team MOBA maps.

They were usually the least popular maps.

The maps were highly symmetrical, just like RTS maps. The game experience was something between a free-for-all and a team game, except with a major problem: **pile on**.

With the stronger teams ganging up on the weaker teams, those members will get upset quickly and try to switch teams or just leave the game, until only two teams were left.

Why isn't this a problem with free-for-all? Sometimes it is, but in many FPS free-for-alls:

* There's high turnover; most players die before long, and once they respawn their equipment is reset. Besides, there's always weaker players to exploit. In team games however, you can't reset the whole team until the end of the game, so dominance hierarchies persist.
* You can't switch teams; well, there are no teams at all.

This also isn't a problem in other genres (RTS, tabletop games) because players can't freely change teams or leave mid-game.

# Answer
> 0 votes
I wouldn't really call it a "con" but, having 3 teams in an FPS makes less impact than for example in a RTS game.

When playing a RTS game, you have to think of strategies, how to take advantage of situations, capture lands, and diminish your enemies. Knowing who is your enemy's enemy can have a massive advantage, which you can use to win.

In a FPS game, at least the ones I've played, it's more like "Run around and kill whoever is not in your team". Obviously there is room for strategy, but you can't really take advantage of knowing your enemy's enemy, not to mention that in most cases you win if **you** kill someone, not if someone loses, which is not the case on a RTS game.

To sum it up, the only con I would give it is that it's not worth spending time on a mechanic like that, as the final game won't be that different that a 2-team one.

# Answer
> 0 votes
> What are the cons of implementing a 3 team multiplayer FPS game?

Well, apart from the other answers: What are the benefits?

As opposed to RTS, where you have a global strategy you can follow, in FPS you don't really have that much strategy, you see an enemy, you shoot, and a wounded teammate to help.

It doesn't really matter whether there is one enemy team or two. The only benefits are: more targets to shoot at and enemys can be distracted from your team (which is a huge con if you are the distracted one)

**But there is a 3 faction FPS: Planetside 2**. (and 1 but that's been shut down)

However, it is an MMOFPS, not a pure FPS. And that explains why you don't see 3 teams in regular FPS: because it's bad.

Coming from a Platoon leader standpoint there (meaning that I actually command 40 people on a 900+ player continent: The three-way fights (which are those where all 3 factions have significant population) are the worst. They might be fun for farming (=racking up cheap kills) as an experienced player but for getting any objectives (capturing bases) and for newer players they are hell.

The only reason the 3 factions work in that game, is that these 3 way fights are the exception rather than the norm. You have a giant map with over 800 players and usually 20 vs 20 (well from 1 on 1 to 96+ on both sides) fights between two factions on one base.

The 3-Faction-part is only relevant for the metagame that the platoon leaders play/ think about, but that is nothing else than RTS with your units being individual actual humans. Here it's important to have 3 sides: to prevent / limit imbalances, but again, that is metagame and thereby RTS territory, no direct gameplay impact for the FPS player.

On smaller single-map games the downsides would be even worse. Objectives become almost uncaptureable and you get killed from random places, because EVERYWHERE can be where an enemy is. Sounds like an incredibly frustrating experience.

---
Tags: game-design, game-mechanics
---


# Question
Title: How to name HP/MP/Exp bars in a single word?
I have one question related to game design.

In my prototype game, I have an options when you can change look of your HPbar, MPbar and Expbar. Actually I don't know how to easily name this option.

Currently have "player HP/MP/Exp bars - Value", but it doesn't look so great.

I am looking for a simple name for this, so I want to provide more understandable naming for player.

# Answer
In game design terms, HP, MP, and XP are all "resources" so we could call them "Resource Bars" collectively.

If that's too abstract/designer-y, we could also try "Points Bars" since it encompasses hit *Points*, magic *Points*, and experience *Points*

Of the three, "Health Bar" is probably the most familiar to players, so "Health & Other Bars" would give players a concrete example of what the setting affects.
> 3 votes

# Answer
I very much disagree you'd refer to these as "resource bars" or "points bars" the first is ambiguous and the second I'm not sure is proper English. The term I've *literally* heard and used to describe these concepts is ***Status Bars***. they display your ***status***. Wikipedia agrees with me https://en.wikipedia.org/wiki/Status\_bar and if you look up "status bar game" you will find it is used in *exactly* the way you describe ie in aion online
> 1 votes

# Answer
It's often called the HUD or Heads Up Display. Though that encapsulates everything "cluttering" the edges of the screen in normal gameplay.

However a HUD design is very much tied to the identity of your game. Allowing too much customization can dilute how recognizable screenshots will be. In many cases it's better to settle on the single design.
> 0 votes

---
Tags: terminology, user-interface
---


title: What makes a good tech tree?

text:
# Question
Title: What makes a good tech tree?
In strategy/simulation games there are often tech/research trees which allow players research new abilities/options, improve existing options and decease negative effects.

Some games seem to follow the abc approach of `item 1 -> item 2 -> item 3` with minor stat changes while others make every unlocked option wildly change the way a game is played by throwing new units into the game which are able to change the balance of the game. Some make unlocking one branch block off another for the rest of the game while other will let you research everything. Some let you research multiple things while others will penalize you for switching research before it is complete. On that note tech trees can be progressive (with dedicated research over time unlocking an item) while some need you to collect enough money/points in order to unlock instantly.

**What are some general guidelines for when to employ what strategy in a game?** What games types of games would benefit more from one tech tree type over another and why? When should a linear tech tree be employed over a branching one?

**Edit**

For example a game where the main character has to build up an organisation and research technologies in secret while others are finding them and shut them down resulting in lost research laboratories, which reduce research output. The research output should increase somewhat exponentially as the game goes on as better technology is unlocked and research laboratories are upgraded. There would presumably be a very large tech tree to explore and the constant danger of losing facilities to other parties until you either unlock some endgame tech or lose everything.

**Why this isn't a duplicate**

Some people are marking this question as a duplicate because there is a related question about tech tree size. This question has to do more with the connections, cost and relationships between the technology options (of which size is a factor but not everything).

# Answer
Sid Meier has said that "games are a series of interesting decisions". This definitely applies to tech trees. In a typical strategy game, at any moment the player is faced with a decision among very different choices: economy (train workers), military (train soldiers), or tech. Tech is often the most interesting because of the uncertain and distant payoff; by spending resources on tech research, you are spending something that could have been used for the cumulative payoff of economy (extra income for the rest of the game), or the immediate security of military.

A decision is interesting when there's a limited number of unique-yet-viable choices. Too few or too alike and the choice becomes uninteresting. Too many and the player falls into decision paralysis. If some choices are obviously superior than others, they are uninteresting to veterans but will trap and frustrate newbies.

Another factor to consider is that hardcore players and genres can tolerate more choices. Turn-based, 4X games are notorious for the bewildering amount of choices. Contrast this to choices in faster-paced games like ARPGs.

There's an excellent analysis of tech trees in RTS games here, which uses the term **core choice** for such choices. Likewise you want to avoid **newbie traps**, choices which are hazardous for newbies because they lead to strategies that are difficult to play.

Let's look at the classic Starcraft Terran build tree (which is also a form of tech tree). Terrans have three military production buildings:

```
Barracks (weak yet versatile units)
   |
 (allows)
   |
Factory (strong yet specialised units)
   |
 (allows)
   |
Starport (very specialised units)

```

Initially you can only build Barracks. Only once you have at least one Barracks, can you build a Factory, and only then can you build a Starport.

Why didn't they flatten that tree, and allow the player to build a Starport off-the-bat? Apart from artificially delaying the appearance of air units (which are tougher to counter), it's difficult to use air units. For their cost, they tend to be weak, but are great at specialised roles like exploration and harassment. They are a poor choice for attacking strong points, or defending an attack. This makes them a **newbie trap**; while a veteran player will know when to use air units, if a newbie went straight for air units, they can easily lose them in a fight against more cost-efficient ground units. This comes at a cost to veteran players, who could enjoy more variety if they could play air units from the early game.

This tech tree is also a way of opening up more choices as the game progresses through stages. In the early game, you want fewer choices and a more predictable match-up. The mid-game contains more interesting choices but few decisive ones, as you want players to recover from poor choices and enter the late-game, where the truly devastating, game-ending strategies are made.

So I encourage you to look at your strategy game as a graph of choices, among the stages of the game. Your tech tree will fit somewhere into this graph.

* **Flat (or no) tree vs deep tree**: trees are used to present interesting choices and eliminate newbie traps. Consider your target audience's expertise level, the stage of the game, and the number of interesting choices. Hardcore strategy games have more choices. Early stages have less choices than late stages. Your tree should present the desired structure.
* **Exclusive branches vs all options available**: consider that even if all tech options are available, there is still a cost to choosing one or the other first, in terms of resource or time. Making branches exclusive reduces the number of choices; keeping all options available makes it possible for players to change strategies mid-game. Again, consider how many choices you want to expose to players at every stage and pick the right structure.
* **Global, permanent research / per-unit upgrades / collecting map items etc.**: this very much depends on the style of gameplay you want. Tech that can be undone, such as tech buildings, leads to base building and defense being an important gameplay factor. Gaining tech via map exploration encourages that and discourages turtling. Per-unit upgrades is better for smaller, long-lived squads than massed armies.
> 8 votes

# Answer
Following Sid Meyer's "important decisions" again, some tech trees suck. And it's those with either low-impact research or with the result being flat stat boosts or so. (as well as highly granular trees most of the times) The decisions feel weightless and are therefore boring.

Excluding trees on the other hand are nice, because not only do you choose a reward, but you also forfeit ever researching that other thing. (This however comes at the cost of being harder to balance or leaving only few actually viable paths)

Leaving few viable parts is another hot topic. If your tree is huge and meaningful, but if "not choosing A,B,F,T as the first 4 research blocks" means you loose the game, the tree is really really bad (this is more balance than tree design tho)

Also important is the research being tied to the lore/world. Making something researcheable which according to the world is already common knowledge (or should be) just for the sake of having more options usually breaks the immersion. This also goes for illogical research dependencies. \[It does depend on your game how relevant this point is though\]

Another thing is: most good research trees I encountered were important. Not in that the decisions were meaningful, but that the research itself was part of the core gameplay, and for example while "not going for research at all" was a viable strategy in Supreme Commander (I or II don't remember), it was only as an all-in rush strategy, which meant that you were actively not engaging with research (which is another way of engaging with it imo). On the contrary, the most annoying tech trees were the ones that just felt tacked on later. If most research rewards could also be given in another way (items, level-ups, milestones etc.) or feel like they should have been in the game to begin with, consider not having one, or stripping it down.

Most of these things don't really comply to the example you gave, but I fell they still matter to most other people
> 0 votes

# Answer
In addition to the other answers, i wanted to talk about the relevance of the 'match time' on the choice of tech tree and the option of 'stopping progress' in a tech tree.

As congusbongus said, even a build order can represent a sort of tech tree. This has special attributes, as you can 'delete' progress, but also 'save' it. Building A needs Building B first, if B s destroyed, you wont be able to build A anymore. To circumvent this, it is possible to build severals Building Bs, so if one gets destroyed you still got the option for Building A.

This would be roughly equivalent to your example of a opposing player 'shutting down' a research center. If you got another building with the same research, nothing is lost. If the opposing player doesnt know that, he might feel save and wont persuit more actions in this way.

So, depending on what kind of game your playing, you might want to have research that is stored somewhere with the possible option of redundancy. This would cost extra resouces but if you go for the late game anyway, this could be a good strategy. This would be most likely in some sort of action based RTS with shorter tech tress, as losing core and maybe even global technologies would cause a big problem for game design. Imagine a Civ game, where everyone is in the industrial age with first tanks and cars, and suddenly some race losses the knowledge of the wheel, cause the building which hosts "THE WHEEL", the prototype of the wheel of this gets destroyed. But loosing the radar dish so you can't build planes anymore makes sense (sort of).

the other factor sit, that RTS dont force you to advance, as any kind of research is connected to some sort of cost, while in this cases the cost of 'time' is constant. Back to the Starcraft example, you can decide when to build the next building to advance the build order, when to research the weapon upgrade etc. Everytime you do that, its an active decision, and while it not always seems awesome to have that sort of choice, you activly decided to to that. But you have to option to spend your resources on something else, like more troops. In Command & Conquere Generals you collected Experience, to let you progress into a tech tree. You decided what to pick with your points and when to pick them. Maybe you saved your points to pick a tank upgrade to defend against stealth, but then your enemy focused on defense, so upon realising this, you could pick the stealth bomber instead.

In games with a longer time frame (mostly turn based) like 4X games, they hint you to research something, cause your last research completed. Some games wont even go on until you choose another research. Most of these games only allow to research one thing at a time, cause research is a type of game progression, not just power progression. In Civ, researching archery over science means, you will be behind in research for the rest of the game if not for some lucky incident or natural bias (race with better science gain or better starting position). In these games researching doesnt cost anything, but the 'production' of knowlegde costs resources. While your people produce a static amount of science, you can build schools, universities etc. whiche cost money. In these cases, having a tech tree means to have maintenance costs. Something you wouldnt have in most RTS.
> 0 votes

---
Tags: game-design, balance
---


# Question
Title: Why does the head of my ragdoll act like its about to fly off its shoulders?
The problem can be seen here: https://gfycat.com/LimpingMerryGermanshorthairedpointer

Ive created my ragdolls by using the Unity ragdoll creator tool.

To begin with, all the limbs of my ragdoll acted like this, then I searched online, found this post: https://forum.unity.com/threads/how-can-i-prevent-ragdolls-from-stretching-and-spazzing-out.328348/ and enabled projections as advised.

This fixed all limbs but the head.. How do I fix this?

Thanks

# Answer
I managed to fix this. The problem was with the collider on the ragdoll head. For some reason it was automatically set to a radius of 0.004, this making it extremely small. I manually increased its size so that it properly covered the head, and this fixed my problem :)
> 1 votes

---
Tags: unity, 3d, models
---


title: Stealing system RAM for texture cache

text:
# Question
Title: Stealing system RAM for texture cache
As an example, the N64 has a notorious 4kb texture cache. Could someone sap another 4kb (or more) from the system's RAM or the Expansion Pak and use that as texture cache space? If so, would it be worth it to do it?

# Answer
Since the texture cache was dedicated hardware, read directly by similarly dedicated rendering hardware, you couldn't just point the renderer hardware elsewhere or relocate the cache.

You *could* stream larger texture data from the cartridge memory into the cache in 4k chunks (2k if using mipmapping), however, and that's generally what later-generation games tended to do.
> 2 votes

---
Tags: textures, console, nintendo
---


# Question
Title: SQL Server Question: How to go about using a collection of cards
So basically I'm new to SQL Servers and for that matter generally to Server Logic and Server behavior. (Used to only work on single player games) OK, so my questions is as followed. Lets take Hearthstone for example every user has a card collection. Now if using an SQL server, I can create tables for the users, I can also create tables for the cards, but how do I combine those? To be more specific my solution would have been to make a new table where the playerid and the cardid is stored with the value of how many of the certain card the player has.

However, my issue with this solution is that, if we assume we have 1000 players and we have like 500 cards then the table will be clustered with entries of same playerid's who have different cards.

Basically my question is: Is there a better solution for this and if not what is the capacity of SQL tables/Servers, like when can i expect a drop off during loading the collection of a player who has all 500 cards for example?

Since I'm new to SQL I might also be having a wrong idea on how to solve this issue, so if there is another solution or I'm missing something I would appreciate if someone pointed me in the right direction.

# Answer
> 2 votes
Your hunch is reasonable: you'd create a third table, a `CardOwnership` table or some such, that has (at least) columns for player ID and card ID. You'd probably use a clustered index on the player ID for this table.

While capacity and performance measurements are tricky in a vacuum, it's quite unlikely you'll see any sort of performance issue with only 1,000 players having up to 500 cards. Those are pretty small numbers in the grand scheme of things and you'd likely be fine even if you chose really poor indexes and wrote relatively suboptimal queries to access them.

---

That said, don't fall into the trap of thinking that your SQL database has to be your backend. In general, you may want to use a database as a long-term storage mechanism but for actual gameplay, you'd probably want an actual server *program* (written in whatever language you're familiar with) running to arbitrate and validate play sessions. The server would have its own, in-memory data structure for representing the card collection of a player that you eventually persist to a database.

You don't even strictly speaking *need* a database for this; you could just as easily archive the player information to disk after a game using basic file I/O.

---
Tags: c#, mysql
---


# Question
Title: Noise when using SSLR (Screen Space Local Reflections)
When I tried to apply reflections to my scene, I ran into the problem of noise:

My fragment shader code:

```
#version 330 core

uniform sampler2D normalMap; // in view space
uniform sampler2D depthMap; // in view space
uniform sampler2D colorMap;
uniform sampler2D reflectionStrengthMap;
uniform mat4 projection;
uniform mat4 inv_projection;

in vec2 texCoord;

layout (location = 0) out vec4 fragColor;

vec3 calcViewPosition(in vec2 texCoord) {
    // Combine UV & depth into XY & Z (NDC)
    vec3 rawPosition = vec3(texCoord, texture(depthMap, texCoord).r);

    // Convert from (0, 1) range to (-1, 1)
    vec4 ScreenSpacePosition = vec4(rawPosition * 2 - 1, 1);

    // Undo Perspective transformation to bring into view space
    vec4 ViewPosition = inv_projection * ScreenSpacePosition;

    // Perform perspective divide and return
    return ViewPosition.xyz / ViewPosition.w;
}

vec2 rayCast(vec3 dir, inout vec3 hitCoord, out float dDepth) {
    dir *= 0.3f;

    for (int i = 0; i < 20; i++) {
        hitCoord += dir;

        vec4 projectedCoord = projection * vec4(hitCoord, 1.0);
        projectedCoord.xy /= projectedCoord.w;
        projectedCoord.xy = projectedCoord.xy * 0.5 + 0.5;

        float depth = calcViewPosition(projectedCoord.xy).z;
        dDepth = hitCoord.z - depth;

        if(dDepth < 0.0) return projectedCoord.xy;
    }

    return vec2(-1.0f);
}

void main() {
    vec3 normal = texture(normalMap, texCoord).xyz * 2.0 - 1.0;
    float depth = texture(depthMap, texCoord).r;
    vec3 screenPos = 2.0 * vec3(texCoord, depth) - 1.0;
    vec3 viewPos = calcViewPosition(texCoord);

    // Reflection vector
    vec3 reflected = normalize(reflect(normalize(viewPos), normalize(normal)));

    // Ray cast
    vec3 hitPos = viewPos;
    float dDepth;
    float minRayStep = 0.1f;
    vec2 coords = rayCast(reflected * max(minRayStep, -viewPos.z), hitPos, dDepth);
    if (coords != vec2(-1.0)) fragColor = mix(texture(colorMap, texCoord), texture(colorMap, coords), texture(reflectionStrengthMap, texCoord).r);
    else fragColor = texture(colorMap, texCoord);
}

```

Normal map:

Reflection strength map (only red chanel):

# Answer
> 1 votes
There is usually no magic solution, you will get noise when doing SSR, to avoid it and get better results, you will need to cast multiple rays and interpolate between the different values you get.

Doing that will also allow you to apply different roughness values to your reflections, so they can become more or less blurry.

---
Tags: opengl, glsl, raycasting, post-processing
---


# Question
Title: Is it possible to do 2d character movement with vectors instead of using tiles
we have a character moving through a house and so far we used tiles to simulate character movement. Is it possible to use a vector image of the character and move the points via vectors to simulate movement.

We programm in java.

Thanks in advance

# Answer
> 0 votes
Animating vector images is definitely possible, and it's how flash used to work with. How to do that? Well, you haven't revealed a lot of details about how you work, so it's hard to give the best option, so here are two of them I can think of:

* **Using animation software**: There are programs with which you can animate images and export them for use, one I've heard of is DragonBones. Ideally you'd have your graphics designer to work with it, and export the characters in such a format to use in your game. Unfortunately I'm not sure how that can be done with Java.
* **Programmatically**: If for whatever reason, this is a project to learn, you can also design a small animation engine yourself. This can be very simple like "Object moves from A to B", to something more complicated like supporting rotation, scale and more.

It's difficult to go into more details without going off-topic, however this should answer your question: **Yes**, it **is** possible to do vector-based animations.

In a way, all 3D graphics are essentially vector-based, which can prove that potentially you can do a lot of things with vector-based animations.

---
Tags: java, 2d, character
---


# Question
Title: Know any 3D game makers that work on chromebooks?
Ok so I make flash games using a website named scratch.mit.edu, and it used to be a downloadable program in 2013. They have had 3 major updates to the site since 2013. Understand that this site is for people ages 8 and up. It teaches you a type of flash coding with blocks. Like IF, Space key pressed, Wait 20 seconds, then change sprite 2's costume to #3. I'm not sure if any of that is a good enough base for actual coding. There are people, more professional, who have managed to use it too make 3D imaging and animations on the site and it's really amazing but I have no idea how to do that or if I want too based on the amount of lag.

So I have two questions:

One, what is the best way to learn coding without college. (preferably free)

Two, are there any 3D game creators that don't need coding experience and can actually work using a Samsung Chromebook?

I know i'm not a professional but I couldn't find the amatuer game developer site, if you could direct me there that would be great.

# Answer
> There are people, more professional, who have managed to use it too make 3D imaging and animations on the site and it's really amazing but I have no idea how to do that or if I want too based on the amount of lag.

In theory, on any machine that you are allowed to display graphics, you can also display 3D graphics. Of course that means that if there are no tools/libraries to do the math for you, you'd have to do it yourself, which is **not** recommended for someone new to programming. Also if the software you are using does not support 3D graphics, you can still display them, but it will most likely not take advantage of the system's GPU, which means performance would be terrible.

Having said that, I've never used scratch.mit.edu, but from what I remember it doesn't support 3D graphics, although I could be wrong.

> One, what is the best way to learn coding without college. (preferably free)

Well, the question to that always is, start programming, pick a language, pick a tool/library for making games, and start coding. You don't have to make the next big hit to learn, start by making a broken game, understand the concepts of it, and how everything should work. You could for example try Python, using the Pygame library, which is mean for making games.

One could also argue that you can use a graphical engine, like Unity, which can take care some of the coding for you, until you are more comfortable with it.

> Two, are there any 3D game creators that don't need coding experience and can actually work using a Samsung Chromebook?

Unfortunately I've never owned a Chromebook, but I've heard it supports android apps, so maybe you can find something in the App Store? I've tried some apps in the past like AIDE, which is used for android development, but I've only used it for testing, never for an actual release of an app. Although that was meant for android development with Java, not the best choice for a new person.

There are plenty of tutorials online, if you search on google something like "LANG tutorials" replacing "LANG" with the language of your choice, you can get plenty of free resources. From that point, it's like a musical instrument, the more you use it, the more sense it makes. Once you feel comfortable enough, you can move to the next step.
> 0 votes

---
Tags: flash-develop
---


# Question
Title: Why is EditorGUI.PropertyField with a custom PropertyDrawer resetting values inside OnGUI of another PropertyDrawer?
I made a `PropertyDrawer` for a simple class, which looks something like this:

```
public class Limiter {
    public enum LimitType { None = 0, Range = 1, Vector = 2 }
    public LimitType limit;
    public Range range; //details of 'Range' are not really relevant.
    [VectorPicker] public Vector2 vector;

    /* other stuff */
}

```

```
[CustomPropertyDrawer(typeof(Limiter))]
LimiterProperty : PropertyDrawer {
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {

        /* other stuff */

        if(/* main property is expanded */) {
            SerializedProperty _limit = property.FindPropertyRelative("limit");
            position = AddProperty(position, _limit); //moves the rectangle into position for this property
            EditorGUI.PropertyField(position, _limit, new GUIContent("Type of limiter on the position."));

            if(_posLim.enumValueIndex == 1) {
                SerializedProperty _range = property.FindPropertyRelative("range");
                position = AddProperty(position, _range);
                EditorGUI.PropertyField(position, _range, new GUIContent("Range"), true);
            }

            if(_posLim.enumValueIndex == 2) {
                SerializedProperty _posVector = property.FindPropertyRelative("vector");
                position = AddProperty(position, _posVector);
                Debug.Log("Before: " + _posLim.enumValueIndex);
                EditorGUI.PropertyField(position, _posVector, new GUIContent("Position Vector"));
                Debug.Log("After: " + _posLim.enumValueIndex);
            }

            /* other stuff */

        }
    }
}

```

See the `Debug.Log("Before" + enum);` and `Debug.Log("After" + enum);`? This is what they print when I *change* the enumerator to "Vector".

It immediately changes back. If it was on "Vector" already, then it can be changed to "None" or "Range" just fine, but can't be changed back. There are also no problems switching between "None" and "Range".

Here's the `VectorPicker`:

```
[CustomPropertyDrawer(typeof(VectorPickerAttribute))]
public class VectorPickerDrawer : PropertyDrawer {
    #region Variables
    bool _trackMouse;
    SerializedProperty _property;
    MonoBehaviour script;

    ///<summary>Keep the currently selected object to avoid loosing focus while/after tracking</summary>
    GameObject _mySelection;

    ///<summary>For reverting if tracking canceled</summary>
    Vector2 _originalPosition;

    ///<summary>Flag for doing Setup only once</summary>
    bool _setup;

    /// <summary>Mouse position from scene view into the world.</summary>
    Vector2 worldPoint;
    #endregion

    /// <summary>
    /// Catch a click event while over the SceneView
    /// </summary>
    /// <param name="sceneView">The current scene view => might not work anymore with multiple SceneViews</param>
    private void UpdateSceneView(SceneView sceneView) {

        Camera cam = SceneView.lastActiveSceneView.camera;
        worldPoint = Event.current.mousePosition;
        worldPoint.y = Screen.height - worldPoint.y - 36.0f; // ??? Why that offset?!
        worldPoint = cam.ScreenToWorldPoint(worldPoint);

        VectorPickerAttribute vectorPicker = attribute as VectorPickerAttribute;
        if(script != null && vectorPicker.relative) worldPoint -= (Vector2)script.transform.position;

        // get current event
        var e = Event.current;

        // Only check while tracking
        if(_trackMouse) {
            if((e.type == EventType.MouseDown || e.type == EventType.MouseUp) && e.button == 0) {
                OnTrackingEnds(false, e);
            }
            else {
                // Prevent losing focus
                Selection.activeGameObject = _mySelection;
            }
        }
        else {
            // Skip if event is Layout or Repaint
            if(e.type == EventType.Layout || e.type == EventType.Repaint) return;

            // Prevent Propagation
            Event.current.Use();
            Event.current = null;

            // Unlock Inspector
            ActiveEditorTracker.sharedTracker.isLocked = false;

            // Prevent losing focus
            Selection.activeGameObject = _mySelection;

            // Remove SceneView callback
            SceneView.onSceneGUIDelegate -= UpdateSceneView;

        }
    }

    /// <summary>
    /// Called when ending Tracking
    /// </summary>
    /// <param name="revert">flag whether to revert to previous value or not</param>
    /// <param name="e">event that caused the ending</param>
    /// <returns>Returns the vector value of the property that we are modifying.</returns>
    private Vector2 OnTrackingEnds(bool revert, Event e) {
        e.Use();
        Event.current = null;
        //Debug.Log("Vector Picker finished");

        if(revert) {
            // restore previous value
            _property.vector2Value = _originalPosition;
            //Debug.Log("Reverted");
        }

        // disable tracking
        _trackMouse = false;

        // Apply changes
        _property.serializedObject.ApplyModifiedProperties();

        return _property.vector2Value;
    }

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
        script = (MonoBehaviour)property.serializedObject.targetObject;

        if(property.propertyType != SerializedPropertyType.Vector2) {
            EditorGUI.HelpBox(position, "This Attribute requires Vector2", MessageType.Error);
            return;
        }

        var e = Event.current;

        if(!_setup) {
            // store the selected Object (should be the one with this drawer active)
            _mySelection = Selection.activeGameObject;
            _property = property;

            _setup = true;
        }

        // load current value into serialized properties
        _property.serializedObject.Update();

        //specific to the ONE property we are updating
        bool trackingThis = _trackMouse && property.propertyPath == _property.propertyPath;

        GUI.enabled = !trackingThis;
        EditorGUI.PropertyField(position, property, label);
        GUI.enabled = true;

        // Write manually changed values to the serialized fields
        _property.serializedObject.ApplyModifiedProperties();

        if(!trackingThis) {
            var button = new Rect(position) {
                x = position.width - 2,
                width = position.height
            };

            // if button wasn't pressed do nothing
            if(!GUI.Button(button, "")) return;

            // store current value in case of revert
            _originalPosition = _property.vector2Value;

            // enable tracking
            _property = property;
            _trackMouse = true;

            // Lock the inspector so we cannot lose focus
            ActiveEditorTracker.sharedTracker.isLocked = true;

            // Prevent event propagation
            e.Use();

            //Debug.Log("Vector Picker started");
            return;
        }

        // <<< This section is only reached if we are in tracking mode >>>

        // Overwrite the onSceneGUIDelegate with a callback for the SceneView
        SceneView.onSceneGUIDelegate = UpdateSceneView;

        // Set to world position
        _property.vector2Value = worldPoint;

        // Track position until either Mouse button 0 (to confirm) or Escape (to cancel) is clicked
        var mouseUpDown = (e.type == EventType.MouseUp || e.type == EventType.MouseDown) && e.button == 0;
        if(mouseUpDown) {
            // End the tracking, don't revert
            property.vector2Value = OnTrackingEnds(false, e);
        }
        else if(e.type == EventType.KeyUp && _trackMouse && e.keyCode == KeyCode.Escape) {
            // Cancel tracking via Escape => revert value
            property.vector2Value = OnTrackingEnds(true, e);
        }

        property.serializedObject.ApplyModifiedProperties();

        //This fixes "randomly stops updating for no reason".
        EditorUtility.SetDirty(property.serializedObject.targetObject);
    }
}

```

When I remove `VectorPicker` from `Limiter`, it works fine. I have no idea what could be causing this.

# Answer
> 1 votes
I was able to fix it. Turns out it was this stuff that was causing it:

```
_property.serializedObject.Update();
_property.serializedObject.ApplyModifiedProperties();

```

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


# Question
Title: Object pooling of different tpyes of agents (Mobile Game) in Unity
The mobile game I am developing consists of one to four players and different agents that are being spawned and act in their own way. All those Agents (Car, Animal and Powerup) derive from the same base class 'Agent' which in turn has a field called 'rank' which represents something like 'low', 'medium' and 'high'. So an agent with rank 'high' will look and behave different than one being tagged 'low'.

The thing is - the 'rank' of the agent is determined at random. The max count of agents active simultaneously is known but this number is not in regard to their 'rank'. When objectpooling, this would lead to the follwing case:

There's a max agent count of, say, 6. This would require 6 instances of each agent with rank 'low' to 'high' to be created, altough some of those instances would never even be used.

So my idea was to create only 6 gameobjects holding the components that each agent requires and use reflection to set the components fields according to the type. The problem is that some compoents which are unique to rank and type would need to be added and removed at runtime.

What solution would be better in terms of runtime and memory performance?

# Answer
Object pools should be used when you constantly create and destroy a large number of *very similar* objects. When retrieving and reinitializing an object from the pool requires some costly operations, like adding and removing components and performing reflection calls, then you are defeating the whole purpose of object pools.

So if you have 3 different types of objects you want to pool, then create a separate object pool for each type of agent.

A compromise would be to work with one pool, but to add the whole set of components to each agent. Instead of destroying and adding the components, you just enable and disable them. Performance-wise, enabling and disabling is far cheaper than adding or removing.

However, reading between the lines of your question, i get a bit sceptical if object pools are actually useful to you in the first place. You say you only have 6 simultaneous objects in the game. How many of these objects get destroyed and reinitialized per second? Object pooling is useful when you have a large number of short-lived game objects (like bullets in a shoot-em-up, for example). When you have few game objects and they usually live for several seconds, then object pooling is unlikely to really do much for you.
> 1 votes

---
Tags: unity, performance, object-pools
---