# Question
Title: Unity procedural skybox shader texture stretching
I am using the procedural skybox shader that Unity provides, but have tweaked it so that I can have a cloud texture.

The problem I have, is that the texture is not tiling correctly, even though it is a repeatable pattern.

In the GIF below you will see the stretching, but it tiles everywhere else.

Here is the test cloud texture I am using.

Am not doing anything unusual in the shader I don't think.

```
// In the vertex (copied this from another shader, could this be the problem?)
OUT.uv = TRANSFORM_TEX(v.uv, _Sky_Clouds);

// in the fragment before returning the color

c = c + tex2D(_Sky_Clouds, IN.uv);

```

How can I use the cloud texture so it tiles around the whole skybox without stretching?

The look I am trying to achieve is like this...

That image is from this video tutorial by BlenderGuru.

https://www.youtube.com/watch?v=9Q8PwcDzb8Y&t=1046s

# Answer
I know it's been a while since the question emerged, but because I'm now trying to do something similar with procedural skybox shader, I just wanted to share what I've found. The trick is that the uv's coming from the skybox aren't actual uv's. They are running in the \[-1:1\] range and have a third component (w or z, or whatever), and to me it seems more likely that they are the normals of a sphere, encompassing the world. You can use them to map the skybox as a sphere, but have to transform them into \[0:1\] range values, and there still will be distortion errors at the top end bottom of the sphere, unless you use a latlong map, which already has a distortion at the poles, suitable for spherical mapping. For the v coordinate it should be easy - just remap the range:

```
float v = i.uv.y*.5+.5;

```

For the u it's a bit trickier, since it wraps around twice, so you should check on what side of the z axis are you and do some magic there:

```
// Remap to [0 : .5]
float u = i.uv.x*.25 + .25;
// Check the side of the z axis, invert and compress to [.5:1] range
if (i.uv.z < 0) u = (1-u*2)*.5+.5;

```

Hope that helps to someone.
> 0 votes

---
Tags: unity, shaders, textures, skybox
---


# Question
Title: How can I find the reflection of a point in a perpendicular line?
From the image below I know the positions `A` and `B`. How can I find positions `C` and `D` and the reflection (`Er`) of an object `E` in the line `CD`? I saw the solution in How can I reflect a point about a line in Unity? but I don't understand it enough to apply it in my case. Please note that I'm trying to achieve this in 2D.

# Answer
I'm not familiar with unity, but here's an answer in GLSL-like pseudocode.

```
vec2 a = ..., b = ..., e = ...;
vec2 center = (a + b) / 2; // the intersection of the two lines
vec2 n = a - center; // mirror normal
vec2 c = center + vec2(n.y, -n.x); // here I assume that the length of the mirror is
vec2 d = center + vec2(-n.y, n.x); //   equal to the distance between A and B
n = normalize(n);
float l = dot(n, e - center); // distance between CD and E
vec2 er = e - 2*l*n;

```
> 0 votes

---
Tags: geometry
---


# Question
Title: Unity3d - Cast dynamic shadows without processing multiple lights
**Back Story**

I've built a game with a friend and all goes well until there are too many spheres under a group of 5 lights, then things start getting choppy.

**Troubleshooting**

I've found that by turning off all of these lights but one the game runs smoothly, the problem is that the shadows are not realistic at all. Because of the 4 main lights, the objects should have four main shadows.

**My Ideas**

I wanted to use a "projector" but that is too static for multiple & random appearing / disappearing objects. I might be able to do a projector per sphere but I'm hoping there is an easier way as this would require a lot of work to get just right.

**Question**

How can I get 4 lights to cast a raycast shadow on a group of dynamically moving spheres (100 of them) without processing the light portion?

# Answer
> 0 votes
We got rid of the four extra lights and instead attached projectors to the items. The projectors shoot black, circular png shapes onto the ground. It took a bit to soften up the shadows / lock rotation etc but it came out nicely and we saved the performance that we needed to.

---
Tags: unity, performance, lighting, shadows
---


title: How to fit rectangles in a page?

text:
# Question
Title: How to fit rectangles in a page?
Here's my problem: I need to fit rectangles in a polygon but in "certain way".
I have few rectangular shapes (of different sizes) and I need to put them on a polygon.

My first idea was to always try to put them on the top right of the previously placed shape, and if it is not possible, on the bottom left angle of the previously placed shape. It works but it does not looks great, since it does not take into account the placement of the previously placed shape (sometimes the last placed shape is not the most logical).

From this, I imagine we could have a kind of "navmesh": when a shape is placed, it says that nothing more can be placed here and that it needs to find a better place.

Here is how it should look:

Imagine I have the above case, and I want to add one rectangular shape... it shoud go like this:

... with enough space to welcome a new rectangular shape that could possible fit on the blank space.

So... what I want is to place my shapes on the far top and then on the far left.

Do you guys have any ideas how to do this? Maybe this kind of algorithm already exists and I don't know the name?

Thanks !

# Answer
> 1 votes
Depending on your use case, *Texture Packing* (to build Texture Atlas) may be relevant for you. This wiki Article has a section "Explanations and algorithms" with a link to a PDF "A thousand ways to pack the bin"

---
Tags: mathematics
---


# Question
Title: Is there a "Least Terrible Method" for sharing Entities over Network?
*(Preface: Using C++, Box2D, and built UDP client and server classes that are reasonable efficient for a built-from-scratch game using client-server model.)*

This question is specifically in regards to an MMORPG (WoW, Rift, Maplestory) / ARPG (Diablo, Path of Exile, etc) setup. My conundrum is this: **How to efficiently share only what the client needs to know, without running the server (performance) into the floor?**

To elaborate, I have narrowed down to three separate approaches, but all of them feel horrifyingly inefficient and "iteration-spammy". I will detail each below as succintly as I can, though (hopefully) with enough actionable information. My concern is keeping the CPU time as short as possible as a physical server may be running 20+ zones (or "level", if that makes more sense). I will not be sending full data each time, more of full data "as needed" (ex: id, health, x/y/z, velocity), then changes as they occur (ex: \[id, x/y/z\], \[id, new health\], \[id, velocity\]).

To keep things consistent, I will give the following example "setup" that will be referenced with each approach.

* Map size is 20 'units' by 6 'units'
* Players / NPCS are 0.5 'units' squared.
* Sight Range: 1.5 'units' from player center, in a circle.
* Number of Players: 3
* Number of NPCs: 10

---

**Approach A: Entity-based Checking**

This consists of the server either iterating over all NPCs from each player's perspective (or all players from each NPC's perspective). This would look something like "for each player, loop through npcs and check if within n "units" of player. Once player's iteration is done, create and send payload to said player before next player's iteration" (where 'n' = sight range). This is fine in principle, until there are 10-20 players and 100+ NPCs. That ends up with 1,000+ iterations occurring each round (1-3 rounds per second). Again, not horrible by iteself, but 20+ zones could make this exceptionally slow and ruining the player experience.

**Approach B: Tile-based Checking**

By the use of tiles of size 'n' squared (again, 'n' = sight range), divide up the map. With the example map size, let's say it becomes 10 nearly perfectly fitting tiles. For this, the server would maintain the data per tile, then send concatenated entity data (e.g. vector) of tiles which the player is inside and adjacent tiles. This does have the advantage of breaking up the into much more managable areas, though it feels like maintaining the location checking for these tiles may become just as tedious as Approach A in that each 'round' (again, 1-3 rounds per second) the bounds checking will need to be performed against each entity multiplied by the number of tiles; 10 tiles x (10 NPCs + 3 Players) = 130 possible iterations.

**Approach C: Lazy Physics-based Checking**

I believe this is either the least terrible or the absolute most terrible (with no middle ground), though I cannot definitively prove which side of the fence it is standing. This would consist of creating an invisible circle around the player equal to their sight range as a radius. This has the advantage of using the Box2D collision detection and 'sensor' functionality to lazily determine what is and is not in range. Though, given what I've seen from working with Box2D, this is likely similar to simply iterating over the Entities themselves. The obvious con would be the requirement to either maintain a list of 'visible' entities or simply rebuild it each 'round'.

---

If you made it this far, you are a scholar and a saint. I appreciate any feedback, insight, or constructive criticism.

Again, in all seriousness and sincerity, thank you for reading!

# Answer
*Preface: I'm not familiar with Box2D, but these structures can be found in Boost Geometry (R-trees) if you are really interested, as well as other libraries:*

# Premature Optimization (Don't Do it)

Premature optimization leads to longer development times with no benefit, but many people consider micro optimizations to be the only cause of premature optimization when in reality it applies to more than that. Even higher level optimization can be time consuming and equally fruitless.

Do the easiest thing you can implement first, if it actually ends up being a bottleneck *then optimize*. For your test numbers, I doubt even the slowest solution you've suggested will matter in the slightest.

That being said, if you do actually find performance issues with any naive solution you've chosen...

# Spatial datastructures

Instead of iterating for all entities for each player, use **spatial hashing** or other **spatial data-structures** that should already be used for broad phased collision detection.

This can be:

plus any extras I've missed.

With these methods, you should be able to retrieve the list of enemies mostly in range of sight (use final check to make sure that they are actually in range before sending) in times between O(log(N)\*N) to O(N), much faster than your O(N^2) suggestions. The issue will be updating these structures upon both players and entities moving. You will have to figure out for yourself which of these structures will be better for your use case (you could probably also come back here and ask as well). Some will work better with static entities some will work better for moving, and you may be able to utilize box2d's broad phase collider.

You are essentially colliding a bounding volume (box or circle) of the players vision with the bounding volumes of the other entities, if it intersects then you send that information to that client.
> 3 votes

---
Tags: c++, networking, box2d, entity-system, client-server
---


# Question
Title: How can I create a slope/hillsde tileset?
I struggle to create a 2D slope/hillside for a tileset. Not an impassable mountainside like in Pokemon, more a gentle slope which you can walk both directions. When you see the tilemap, one should get a feeling that the two sides of the slope have a different heigth.

Ideas and suggestions are welcome.

# Answer
> 2 votes
Sloped terrain is hard to do in a convincing way in an orthogonal 2d tilemap. But here is an example from the 1993 SNES game *Illusion of Gaia* by *Enix* which does a quite decent attempt:

This ramp uses 3 tiles:

What techniques are at use here?

* The diagonal cliff tiles provide a perspective hint
* The floor texture is darker than the one used for level ground. This creates a 3d illusion through shading. You could also use a brighter texture instead on the ramp in the opposite direction.
* Not visible on this screenshot, but the game mechanics also sell the ramp: When the player moves horizontally while on the ramp, it gets interpreted as diagonal movement. You can also increase the movement speed when moving downhill and decrease it when moving uphill.

Here is a more sophisticated example from a game with more technologically advanced pixel art. The original 1998 *Starcraft* by *Blizzard*:

This slope is more detailed and it isn't tileable. But in the end it uses the exact same techniques: Diagonal rock formations and the shading of the floor texture (in this case lighter) create an illusion of perspective.

And by the way, you should not steal these tiles. Both companies still exist.

---
Tags: 2d, tilemap, tiles, pixel-art, tilesets
---


# Question
Title: Unity3D HTC Vive graphical bug when making builds
Recently I noticed that my builds seem to have a weird graphical bug. This only occurs when I play a build. Running the game in VR in unity play mode doesn't show this bug.

I am not sure what is causing this or what it is even called. I do remember in the old days windows having a similar bug where you could draw on your screen basically by dragging an interface. I have an older build where this glitch didn't occur and checked the settings I had then and now and nothing changed.

Developing in VR is still fairly new to me so if it is anything basic I might not be aware of it.

My Unity version is 2017.2.0f3 with the latest SteamVR version using the HTC Vive, which has been running on the same version as when the bug didn't occur.

This link is a video of the bug occurring during the play mode in a build (in the menu the bug didn't occur strangely enough).

This link is a video of it being run in play mode. This is what I would expect in a build as well.

Just watching the first few seconds of both videos is plenty to understand the issue I am experiencing.

Thanks in advance.

Edit: I have discovered that this issue is called ghosting. I hope this helps anyone.

# Answer
> 0 votes
Alright I am not exactly sure what fixed it, but after figuring out it was called "ghosting" I did some research on other projects and people experiencing the issue in combination with Unity and VR.

First I updated my nVidia drivers for my graphics card... didn't seem to solve the ghosting. After that I decided to look at the assets.

I completely removed the SteamVR asset and redownloaded it from the store. Then I imported the CameraRig prefab (as I am using it) and tweaked some settings to suit my needs. After that I ran a test build and the ghosting bug was gone. So I added my own components to the CameraRig and still no ghosting.

I tested this in various builds with different settings (even with single pass rendering) but the ghosting issue is gone. Currently I am flabbergasted since this bug came out of nowhere and disappeared into thin air.

If anyone in the future experiences the same, redownloading the asset seems to fix it somehow.

And if someone is able to enlighten me a bit more about this I'd be grateful.

---
Tags: unity, virtual-reality, bug, htc-vive, steam-vr
---


# Question
Title: How can you allow a sphere to rotate 360 degrees inside a hollow cylinder in Unity?
I have a hollow cylinder, within which is a sphere. The forward vector is predefined, so the user can not change their forward speed. What they do have control of, however, is the rotation of the sphere around the cylinder by swiping the screen.

Again, I want this rotational movement to occur while the ball is traveling on a forward vector.

Here is the code I have thus far in C#:

```
public float speed;

private Rigidbody rb;

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

void FixedUpdate()
{
    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = 1;

    print(moveVertical);

    Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

    rb.AddForce(movement * speed);
}

```

The current controls are for the left and right arrow keys, but I will implement swiping later.

I would appreciate any help you could provide. Thank you.

# Answer
> 1 votes
If you want to do it purely from a mathematical point of view (so it works outside Unity too) you can use this:

```
x = sin(rot) *rad;
y = cos(rot) *rad;

```

This assumes that `rot` is the rotation of the sphere inside the pipe. This should be in radians, so to convert from 90 degrees do something like `rot = 90 *Math.PI /180`.

It also assumes that the sphere's `z` axis is the one moving "forward", which is unaffected.

This lets you have complete control over the sphere, you can for example reduce `rad` if you pan to make the sphere "jump" (approach the center) or increase/decrease it in case you plan to make the pipe bigger/smaller while the sphere is still inside.

---
Tags: unity, c#, rotation, movement, transformation
---


# Question
Title: How to Make Character Shoot Where Aiming with Mouse
I've looked around and none of the stuff I've found seem to help me. Here's my code so far. Right now it just shoots to the right (on purpose). Now how do I adjust my code to make the bullet go where I'm pointing with the mouse?

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

 public class PlayerShooting : MonoBehaviour {

 public GameObject projectilePrefab;
 private List<GameObject> Projectiles = new List<GameObject>();
 private float projectileVelocity;

 // Use this for initialization
 void Start () {
     projectileVelocity = 10;
 }

 // Update is called once per frame
 void Update () {
     Shoot();
 }

 void Shoot()
 {
     if (Input.GetButtonDown("Fire1"))
     {
         GameObject bullet = (GameObject)Instantiate(projectilePrefab, transform.position, Quaternion.identity);
         Projectiles.Add(bullet);
     }

     for (int i = 0; i < Projectiles.Count; i++)
     {
         GameObject goBullet = Projectiles[i];
         if (goBullet != null)
         {
             goBullet.transform.Translate(new Vector3(1, 0) * Time.deltaTime * projectileVelocity);

             Vector3 bulletScreenPos = Camera.main.WorldToScreenPoint(goBullet.transform.position);
             if (bulletScreenPos.y >= Screen.height || bulletScreenPos.y <= 0)
             {
                 Destroy(goBullet);
                 Projectiles.Remove(goBullet);
             }
         }
     }
 }

```

}

# Answer
So there is multiple ways to go about this and none are correct or incorrect they just depend on how you want your game to function.

For example one method that makes sense for a bullet (It's not a heat seeking missile, it's fired from the gun and its momentum carries it in direction its facing) so I would create a script called Bullet for example :

**Method One**

```
using UnityEngine;

public class Bullet : MonoBehaviour
{
    public float Speed = 2.0f; //set your speed variable as a public float and
    //you can adjust it from the inspector

    //Any Monobehaviour (Script you put on a GameObject) has this method
    //and it's called every frame
    void Update()
    {
       //for very simple movement since this is a bullet and they move
       //towards the bullets forward direction
       //(transform.forward * timesinceLastFrame * SpeeD)
        transform.position += transform.forward * Time.deltaTime * Speed;
    }

}

```

Now if you attach the script to your bullet prefab whenever you spawn the Bullet Prefab in PlayerShooting the script we attached will move it forward in the direction of its facing.

**Method Two**

But this wouldn't make sense for a heat seeking missile since they are given a target and track it's movement changing it's own direction so it stays on target.

You would need to calculate a Vector3 which has X, Y, Z co-ordinates for representing *something* in world space, everything that is in a scene in unity has a Transform Component which holds it's position.

```
using UnityEngine;

public class Missile : MonoBehaviour
{
    public float Speed = 2.0f;

    private GameObject target;

    void Update()
    {
        //if there is a target set
        if (this.target)
        {
           //use our MoveTowards function to move to the targets position
            //which we get from its transform component
            MoveTowards(target.transform);
        }
    }

    public void SetTarget(GameObject _target)
    {
        this.target = _target;
    }

    void MoveTowards(Transform target)
    {
        //to calculate a heading towards our target we can
        //subtract the current objects position (transform)
        //from the targets position and that gives us a heading
        Vector3 vectorToTarget = target.position - transform.position;
        transform.position += vectorToTarget * Time.deltaTime * Speed;
    }
}

```

This is the same deal as before you add this script to your Missile Prefab but when we spawn it on left click in PlayerShooting we also want to set the Missiles target so it knows who to fly at we can do this using the SetTarget() public method and a RayCast.

I also tidied up your PlayerShooting a little.

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

public class PlayerShooting : MonoBehaviour
{
    public GameObject projectilePrefab;
    //you can set the default value for variable when you declare it, if you
    //set it public you can edit it in the inspector, which is handy for
    //tweaking behaviour
    public float projectileVelocity = 10f;
    //added a float variable so you can set the max distance
    //the target can be from the mouse
    public float maxRange = 50f;

    private List<GameObject> Projectiles = new List<GameObject>();

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        Shoot();
    }

    void Shoot()
    {
        if (Input.GetButtonDown("Fire1"))
        {

            //create a ray cast, which is quite honestly the same as how you would expect a laser pointer to work, you point it at something
            //in this case the mouse position translated to a world position
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            //if our ray cast hit anything
            if (Physics.Raycast(ray, out hit, maxRange))
            {

                Debug.Log("We hit " + hit.collider.gameObject.name);
                GameObject target = hit.collider.gameObject;
                //ok we have a target create the projectile,
                GameObject projectile = (GameObject)Instantiate(projectilePrefab, transform.position, Quaternion.identity);
                //set its target
                projectile.GetComponent<Missile>().SetTarget(target);

                //add it to your list
                Projectiles.Add(projectile);
            }

        }
    }
}

```
> 0 votes

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


# Question
Title: Difference between integral and accumulator?
I'm trying to build a bouncing-ball effect, and a newbie to calculus things...

For the ball-drop, it's straightforward - since there's no initial velocity and acceleration is constant.

For the bounce-up, it seems that what I want to do is *integrate* the velocity changes over time (since there's some transfer of energy upon impact, and that drives the ball upwards with a sortof fade-off as it fights against gravity?)

This leads me to some questions, one generic and one specific (with a more detailed followup):

1. Is this correct- that I need to use integration and not just a straight kinematic equation for the bounce-up?
2. I'm not quite sure about the difference between *integration* and *accumulation*. Ideally I would like to have a function `y = f(t)` where various other properties are known such as the initial velocity upon impact, but I do *not* want to *accumulate* anything every tick. I.e. it'd be nice to just have a pure function that pre-loads all the info it needs on impact, and then can be run with any time as an input. Can someone please explain the difference between integration and accumulation in light of this?
3. A bit more specifically, it seems like maybe there are rules of integration that allow for solving at any `t` such as the "power rule", but then integrators like Euler/Verlet operate more like accumulators. This is confusing and speaks to the above point.

Thanks!

# Answer
> 1 votes
1) It's possible to use a kinematic equation for the bounce-up in the case of a perfectly elastic bounce -- just model the ball's motion as `y = max_height - ((t - t_start) % (2 * sqrt(max_height)) - sqrt(max_height)) ** 2`, for example.

2) Accumulation is a numeric approximation to integration. Any integral can be expressed as a series of sums of f(x) * dx where dx approaches 0. The standard game-engine accumulation pattern uses an appropriately small value of dx (the simulation timestep) to approximate the value of the integral.

Some Integrals (such as the integral of a constant-acceleration motion) can be expressed as a function that you can evaluate once at any time. Most motion in games cannot be easily expressed as a pure function since it has to deal with things like collisions, piece-wise interpolated animations, and user-controlled motion. This is why accumulating motion is more commonly seen, except in the case of things that never interact with anything else (e.g. things that just rotate in place, things that bounce without colliding with anything other than the ground).

3) Rules like the "power rule" are for symbolically integrating a function. Euler / Verlet are numerical methods to approximate the integral, similar to the Runge-Kutta method you may have learned in Calculus class.

---
Tags: physics, mathematics
---


# Question
Title: How can I calculate the angle and proper turn direction between two 2D vectors?
I am working on some movement AI where there are no obstacles and movement is restricted to the XY plane. I am calculating two vectors, **v**, the facing direction of ship 1, and **w**, the vector pointing from the position of ship 1 to ship 2.

I am then calculating the angle between these two vectors using the formula

```
arccos((v · w) / (|v| · |w|))

```

The problem I'm having is that `arccos` only returns values between 0° and 180°. This makes it impossible to determine whether I should turn left or right to face the other ship.

Is there a better way to do this?

# Answer
It's much faster to use a 2d cross-product. No costly trig function involved.

```
b2Vec2 target( ... );
b2Vec2 heading( ... );

float cross = b2Cross( target, heading );

if( cross == -0.0f )
   // turn around

if( cross == 0.0f )
  // already traveling the right direction

if( cross < 0.0f)
  // turn left

if( cross > 0.0f)
  // turn right

```

If you still need the actual angles I recommend using `atan2`. `atan2` will give you the absolute angle of any vector. To get the relative angle between any to vectors, calcuate their absolute angles and use simple subtraction.

```
b2Vec2 A(...);
b2Vec2 B(...);

float angle_A = std::atan2(A.y,A.x);
float angle_B = B.GetAngle(); // Box2D already figured this out for you.

float angle_from_A_to_B = angle_B-angle_A;
float angle_from_B_to_A = angle_A-angle_B;

```
> 23 votes

# Answer
Use arcsin of the 2D cross product (i.e the z component of the cross product vector). That'll give you -90 to 90 which will let you know whether to go left or right.

Be careful because A cross B is not the same as B cross A.

Another strategy (but probably not as straight forward) is to calculate the "heading" of the two vectors using atan2 and then figuring out whether A pointing at X degrees needs to go left or right to go to B pointing at y degrees.
> 11 votes

# Answer
Use *vectors* to redirect the ship. This is how "steering behaviors" work -- you never need to calculate the angle, just use the vectors you have. This is computationally much cheaper.

The vector `w` (vector from Ship 1 to Ship 2) is all the information you need. Modify either ship 1's velocity vector or ship 1's acceleration vector (or even the heading vector directly) using a weighted version of `w`.

The *magnitude* of how far off ship 1 is off course (how badly v does not match up with w) can be found by using ( `1 - dot(v,w)` )

* (`dot(v,w)` is maximized when `v` and `w` line up exactly)
* (`1 - dot(v,w)`) gives 0 when `v` and `w` are completely lined up, provided `v` and `w` are normalized)
> 2 votes

# Answer
There is a simple way to find the absolute angle of a vector through normal geometry.

for example vector V = 2i - 3j;

absolute value of x coefficient = 2;

absolute value of y coefficient = 3;

angle = atan( 2 / 3 ); \[ angle will be in between 0 to 90 \]

Based on quadrant angle will be changed.

if ( x coefficient \< 0 and y coefficient \> 0 ) then angle = 180-angle;

if ( x coefficient \< 0 and y coefficient \< 0 ) then angle = 180+angle;

if ( x coefficient \> 0 and y coefficient \< 0 ) then angle = 360-angle;

if ( x coefficient \> 0 and y coefficient \> 0 ) then angle = angle;

after finding angle of first and second vectors, just subtract first vector angle from second vector. Then you will get absolute angle between two vectors.
> 0 votes

# Answer
Maybe I should post a slightly different question and answer it myself; this is the closest question I could find to the one I had.

I'm doing 2D work in the html canvas, where I have rotation angles in radians rather than vectors. I needed the "turn angle" (ta) to get from "current heading" (h) to the "target heading" (t).

Here's my solution:

```
var ta = t - h,
    ata = Math.abs(ta)
;
if (ta > Math.PI) ta = (ta / ata) * (Math.PI - ata)
return ta;

```
> 0 votes

---
Tags: 2d, vector
---


title: Unity can't add script component

text:
# Question
Title: Unity can't add script component
I keep getting the following error when i try to drag and drop a script to my gameobject:

I have made sure that both my Script name and the class name is : `Soldier` as you can see:

```
public class Soldier : MonoBehaviour
{
    public int Rank;
}

```

So my question is what have i done wrong?

# Answer
1. Fix compiler error.
2. Make sure you have "using UnityEngine;" in your namespace.
3. make sure you have the same names for classname and filename

I assume your file has a big "I" instead of a small "L" or a special character.

to check it paste both, the Filename here and then the Class name here:

https://www.textmagic.com/free-tools/unicode-detector

Compare for special characters. (red)

i != í for example

You might have accidently pushed ´ or \` something before pushing the i button, resulting in a different class name than file name.

To make it 100% sure copy and paste the classname to the filename.
> 2 votes

---
Tags: unity
---


# Question
Title: When is an intro too long for game logos?
After doing some searching and finding no answers, I decided it would be okay to ask here.

In indie or big company games, when they show their logo or have an animation for that company logo, what is the average display time for it and how often do they have themes or sounds with that splash screen?

# Answer
> 3 votes
I think I speak for all gamers when I say we'd rather there just not be a splash screen. From the moment that I click the executable, I'm waiting to start playing, so shorter is clearly better than later. Instant satisfaction is a very real factor for a player's opinion on a game. That said, a splash screen is necessary for branding.

I would say no more than 3 seconds, no less than 1 second. I've seen a few longer than 3 seconds, but they were animated and skippable. I've also seen some that kind of flashed on the screen for a quarter of a second, and that makes the game look a bit unfinished.

# Answer
> 2 votes
Generally, in my experience, game splash screens are generally 3-10 seconds. You have to remember that the more collaborators there are on a game, the more the user will have to sit through the introduction, so plan accordingly. In my opinion as a gamer the best splash screens are the shortest splash screens.

Just try to use common sense with this. If you can sit through it throughout the entire edit process, the user can sit through it once per gaming session.

EDIT: Seeing @comet-cloud's answer, it's also better if the user can skip it.

---
Tags: splash-screen
---


title: Popupwindow size and position [Unity]

text:
# Question
Title: Popupwindow size and position [Unity]
I am working through the popwindow sample code provided in the documentation here. So far my code opens up an instance of PopupExample when user clicks on a sprite. But I am unable to understand how PopupExample's position and size is being determined. The line below from the sample code, is setting the activator rect of PopupExample to buttonRect. And buttonRect is initialized to default values, which should be x=0f; y=0f; width=0f; height=0f.

```
PopupWindow.Show(buttonRect, popup);

```

When I run the code and click on the sprite, the popupwindow shows up on the upper-left corner of the IDE(screenshot below). I was expecting it show up somewhere within the scene itself. Why is it not contained within the scene? Also how can a widow with width and height initialized to 0f be visible at all?

# Answer
> 0 votes
Essentially you are using the wrong kind of Window script.

The `EditorWindow` is an internal UI Window used as an empty template provided by Unity so programmers can design interfaces for designers and artists to tweak settings in the inspector (Much like you do with GameObjects and their components but for custom components) the EditorWindow itself is all over Unity.

The `console` Window is an EditorWindow, as is, `Hierarchy`, `Inspector Panel` etc.

The reason you don't set the `EditorWindow`'s x, y, wdith, height is because they are managed by Unity itself, you can resize, move, place the place panel where you want and Unity saves its settings.

What you need to do is click `Create` in the scene Hierarchy and then scroll down to `Panel` under `UI` and add it to the scene, this gives you an empty window, you can then add UI components to this panel, such as text, buttons, images etc by adding them as children of the panel you created.

That way whenever you want to hide the entire panel you can disable the Panel GameObject and re-enable whenever you want it shown it's children (images, buttons, text will disable with it since they are children of it)

If you are still confused I can provide further help.

---
Tags: unity
---


# Question
Title: How do I use Unity's TargetRPC calls? Trying to send data from the server to a client
I want to send a large amount of data to only one player, as it would be wasteful to do this for every player when only one player needs the data. After a bit of research, it appears that TargetRPC is the thing that I want to use. Unfortunately, TargetRPC was only introduced semi-recently in Unity 5.4, and I have not been able to find a guide on how to use it properly.

Here is a barebones version of my attempt so far:

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

public class TargetRpcTest : NetworkBehaviour {

    private List<NetworkConnection> finishedConnections = new List<NetworkConnection>();

    void Start () {
        // We don't want to send data to ourselves.
        finishedConnections.AddRange(NetworkServer.connections);
    }

    void Update () {

        // If we're not the server, we don't have any business in sending data to players.
        if (!isServer) {
            return;
        }

        // Do the code contained below for everyone we haven't done it for yet.
        foreach (NetworkConnection connection in NetworkServer.connections) {
            if (!finishedConnections.Contains (connection)) {

                TargetSendStuff (connection);
                finishedConnections.Add (connection);
            }
        }
    }

    [TargetRpc]
    public void TargetSendStuff (NetworkConnection connection) {
        print ("I've just received a target RPC call!");
    }

}

```

This code is all I could come up with, and it does compile properly. No errors are thrown on the server side, either. However, when a client connects to the server, Unity throws this error:

```
Could not find target object with netId:5 for RPC call ClientRpc:InvokeRpcTargetSendStuff
UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate()

```

The `5` in `netId:5` varies depending on which object I apply this script to. All objects I attach this script to are required to have NetworkIdentity component because of NetworkBehavior. I have tried applying this script to static scene objects as well as the players themselves, but for some reason UNet still can't seem to find the target objects.

Also, I don't really need the TargetRPC call to apply to any particular object. The code within will do only operations to other objects, and even create new ones based on the sent data. All I need is some way that I can send data to specific clients.

# Answer
Based on this code i'm assuming that you want the data to be sent from player to player?

```
    // If we're not the server, we don't have any business in sending data to players.
    if (!isServer) {
        return;
    }

```

Which isn't the correct use of \[TargetRpc\]. If you look at the Unity documentation it says

> This is an attribute that can be put on methods of NetworkBehaviour classes to allow them to be invoked on clients from a server. Unlike the ClientRpc attribute, these functions are invoked on one individual target client, not all of the ready clients.

So what a \[TargetRpc\] does is the same as \[ClientRpc\] except it ***only*** sends it to the client specified in NetworkConnection parameter. Basically you still need to send the data from the Server -\> Client.

If you want to send Client -\> Client data (i'm not sure the best way but staying in the context of this question) you would need to have a \[Command\] that would be supplied with what player you want to send the data to and then (from the server) specify that target/send the data using the \[TargetRpc\]
> 1 votes

# Answer
It is probably an issue of timing. The error message is telling you that the object to which the `TargetRpcTest` script is attached exists on the server, but not on the client. On the frame upon which the connection is established, Unity has not yet spawned all the objects on the clientside, since it needs to send messages over the network to do that.

Just to confirm that this is the issue, you could try delaying your RPC call by some frames, and see if that fixes the issue. Of course, that isn't so robust; a better way would be to put, in the `OnClientStart` of `TargetRpcTest`, a `Command` which triggers the `ClientRpc`. But then that's two network calls.

There is yet another way. You say you don't need a specific object to receive the call; `NetworkMessages` can achieve this, and you shouldn't have any timing issues.
> 1 votes

---
Tags: unity, c#, networking, unity-networking, unet
---


# Question
Title: Will using OpenGL for rendering with SDL make my 2D game run smoother?
I've been working on a 2D game using SDL. I've noticed the objects look blurry and glitchy when they're moving, so I was thinking about using OpenGL to render the graphics. Would this help? What are the pros and cons of using OpenGL for a 2D game?

# Answer
If you're having slowdowns and glitches with SDL software rendering *in a 2D game*, chances are very slim that OpenGL is going to do anything for you. SDL can run 2D games quickly on a Pentium II or even lower spec machine. In other words, there are problems inherent to how you are making your draw calls. I've had no problems with speed in SDL rendering, and I've written a pure scanline renderer, which is far more intensive than working with sprites.

Two approaches I suggest:

* Pull out bits of your rendering code, methodically, until you see a speed increase. If you pull out one section and see a drastic speed increase, then pull out smaller pieces within that code section (where possible). If you pull out all of your rendering code (i.e. it's rendering nothing), and it's still slow, then you have problems with your game loop timing. In that case, see Fix Your Timestep.
* Profile your code. If you are running under Linux, you can happily take advantage of the Valgrind suite of profiling and debugging tools. If you're under Windoze with MinGW or Cygwin, and you really want to profile, you can run your app with gdb and interrupt it, to manually take stack samples (leading you to see in which functions most of your time is being spent) -- see this for more info. This is because gprof, the profiler that comes with gcc/g++, is not very good... at least for real-time games it's next to useless.
> 8 votes

# Answer
SDL uses OpenGL for its rendering, they just wrap there code in methods / free functions, so using "OpenGL" vs SDL will give you ultimately the same result, the only difference being that using OpenGL directly will give you more control over your rendering, sometimes this can be helpful as many older libraries use older OpenGL functions for rendering instead of newer standards e.g. ( a older library might use glBegin and glEnd instead of glDrawArrys or glDrawElements ), so in theory i would say yes, using OpenGL directly might improve performance, but in reality i highly doubt its the SDL rendering pipeline getting too much overhead and more possibly the way you are iterating over object in your scene, especially if you aren't optimizing your use of matrices depending on how many object you have in a scene at a time,

I hope this helps see, sorry this answer is so late (=
> 0 votes

---
Tags: opengl, rendering, sdl
---


# Question
Title: How can I keep a consistent number of players per match in a continuous multiplayer game?
Fortnite Battle Royale is an example of a non-continuous multiplayer game. 100 players join a game which has fixed start and end times. When there's only one player remaining, the game ends.

Agar.io is an example of what I like to call a continuous multiplayer game. Players join in and die out, but the game goes on forever.

How would a game developer design a system to split players into different groups when there're too many online to fit in a single game? Let's say a game has a limit of 10 players, and 50 players are trying to join. The server will split them up into 5 separate groups. New players will be sorted evenly into these groups to replace players who died. When the player count increases past the global limit, new games will be created to fit them. The problem arises when the player count decreases. The system needs some way to seamlessly delete extra groups of players that are no longer needed. How can that be done without A) interrupting games to merge players together or B) block new players from joining into the group(s) that require deletion and waiting for everyone in it to die (which will be a bad experience for the last few players).

Agar.io obviously has a player population management system that works, so how do they do it?

# Answer
> 1 votes
**Merge the Games**

If i understand it correctly, you have 5 different games with max 10 Players. Problem: you don't have enough players to refill every match.

Possibloe solution: merge the games slowly. Show the Players from the other game ghostelike for 10-20 seconds. Maybe with a warning on the screen, that the games get merged. So everyone can see the other players for a moment, before they get merged in and shot directly.

How does your game handling spawning of new players? This maybe could also done this way. So there would be no difference in new players joining, or merging two matches.

How could the server manage Players? Make a lobby for waiting players. If there are (n/2)+1 players, where n is the max size of a game, create a new one. If the number of players drops below n/2 in two matches merge them.

Problem: People like playing with friends. If you assign everything automatically this won't be possile. You could let them say, who they want to play with, but that really depends on the type of game.

# Answer
> 2 votes
**Team Auto-balance:** A good way to balance the teams is making players change teams mid-game. This would need to be handled with care, as it would be very annoying for a player to keep changing teams, only to end up losing because in the last match they were moved to the losing team, but they are the player with the best score. (not true in continuous games)

**Team-up:** Don't forget that when you have a game with multiple teams, the teams consist of actual humans, which means if there are 5 teams in the game, and one team is dominating everyone else, most likely all other teams will start attacking that one team, to bring balance. Yes, this is up to the players, and not really in your control, but isn't that true for most multiplayer games anyway?

**Weak players have different skills:** What I like in agar.io is also that when you become strong, you start moving slower, and new players move fast. Although most likely the strong player can get them, the new players have a chance to avoid being killed, so they don't feel that underpowered. So a nice idea would be "weak players have skills focused on escaping, and as they grown stronger, they focus on being more powerful".

# Answer
> -1 votes
Give the enemy team advantages.

I thought about Bf1 in this case.

The losing team will get a bonus - e.g. an airship that could (if used correctly) give the losing team the advantage to even out with the opponents.

---
Tags: multiplayer, server, web, online
---


# Question
Title: What is the most efficient way to render a 2D scene objects?
What is the most efficient way to render scene objects according to the current position of the camera (which will follow the player position)?

A friend told me that since processors are powerful these days, it is okay to set up everything virtually and then just update the surface according to what is inside the camera position, after a loop inside the sprites filtering only what should be rendered by the GPU.

But seems to me that this is taking more processing power from the CPU. Why process objects that aren’t visible by the player? What if I need to target mobile devices? What if I want to make my game available in a raspberry pi or very old computers?

# Answer
I think the key point in your question is this:

> After a loop inside the sprites filtering only what should be rendered by the GPU.

A naive implementation would be

```
foreach(sprite in spriteList)
{
    if(IsInsideViewPort(sprite))
    {
        RenderSprite(sprite);
    }
}

```

While computers are extremely fast. If this lists gets huge it **might** start to become a problem. But I do not expect a problem until you have tens of thousands of sprites.

However, we can do much better than this naive approach.

**Spatial Partitioning**

Lets divide our world into cells in a grid. Every cell has a list of sprites that it overlaps with (a sprite can be overlapped by multiple cells, cells can overlap with multiple sprites). When we want to know what sprites should be rendered by the GPU we calculate what cells the camera can see. For each of those cells we take the sprites it overlaps with. These are the sprites we wish to draw.

The hard part is to keep the list of sprites inside a cell up-to-date. But we only have to do this when a sprite moves, and usually most of your sprites don't move :).

There are many techniques for spatial partitioning. A grid is the simplest form, but there are also hierarchical systems, like a k-d tree, and binary space partitioning.
> 1 votes

---
Tags: 2d, camera
---


title: Fixed timestep without physics?

text:
# Question
Title: Fixed timestep without physics?
I read Gaffer's Fix Your Timestep article many years ago, and have since had the impression that game code should have a fixed timestep, with only non-gameplay related tasks outside of that in the main loop.

However, I recently reread the article, along with several others, and realized the emphasis is on physics. Which makes sense, but now I'm wondering if it **only** applies to physics.

What about games which don't use a real physics simulation? People talk about 60fps games, doesn't that imply a fixed timestep? What about multiplayer where you have regular updates to and from the server?

The only alternative I know of is variable rate with time delta, but that sounds like it wouldn't be any better, and less exact. What method is typically used?

# Answer
> 1 votes
It definitely also applies to game logic.

Computers are imprecise, so weird things can happen if you just let the update loop go as fast as it can.

For example, the goal of a game is to produce as much points as possible. Player **A** has a slow computer and runs at 1 update per second. Player **B** has a faster computer at runs at 10 updates per second

Both players start the same game and create one factory. One factory produces one 'score' per second. For player A the computation is easy. The game updates one per second, and adds one item to the list every update

For player two its also easy. The game updates ten times per second, so adds 1/10th of a score to the list. So how much points will both players have after one second?

```
playerAscore = 1.0
playerBscore = 1.0000001

```

Eh... wait what!? Turns out that 32bit floating point numbers can't exactly represent 0.1. The nearest number it can represent is 0.100000001490116119384765625. Updating ten times actually adds a bit more of an error, because the intermediate steps are also not represented exactly. So the end result is 1.0000001.

Now what if we had a win condition. This sounds reasonable, right?

```
if(playerBscore > playerAScore)
{
    print("player B wins!");
}

```

Seems unfair, right?

Ok, so we require someone to have a full point more to win. Fixed? Oh now the problem only occurs after 16 weeks. Nobody plays that long right? Except every factory that produces a point you add makes it worse.

So we're now using extremely costly exact numbers, like big decimal. It can't go wrong anymore now right? Let's do a quick check. What are the scores of the players after 1.5 seconds?

```
playerAscore = 1.0
playerBscore = 1.5

```

Whoa!! player B is winning by a margin of 50%... Why? Because player A hasn't updated yet. What would happen if we checked the win condition after 1.5 seconds? :).

Now this is only silly example. But imagine the myriad of problems you have to fix, when you allow variable update rates.

Please note, that you have these floating point imprecision problems all the times. But normally we don't really care. They are too small for us to notice (most of the time). But when you start comparing stuff, its when things go wrong.

Real world examples: see in this video how a high fps leads to more gravity in Quake 3 :) https://www.youtube.com/watch?v=MbznZbuWcpY

Other fun floating point precision bugs: you could drive slightly faster on lap 1, 3, 5,.. than on lap 2, 4, 6... in this race game: https://www.iracing.com/q-circles-the-crop-circles-of-iracing/

---
Tags: physics, timestep
---


# Question
Title: How can I change the rotatearound radius in real time when the game is running?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TargetBehaviour : MonoBehaviour
{
    // Add this script to Cube(2)
    [Header("Add your turret")]
    public GameObject Turret;//to get the position in worldspace to which this gameObject will rotate around.

    [Header("The axis by which it will rotate around")]
    public Vector3 axis;//by which axis it will rotate. x,y or z.

    [Header("Angle covered per update")]
    public float angle; //or the speed of rotation.

    public float upperLimit, lowerLimit, delay;// upperLimit & lowerLimit: heighest & lowest height;
    private float height, prevHeight, time;//height:height it is trying to reach(randomly generated); prevHeight:stores last value of height;delay in radomness;

    [Range(0, 50)]
    public float xradius = 5;
    [Range(0, 50)]
    public float yradius = 5;

    private void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //Gets the position of your 'Turret' and rotates this gameObject around it by the 'axis' provided at speed 'angle' in degrees per update
        transform.RotateAround(Turret.transform.position, axis.normalized, angle);
        time += Time.deltaTime;
        //Sets value of 'height' randomly within 'upperLimit' & 'lowerLimit' after delay
        if (time > delay)
        {
            prevHeight = height;
            height = Random.Range(lowerLimit, upperLimit);
            time = 0;
        }
        //Mathf.Lerp changes height from 'prevHeight' to 'height' gradually (smooth transition)
        transform.position = new Vector3(transform.position.x, Mathf.Lerp(prevHeight, height, time), transform.position.z);
    }
}

```

Using the xradius and yradius sliders I want to change the transform.RotateAround radius in real time.

UPDATE:

I added this to the Update:

```
if (radius > 0)
        {
            var newPos = (transform.position - Turret.transform.position).normalized * radius;
            newPos += Turret.transform.position;
            transform.position = newPos;
        }

```

The problem is now that some times when the radius the distance from the Turret is small for example 20 or less some times the transform is getting right above the turret not sure why. I want it to rotate around the turret at the fixed set distance(radius) but not to be above the turret. Can't figure out why sometimes it's moving right above the turret then after some time it's getting back to the set distance.

# Answer
> 1 votes
You could have an `UpdateRotation()` function where you take the vector between the center object and the orbiting object, normalize it, and then find the proper location for the orbiting object by applying the changeable distance that you want on the fly. The problem is, the orbiting gameobject will just kind of snap between locations. If that's what you want, roll with that. Alternatively, you could have a coroutine run to gradually change the distance variable over time to give the game a bit of flow. A third option is implementing the `Mathf.Lerp()` function somehow, but off the top of my head I can't articulate how you would do that similarly to what I've already described. However, its likely going to be the cleanest option.

I'd look into vectors, normalization and distance formulas to get a solid grasp of how to handle this.

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


# Question
Title: Game Over not appearing in third room (GameMaker Studio 2 Trial)
This is my first StackExchange post, so forgive me if I make a silly mistake.

Getting to the point, I've made a simple Mario-esque platformer where whenever you die, game over text is printed to the middle of wherever you are on the screen. Dying is an Instance Destroy event triggered by various objects, while the Draw GUI event is triggered by a separate object placed in each room.

The third and final "level" room is where text doesn't appear no matter where you die. I've made multiple attempts to fix this, but nothing appears. I believe part of it involves the room's layout; the other levels were simple "go to the right" styled rooms. The third room goes vertically and is much taller.

The issue also likely involves the camera. I'm using `viewport[0]`. Room properties are as follows:

* Room settings - Width: 3000, Height: 3000
* Clear Viewport Background: ON
* Camera - X Pos: 0, Y Pos: 2250, Width: 1080, Height: 768
* Viewport - X Pos: 0, Y Pos: 0, Width: 1080, Height: 768
* Following object: `obj_playercube` (player object) (Hor. border: 400, Vert. border: 400, Hor. speed: 200, Vert. speed: 200)

This is the code for `obj_gameover`'s Draw GUI event:

```
draw_set_font(fnt_dead);
draw_set_halign(fa_center);
draw_set_valign(fa_middle);
draw_set_color(c_white);

// (x, y) coordinates of the center of the view

var center_x = view_xview[0] + view_wview[0]/2;

var center_y = view_yview[0] + view_hview[0]/2;

if (!instance_exists(obj_playercube))

{

    draw_text(center_x, center_y, "Game Over\n Press Enter to restart from current room.");
    show_debug_message("Game over has printed");

}

```

I'm sure it's a matter of adding more variables to account for the room's differing properties compared to the others. I'll try to figure it out myself in the meantime.

# Answer
Hi and welcome to Gamedev Stack Exchange!

Both of your variables `center_x` and `othercenter_x` are always equal so there is no reason to have two of them. The formula looks correct to me and should be working fine in any given scenario.

Debugging is an iterative process. Let's assume that, since we believe the formula is correct, something else is failing which prevents us from seeing the message. You'll have to go through each step to find out which exact one is misbehaving.

Since the third room is the only one where it doesn't work, maybe the object isn't placed there? Try printing your debugging message to make sure that the player's death does in fact trigger the event and the debug message appears. Maybe the positioning is wrong? Print all the variables involved (or better yet, use the debugger and access them directly) and see if their values are what you expect.

If the bug persists, please post your findings here so we can help. At this point there simply isn't enough information to make an accurate guess of what goes wrong here.
> 0 votes

---
Tags: game-maker
---


# Question
Title: 2D top down 360 degrees rotational movement - stop instant rotation
I currently have a working, decently complicated, way of moving my player around.

Using A & D you rotate the player and using W and D you increase forward or backward moving speed.

This works great!

I now want to update my code so that while rotating, the player will not instantly start moving in that direction, but it will start turning in that direction and after an adjustable "speed/time" start moving in that direction entirely.

So the player can rotate freely around without anything happening. But when facing a new direction, the player's speed should easy towards that direction until it is moving in the direction the player is facing. Currently this happens instantly.

An example of how I want my movement: https://www.youtube.com/watch?v=CwkVrxYZvEE

Here's my current code, I barelly understand how this works tbh. I do feel I'd just need a few minor tweaks to get this working?

Feel free to ask if you need any more info! Also feel free to use any of this code for your own purposes!

```
var canvas = document.getElementById('canvas');
var c = canvas.getContext('2d');

// Movement
var playerWidth = 64;
var playerHeight = 64;
var playerX = 500;
var playerY = 500;
var playerAngle = 1 * Math.PI / 180;
var rotationRate = 4 * Math.PI / 180;
var playerSpeed = 0;
var maxSpeed = 4;
var moveResistance = 0.04;
var speedRate = 0.05;
var speedUp = false;
var turnRight = false;
var speedDown = false;
var turnLeft = false;

// Images
var playerSprite1 = new Image();
playerSprite1.src = '/assets/sprites/spider-red.png';

// Game loop
setInterval(function() {
    c.clearRect(0, 0, canvas.width, canvas.height);
    calculatePosition();
    drawReDrawCanvas();
}, 1000 / 60);

function calculatePosition() {
    if (speedUp) {
        playerSpeed += speedRate;
        if (playerSpeed > maxSpeed) {
            playerSpeed = maxSpeed;
        }
    }
    else if (speedDown) {
        playerSpeed -= speedRate;
        if (playerSpeed < -maxSpeed) {
            playerSpeed = -maxSpeed;
        }
    }
    else {
        // Somehow the player keeps moving if speed is < 0.05
        if (Math.abs(playerSpeed) < 0.05) {
            playerSpeed = 0;
        }
        if (playerSpeed > 0) {
            playerSpeed -= moveResistance;
        }
        if (playerSpeed < 0) {
            playerSpeed += moveResistance;
        }
    }
    if (turnRight) {
        playerAngle += rotationRate;
    }
    if (turnLeft) {
        playerAngle -= rotationRate;
    }
}

function drawReDrawCanvas() {
    playerX += Math.sin(playerAngle) * playerSpeed;
    playerY -= Math.cos(playerAngle) * playerSpeed;
    c.save();
    c.translate(playerX, playerY);
    c.rotate(playerAngle);
    c.drawImage(playerSprite1, playerWidth / -2, playerHeight / -2);
    c.restore();
}

document.addEventListener('keydown', function(e) {
    var k = e.code;
    switch (k) {
        case 'KeyW':
            speedUp = true;
            speedDown = false;
            break;
        case 'KeyD':
            turnRight = true;
            turnLeft = false;
            break;
        case 'KeyS':
            speedDown = true;
            speedUp = false;
            break;
        case 'KeyA':
            turnLeft = true;
            turnRight = false;
            break;
    }
});

document.addEventListener('keyup', function(e) {
    var k = e.code;
    switch (k) {
        case 'KeyW':
            speedUp = false;
            break;
        case 'KeyD':
            turnRight = false;
            break;
        case 'KeyS':
            speedDown = false;
            break;
        case 'KeyA':
            turnLeft = false;
            break;
    }
});
```

```
<!doctype html>
<html>
<head>
    <title>Rotation</title>
</head>
<body>
    <canvas id="canvas"></canvas>

    <script type="text/javascript" src="player.js"></script>
</body>
</html>
```

# Answer
> 0 votes
Had a friend who's pretty good at math solve this with (for) me!

Here's the result:

```
var canvas = document.getElementById('canvas');
var c = canvas.getContext('2d');

// Movement
var playerWidth = 64;
var playerHeight = 64;
var playerX = 500;
var playerY = 500;
var playerAngle = -1 * Math.PI / 2;
var rotationRate = 4 * Math.PI / 180;
var playerSpeedX = 0;
var playerSpeedY = 0;
var maxSpeed = 4;
var moveResistance = 0.99;
var thrust = 0.1;
var speedUp = false;
var turnRight = false;
var speedDown = false;
var turnLeft = false;

// Images
var playerSprite1 = new Image();
playerSprite1.src = '/assets/sprites/spider-red.png';

// Game loop
setInterval(function() {
    c.clearRect(0, 0, canvas.width, canvas.height);
    drawMap();
    calculatePosition();
    drawReDrawCanvas();
}, 1000 / 60);

function calculatePosition() {
    var thrustX = thrust * Math.cos(playerAngle);
    var thrustY = thrust * Math.sin(playerAngle);
    if (speedUp) {
        playerSpeedX = playerSpeedX + thrustX;
        playerSpeedY = playerSpeedY + thrustY;
    }
    else if (speedDown) {
        playerSpeedX = playerSpeedX - thrustX;
        playerSpeedY = playerSpeedY - thrustY;
    }
    playerSpeedX = playerSpeedX * moveResistance;
    playerSpeedY = playerSpeedY * moveResistance;
    var speed = Math.sqrt(playerSpeedX * playerSpeedX + playerSpeedY * playerSpeedY);
    if (speed > maxSpeed) {
        playerSpeedX = playerSpeedX / (speed / maxSpeed);
        playerSpeedY = playerSpeedY / (speed / maxSpeed);
    }
    if (turnRight) {
        playerAngle += rotationRate;
    }
    if (turnLeft) {
        playerAngle -= rotationRate;
    }
}

function drawReDrawCanvas() {
    playerX += playerSpeedX;
    playerY += playerSpeedY;
    c.save();
    c.translate(playerX, playerY);
    c.rotate(playerAngle);
    c.drawImage(playerSprite1, playerWidth / -2, playerHeight / -2);
    c.restore();
}

document.addEventListener('keydown', function(e) {
    var k = e.code;
    switch (k) {
        case 'KeyW':
            speedUp = true;
            speedDown = false;
            break;
        case 'KeyD':
            turnRight = true;
            turnLeft = false;
            break;
        case 'KeyS':
            speedDown = true;
            speedUp = false;
            break;
        case 'KeyA':
            turnLeft = true;
            turnRight = false;
            break;
    }
});

document.addEventListener('keyup', function(e) {
    var k = e.code;
    switch (k) {
        case 'KeyW':
            speedUp = false;
            break;
        case 'KeyD':
            turnRight = false;
            break;
        case 'KeyS':
            speedDown = false;
            break;
        case 'KeyA':
            turnLeft = false;
            break;
    }
});
```

---
Tags: 2d, rotation, movement
---


title: Unity Hybrid ECS with "old way"

text:
# Question
Title: Unity Hybrid ECS with "old way"
Is it possible to use Hybrid ECS with some components and the standard `MonoBehaviour` with all your old code?

I want to know because I already have some game mechanics build with the "old" way and I want to build the new ones using hybrid

# Answer
It is perfectly possible to mix both styles. The same GameObject can have some of its functionality implemented with the new ECS system and other functionality in classic MonoBehaviour events.

What Unity recommends in their ECS tutorial is in fact to start with a project which uses the old style and then look for features which you think would benefit from refactoring them to the new ECS pattern:

> **What does this mean for my game?**
>
> you can one by one, convert behavior from MonoBehaviour.Update methods into ComponentSystems. You can in fact keep all your data in a MonoBehaviour, and this is in fact a very simple way of starting the transition to ECS style code.
>
> So your scene data remains in GameObjects & components. You continue to use GameObject.Instantiate to create instances etc.
>
> You simply move the contents of your MonoBehaviour.Update into a ComponentSystem.OnUpdate method. The data is kept in the same MonoBehaviour or other components.

This of course does not make use of the benefits of the new Jobs system and the instantiating of entities through an EntityManager. But those new features can also be mixed and matched with classic MonoBehaviours.

For more information about how to convert a game from using the classic MonoBehaviour pattern to the ECS pattern I also recommend this series of videos from the official Unity channel where they convert the good old space shooter example to the new style step-by-step making use of more and more of the new features. Each step in between works perfectly. The final version still uses some classic game objects, because of a feature which is not yet available with the ECS system (particle effects).
> 8 votes

---
Tags: unity, entity-system, oop, entity-component-system, monobehaviour
---


# Question
Title: MiniMax not working properly(for checkers game)
I am creating a checkers game but My miniMax is not functioning properly,it is always switching between two positions for its move(index 20 and 17).Here is my code:

```
 public double MiniMax(int[] board, int depth, int turn, int red_best, int black_best)
 {

  int source;
  int dest;
  double MAX_SCORE=-INFINITY,newScore;
  int MAX_DEPTH=3;
  int[] newBoard=new int[32];
  generateMoves(board,turn);
  System.arraycopy(board, 0, newBoard, 0, 32);
  if(depth==MAX_DEPTH)
  { return Evaluation(turn,board);}
  for(int z=0;z<possibleMoves.size();z+=2){
        source=Integer.parseInt(possibleMoves.elementAt(z).toString());
        System.out.println("SOURCE= "+source);

        dest=Integer.parseInt(possibleMoves.elementAt(z+1).toString());//(int[])possibleMoves.elementAt(z+1);
        System.out.println("DEST = "+dest);
        applyMove(newBoard,source,dest);
        newScore=MiniMax(newBoard,depth+1,opponent(turn),red_best, black_best);
        if(newScore>MAX_SCORE)
        {MAX_SCORE=newScore;maxSource=source; maxDest=dest;}//maxSource and maxDest will be used to perform the move.

        if (MAX_SCORE > black_best)
        {
            if (MAX_SCORE >= red_best)
                break;  /*  alpha_beta cutoff  */
            else
                black_best = (int) MAX_SCORE;  //the_score
        }
        if (MAX_SCORE < red_best)
        {
            if (MAX_SCORE<= black_best)
                break;  /*  alpha_beta cutoff  */
            else
                red_best = (int) MAX_SCORE;  //the_score
        }

  }//for ends

  return MAX_SCORE;
 } //end minimax

```

I am unable to find out the logical mistake. Any idea what's going wrong?

# Answer
> 4 votes
For your current implementation, this line:

```
return Evaluation(turn, board);

```

should be

```
return Evaluation(rootTurn, board); // rootTurn is black, probably?

```

so your evaluation is in the perspective of the max player. Also,

```
double MAX_SCORE = -INFINITY;

```

should be

```
double MAX_SCORE = turn == rootTurn ? -INFINITY : INFINITY;

```

since if you're minimizing the score as you're doing for red, it can't already be `-INFINITY`.

As you don't seem to be convinced, you can avoid this entire mess of keeping track of sides and whether it's a min or max node, I'd advise using negamax. It gives the same result, but is simpler:

```
public double Negamax(int[] board, int depth, int turn, double alpha, double beta) {
    if (depth == 0)
        return Evaluation(turn, board);
    int[] newBoard = new int[32];
    generateMoves(board, turn);
    System.arraycopy(board, 0, newBoard, 0, 32);
    for (int z = 0; z < possibleMoves.size(); z += 2) {
        int source = Integer.parseInt(possibleMoves.elementAt(z).toString());
        //System.out.println("SOURCE= " + source);
        int dest = Integer.parseInt(possibleMoves.elementAt(z + 1).toString());// (int[])possibleMoves.elementAt(z+1);
        //System.out.println("DEST = " + dest);
        applyMove(newBoard, source, dest);

        double newScore = -Negamax(newBoard, depth - 1, opponent(turn), -beta, -alpha);
        if (newScore >= beta) // alpha-beta cutoff
        return newScore;
            if(newScore > alpha)
                alpha = newScore;
    }// for ends

    return alpha;
} // end minimax

```

In this case it's probably actually faster because you didn't set your alpha bound correctly. It works because of symmetry; `max(a, b) = -min(-a, -b)`. In your root node, you should start the search like this:

```
depth := 3   // what depth to search to?
alpha:= -infinity
foreach move in move list
    do move
    newScore := -Negamax(newBoard, depth - 1, opponent(turn), -infinity, -alpha);
    if newScore > alpha
         alpha := newScore
         bestMove := move
return bestMove

```

# Answer
> 0 votes
You say 'it is always switching between two positions for its move(index 20 and 17)' — once you have debugged and tested your search code (and use the negamax suggested by zong) — you may find that the output still results in an oscillation between two squares.

This may not necessarily be a problem with the search — I've found search result oscillations can occur when the evaluation function doesn't provide sufficient discrimination between the advantages of two different positions in the static eval.

So check both places that your search is scoring as index 20 and index 17 — they may have very similair or identical static scores, and there is insufficient evaluational information for the engine to definitively decide between them.

For debugging negamax, putting in some debug/print statements immediately after the recursive call to negaMax:

```
moveScore = -negaSearch(theBoard, -beta, -alpha, depth-1)

if depth>2 {print (moveIndex, depth, moveScore)}

```

---
Tags: game-design, algorithm, ai
---


title: Unity2D: Sprite Mesh Lighting Issue

text:
# Question
Title: Unity2D: Sprite Mesh Lighting Issue
I am trying to make my 2D mesh render sprites with the **same brightness** as the original file.

On the below picture, the mesh on the left is **darker** than the UI Image on the right, which is an exact likeness of the original file. **How can I make the mesh as bright as the Image?**

So far, I've been looking into the following potential culprits:

* Shader attached to the Mesh
* Global lighting settings
* Mesh renderer lighting settings

The above image is with *Environment Lighting \> Ambient Color* at **#FFFFFF**.

*Environment Lighting \> Ambient Color \> Intensity* doesn't help.
Increasing the shader's emissions can offset the darkness but it's not an ideal solution.

*All other lighting settings both globally and on the Mesh Renderer are default.*

At this point, I'm lost :/
Any help would be much appreciated!

# Answer
> 1 votes
The solution was the **shader** ***type***.
Changing **Shader** Standard -\> **Shader** Unlit/Texture, solved the issue!

---
Tags: unity, shaders, sprites, lighting, global-illumination
---


# Question
Title: Adding functionality to make individual anchor points of bezier continuous or non-continuous
I am creating bezier curves with the following code. The curves can be extended to join several bezier curves by shift clicking in the scene view. My code has functionality for making the whole curve continuous or non-continuous. I realised that I need to make individual points (specifically anchor points) have this functionality.

I believe the most ideal way to go about this is creating a new class for the points with this functionality (making points continuous or non-continuous) since this can be used to add other properties that might be specific to the points. How can do this?

Path

```
[System.Serializable]
public class Path {

[SerializeField, HideInInspector]
List<Vector2> points;

[SerializeField, HideInInspector]
public bool isContinuous;

public Path(Vector2 centre)
{
    points = new List<Vector2>
    {
        centre+Vector2.left,
        centre+(Vector2.left+Vector2.up)*.5f,
        centre + (Vector2.right+Vector2.down)*.5f,
        centre + Vector2.right
    };
}

public Vector2 this[int i]
{
    get
    {
        return points[i];
    }
}

public int NumPoints
{
    get
    {
        return points.Count;
    }
}

public int NumSegments
{
    get
    {
        return (points.Count - 4) / 3 + 1;
    }
}

public void AddSegment(Vector2 anchorPos)
{
    points.Add(points[points.Count - 1] * 2 - points[points.Count - 2]);
    points.Add((points[points.Count - 1] + anchorPos) * .5f);
    points.Add(anchorPos);
}

public Vector2[] GetPointsInSegment(int i)
{
    return new Vector2[] { points[i * 3], points[i * 3 + 1], points[i * 3 + 2], points[i * 3 + 3] };
}

public void MovePoint(int i, Vector2 pos)
{

    if (isContinuous)
    {

        Vector2 deltaMove = pos - points[i];
        points[i] = pos;

        if (i % 3 == 0)
        {
            if (i + 1 < points.Count)
            {
                points[i + 1] += deltaMove;
            }
            if (i - 1 >= 0)
            {
                points[i - 1] += deltaMove;
            }
        }
        else
        {
            bool nextPointIsAnchor = (i + 1) % 3 == 0;
            int correspondingControlIndex = (nextPointIsAnchor) ? i + 2 : i - 2;
            int anchorIndex = (nextPointIsAnchor) ? i + 1 : i - 1;

            if (correspondingControlIndex >= 0 && correspondingControlIndex < points.Count)
            {
                float dst = (points[anchorIndex] - points[correspondingControlIndex]).magnitude;
                Vector2 dir = (points[anchorIndex] - pos).normalized;
            points[correspondingControlIndex] = points[anchorIndex] + dir * dst;
                }
            }
        }
    }

    else {
         points[i] = pos;
    }
}

```

PathCreator

```
public class PathCreator : MonoBehaviour {

[HideInInspector]
public Path path;

public void CreatePath()
{
    path = new Path(transform.position);
}
}

```

PathEditor

```
[CustomEditor(typeof(PathCreator))]
public class PathEditor : Editor {

PathCreator creator;
Path path;

public override void OnInspectorGUI()
{
    base.OnInspectorGUI();
    EditorGUI.BeginChangeCheck();

    bool continuousControlPoints = GUILayout.Toggle(path.isContinuous, "Set Continuous Control Points");
    if (continuousControlPoints != path.isContinuous)
    {
        Undo.RecordObject(creator, "Toggle set continuous controls");
        path.isContinuous = continuousControlPoints;
    }

    if (EditorGUI.EndChangeCheck())
    {
        SceneView.RepaintAll();
    }
}

void OnSceneGUI()
{
    Input();
    Draw();
}

void Input()
 {
    Event guiEvent = Event.current;
    Vector2 mousePos = HandleUtility.GUIPointToWorldRay(guiEvent.mousePosition).origin;

    if (guiEvent.type == EventType.MouseDown && guiEvent.button == 0 && guiEvent.shift)
    {
        Undo.RecordObject(creator, "Add segment");
        path.AddSegment(mousePos);
    }
}

void Draw()
{

    for (int i = 0; i < path.NumSegments; i++)
    {
        Vector2[] points = path.GetPointsInSegment(i);
        Handles.color = Color.black;
        Handles.DrawLine(points[1], points[0]);
        Handles.DrawLine(points[2], points[3]);
        Handles.DrawBezier(points[0], points[3], points[1], points[2], Color.green, null, 2);
    }

    Handles.color = Color.red;
    for (int i = 0; i < path.NumPoints; i++)
    {
        Vector2 newPos = Handles.FreeMoveHandle(path[i], Quaternion.identity, .1f, Vector2.zero, Handles.CylinderHandleCap);
        if (path[i] != newPos)
        {
            Undo.RecordObject(creator, "Move point");
            path.MovePoint(i, newPos);
        }
    }
}

void OnEnable()
{
    creator = (PathCreator)target;
    if (creator.path == null)
    {
        creator.CreatePath();
    }
    path = creator.path;
}
}

```

# Answer
> 1 votes
If you want control over whether individual points are continuous or not you could replace your `bool isContinuous` in your `Path` class with a `List<bool>`. Each element in the list would store whether or not the corresponding point in your `points` list is continuous.

---
Tags: unity
---


# Question
Title: Black screen when trying to render multiple textures
I generate an array for two textures:

```
int[] textureID = new int[2];
glGenTextures(1, textureID, 0);
glGenTextures(1, textureID, 1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureID[0]);
glBindTexture(GL_TEXTURE_2D, textureID[1]);

```

Render:

```
int Position = glGetAttribLocation(Shader.program_Image, mPosition);
glEnableVertexAttribArray(Position);
glVertexAttribPointer(Position, 3, GL_FLOAT, false, 0, vertexBuffer);
int TexCoordLoc = glGetAttribLocation(Shader.program_Image, atexCoord );
glEnableVertexAttribArray (TexCoordLoc);
glVertexAttribPointer (TexCoordLoc, 2, GL_FLOAT, false, 0, uvBuffer);
int mtrxBackground = glGetUniformLocation(Shader.program_Image, mbackground);
int mtxObj = glGetUniformLocation(Shader.program_Image, mobj);
glUniformMatrix4fv(mtrxBackground, 1, false, m, 0);
glUniformMatrix4fv(mtxObj, 1, false, m, 0);
int mSamplerLoc = glGetUniformLocation (Shader.program_Image, bTexture);
int mSamplerLoc1 = glGetUniformLocation (Shader.program_Image, sTexture);
glUniform1i (mSamplerLoc, 0);
glUniform1i(mSamplerLoc1, 1);
glDrawElements(GL_TRIANGLES, background.getIndices().length, GL_UNSIGNED_SHORT, drawListBuffer);

```

My fragment shader is like this.

```
precision mediump float;
varying vec2 v_texCoord;
uniform sampler2D b_texture;
uniform sampler2D s_texture;
void main() {
    gl_FragColor = texture2D(b_texture, v_texCoord );
    gl_FragColor = texture2D(s_texture, v_texCoord );
}

```

I have no error message, but when I run the application, I only see a black screen.

The app runs correctly with just one texture, but doesn't with more than one. What's wrong in my code?

Do I have to add another set of coordinates and update the vertex shader? Because I have only one “rectangle” constructed from two triangles.

# Answer
> 0 votes
Sequentially binding two textures without doing anything in the middle is pointless. Only one texture is bound at a time, so in this case it's the last one.

```
glActiveTexture(GL_TEXTURE0);

glBindTexture(GL_TEXTURE_2D, textureID[0]);

glActiveTexture(GL_TEXTURE1);

glBindTexture(GL_TEXTURE_2D, textureID[1]);

```

Also, a fragment shader only has one output, if you override it, only the last will count. If you want to mix the textures, you have to decide how to do it, do you want them to be multiplicative, additive? Do you want them to just blend by the alpha?

```
vec4 col1 = texture2D(b_texture, v_texCoord );

vec4 col2 = texture2D(s_texture, v_texCoord );
gl_FragColor = col1 + col2;
//gl_FragColor = col1 * col2;
//gl_FragColor = vec4(col1.rgb * (1.0f - col2.a) + col2.rgb * col2.a, 1.0f);

```

---
Tags: glsl, opengl-es
---


# Question
Title: How to know if mouse coordinates is delta or absolute on Window and Android in Unity?
I wrote sample application, that allows to "rotate" object by mouse. Rotation occured by rotating of camera object around central object and the code is following:

```
float mouseX = -Input.GetAxis("Mouse X");
float mouseY = -Input.GetAxis("Mouse Y");

float magnitude = transform.position.magnitude;

Vector3 mouseSwipe = new Vector3(mouseX, mouseY, 0);
Vector3 startPoint = new Vector3((float)camera.pixelWidth / 2, (float)camera.pixelHeight / 2, magnitude - 1);

Vector3 startPointWorld = camera.ScreenToViewportPoint(startPoint);
Vector3 endPointWord = camera.ScreenToViewportPoint(startPoint + mouseSwipe);

Vector3 mouseSwipeWord = endPointWord - startPointWorld;

float dragLat = mouseSwipeWord.y;
float dragLng = mouseSwipeWord.x;

Vector3 oldPosition = transform.position / magnitude;

float lat = Mathf.Asin(oldPosition.y);
float rsmall = Mathf.Acos(oldPosition.y);

float lng = Mathf.Atan2(oldPosition.z / rsmall, oldPosition.x / rsmall);

lat += dragLat * 10 * 2 * Mathf.PI;
if( lat*180/Mathf.PI > 80 )
{
    lat = 80 * Mathf.PI / 180;
}
else if( lat*180/Mathf.PI < -80)
{
    lat = -80 * Mathf.PI / 180;
}

lng += dragLng * 10 * 2 * Mathf.PI * 2;

float y = Mathf.Sin(lat);
rsmall = Mathf.Cos(lat);

float x = rsmall * Mathf.Cos(lng);
float z = rsmall * Mathf.Sin(lng);

Vector3 newPosition = new Vector3(x, y, z);
newPosition *= magnitude;

transform.position = newPosition;

LookAtTarget();

```

The code assumes that mouse returns delta value on each swipe and this works well on Windows. For example, if I do several separate swipes, I can gradually rotate object for full circle.

Unfortunately, when I run this on Android, it doesn't happen. Each swipe object restarts from some position, depending on swipe point. I.e. on Android, swipes return in absolute value.

Is it possible to know, whether swipes retunrs delta or absolute values and how? Is it possible to claim compatible return units?

# Answer
Have you checked what the value of `Cursor.lockState`?

My guess is that the mouse is locked to the center of the screen on Windows, but you can’t lock a user’s finger in place very easily.

https://docs.unity3d.com/ScriptReference/Cursor-lockState.html
> 0 votes

---
Tags: unity, android, coordinates, mouse, compatibility
---


# Question
Title: How do I get the distance between 2 actors in LibGDX?
How do I get X the distance between 2 actors in LibGDX?

# Answer
> 0 votes
Mathematically you want to use the absolute value e.g. `java.lang.Math.abs(x1-x2)` will give you what you want.

---
Tags: libgdx
---


# Question
Title: Depth Compositing - Background Not Being Rendered
I have a pre-rendered 3D scene which I am rendering as a background image. Over this, I am rendering an invisible version of this scene only into the depth buffer, so that any other 3D object will be not be rendered if they pass behind an object in the 3D scene. As long as the camera remains static, the player will not notice that the scene is pre-rendered. I believe this method is called 'Depth Compositing', or something similar. It has been used in older games.

The problem I am having is that the pre-rendered background image is not showing through the invisible 3D scene being rendered to the depth buffer, like so:

It should look similar to this:

Here is a screenshot of the scene view to help visualize how this is setup:

The cube is rendered with this shader:

```
Shader "Custom/Depth"
{
    SubShader {
        Tags { "Queue" = "Geometry-10" }

        ColorMask 0
        ZWrite On

        Pass {}
    }
}

```

The background image is rendered in panel in a UI canvas, set to `Screen Space - Camera`. It is rendered in its own camera with a lower depth than the 3D object camera.

My assumption is this is to do with render ordering somehow, as perhaps the UI is being rendered after the 3D objects?

# Answer
> 0 votes
The issue was to do with render order - using the Canvas was causing the problem. Thanks to `DMGregory's` suggestion, using a Plane fixed the issue.

The final method I used is like this:

1. Create two cameras: 'Background Camera', '3D Camera'
2. Set both cameras is position 0,0,0 and rotation 0,0,0
3. Set the depth of 'Background Camera' to 0 and '3D Camera' to 1
4. Create two layers: 'Background', '3D'
5. Set 'Background Camera' to only render the 'Background' layer; '3D Camera' to render the '3D' layer (and the other general layers)
6. Create a Plane. Add the plane to the 'Background' layer
7. Set the plane to position 0,0,1 and rotation 90,90,-90 and scale to 0.25,1,0.13
8. Add the prerendered background to the plane's material
9. Add the invisible scene to the '3D' layer

To visualize how this looked for me, here is a screenshot of my editor:

---
Tags: unity, depth-buffer
---


# Question
Title: 2D Spatial partitioning alternatives to spatial hashes and quadtrees
I've been trying to implement a spatial partitioning algorithm in my game, but both spatial hashes and quadtrees aren't what I'm looking for.

My level size is not supposed to have a limit (only Int32 limits). I need a spatial partitioning algorithm that doesn't need a "Level Width" and a "Level Height".

I have many moving physical objects. I need the algorithm to be fast enough to support 500+ objects.

Any alternative?

# Answer
I've decided to go with fixed 2D grids.

I've made two videos which explain in-depth how I implemented them, and the current implementation is available on my GitHub page: https://github.com/SuperV1234/SSVSCollision

http://www.youtube.com/watch?v=7HY\_SqqaoL4

http://www.youtube.com/watch?v=vYB37BDtHuQ
> 0 votes

# Answer
### Dynamic Tree

Box2D is a well optimized engine designed by an experienced physics/game programmer. Originally Box2D used a hash grid that required a fixed height and width.

When Erin upgraded to a better broadphase algorithm he went with Nathanael Presson's btDbvt. This is the broadphase used by Bullet Physics. Erin modified and optimized the algorithm for 2d.

You can read a super high level overiew in the Box2D manual ( §4.11, or search for Dynamic Tree).

Here's an except from the in code documentation (which is very good considering it's not part of the public API).

> A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt. A dynamic tree arranges data in a binary tree to accelerate queries such as volume queries and ray casts. Leafs are proxies with an AABB. In the tree we expand the proxy AABB by b2\_fatAABBFactor so that the proxy AABB is bigger than the client object. This allows the client object to move by small amounts without triggering a tree update.
>
> Nodes are pooled and relocatable, so we use node indices rather than pointers.

My understanding of the Dynamic Tree's algorithm is this. The Dynamic tree is the cross between a classic avl binary tree and a quadtree. The end effect is a quadtree that that only splits each node in half, and the split line isn't fixed (the two halves aren't equal sized like a quad tree). AVL comes in because quadree with dynamic splits can degenerate to essentially a list (O(n) lookup speed). The AVL is used to rebalance subtrees so to ensure O lg(N) lookup speed.

Best of all the code is MIT so feel free to copy / derived / shamelessly-steal / etc.
> 14 votes

# Answer
This is very close to a similar question asked here on Gamedev, but seeing as you're concerned with performance and not file storage, perhaps my answer there will be of more use to you. I'll include the bulk of it here for completeness, but the original answer provides a little more depth if you want to look into it.

> I ran into a similar problem and decided to create my own structure to handle the data. It's based loosely on a quadtree, but has infinite (at least as big as an Int) expandability in all directions. It was designed to handle grid-based data which expanded from a central point, much like Minecraft does now. It is space efficient in memory, and very fast.
>
> My code can be found here. The code is complete, tested (unit- and load-tests), and quite optimized. The inner workings aren't too well documented yet, however, but all the public methods are so it should be usable. If anyone decides to try it out, feel free to contact me with questions or comments.
> 8 votes

# Answer
When working with a relatively small number ( \< several thousand) of smallish objects (most objects aren't big enough to potentially collide with a lot other objects) I find that a simple x-ordered list of axially aligned bounding boxes (AABBs) works pretty well. I just put the objects in a list, then each frame after moving the objects, I quick sort the list by x value, then make one pass through the list checking for AABB proximity. For each object, I check it against the objects ahead of it in the list until I either reach the end of the list or an object which is out of x range; that is, it's left edge's x value is \> x value of the right edge of the object being tested. It basically dynamically divides space into sometimes-overlapping, AABB-x-width-sized slices. It's pretty easy to understand and implement and it works pretty well for the targeted sub set of use cases.
> 1 votes

# Answer
Maybe the r-tree algorithm is what you are looking for.

I works really well for static geometry, but you can also use it for moving objects by removing and adding objects at their new positions.
> 0 votes

---
Tags: c#, collision-detection, physics, tree
---


# Question
Title: Is it advisable to maintain a separation between the engine and the game?
As I'm reading Uncle Bob's Clean Architecture I keep wondering how all the advice presented can be applied in game development. Games are nothing more that highly interactive real-time simulations and shouldn't really differ that much from any other complex systems. Good practices in architecture design should be as much help here as anywhere else.

That said I have some doubts whether obtaining a high level of coupling between game engine and its logic can be easily obtained. Game engine is basically a framework so "Frameworks Are Details" rule should be of use here but from what I see games are practically inseparable from their underlying engines. I haven't seen any use of Clean Code rules in most projects I've encountered. I've heard than even unit testing is a rare occurrence.

How can I even achieve loose coupling if all important subsystems like event handling, physics, renderer and even main loop itself are baked in the engine?

Or should I ignore this since an engine is not a database and it'd be highly unlikely to think about changing it as the project goes by?

# Answer
As a general rule, switching to a different game engine is not something that is likely to ever happen past early development. I can literally count on one hand the number of games I've seen do this after shipping, and in almost all cases it was a change from a third-party engine to one that was developed in-house to specifically meet the needs of the game in question (for example, World of Tanks recently did this). Given this, you can treat it in much the same way you would treat the operating system if you're programming for a single platform and not ever going to port your software, namely, use all the features to the extent you need them, and don't worry about writing your code in such a way that it's trivial to use on a different game engine.

The one exception I would make to this is if you're developing the engine alongside the game. In this case, it's very easy to get the two into a state where you can't ever hope to use the game engine for anything else, and that's generally a bad thing, and you should try to avoid letting that happen.

Now, technically, a game engine is a 'framework'. However, a much better way of describing it is a platform. I mentioned above that you can treat a game engine like an operating system, and this is because it largely does the same thing that an operating system does. The easiest way to understand this is to look at what game programming was like for older console systems that did not have a conventional operating system (for example, any Nintendo system before the Wii or DS, the PS1 and PS2, the original Xbox, and most of the early Sega systems). On those platforms, the game engine *was* the operating system. It provided all the hardware abstractions that were present (and there weren't many), and also defined the 'platform' that the game was written for. There are of course more layers of indirection now, but the same general principles are there. If you write something on, for example, Unity, you can easily get it running on a number of different systems, because Unity handles almost all the work for you.
> 4 votes

# Answer
A Game Engine is, as you said, just a framework. but depending on the amount of 'services' the engine delivers, its arguable how dependent your game really is, when you work with this frame work.

Most Game Engines have their Main class to instantiate, some manager classes to inherit and fill. You instantiate objects, maybe with a graphical representation, sounds, some game rules attached to it. When you start your final game, everything works, because the engine does most of the work.

This basically as decoupled as it can get. You only import some small scripts into the game, most likely not even in the same programming language as the engine was written with.

That said, if you would want to change your game engine mid development, yo could do that. If both engines have the same 'services', maybe the new one even more, all you do is change your function calls for the framework you are using now. Maybe you can't use the same graphics objects (no jpgs or different 3d models), maybe the script language is different, but in the end, you only call the interface of you frame work.

How would you even want to make unit tests on these? Maps, models, animations dont need unit tests. Developers of game engines SHOULD do unit tests, mock components and stuff, but from the view of the end user (the one working the the framework), you have basically no need for that. And unit tests with scrips may be a bit to much.
> 1 votes

# Answer
You should definitely keep as much of your game logic separate from the game engine as possible.

Create libraries and reference them from the main program.

Its easier to see why if you think about a more abstract game than a FPS.

Chess for example, you would want all your, 'is this move valid' and 'whats the best move' code completely decoupled from your 'display the chess piece being moved' code so that it could be fully tested in isolation. Indeed you would probably just want to plug in an existing chess engine to your game.

Even a simple FPS will still have some abstract logic. How many shots can the player take before dying? what damage does a gun of type X do?

Sure, leave the physics in the engine, but your life will be easier if you can just call Player.IsWearingRollerSkates from your player library rather than having everything embedded in ,for example, unity behaviours
> 1 votes

# Answer
I think you should view a game engine as a chunk of reusable code, not as a replaceable component of your software which you could decide to change on whim.

Most of the time, choosing an engine is equivalent to committing to it. If you start building your game with Unreal/c++, you'll have a hard time switching to Unity/c#. Switching midway will require a lot of planning and work.

Also, keep in mind that games are often "disposable code": make the game, release the game, release a bug-fix patch, release a couple of DLCs and never touch this game code again because you'll be working on the next game. Switching engine midway is often only relevant in contexts where the game will be running for years (as you've illustrated with world of tanks).

> Is it advisable to maintain a separation between the engine and the game?

You'll have to figure that out *before* you start. If you want to be able to switch engine during the development (for any reason), you'll have to make sure that the underlying services that these engines offer are roughly architectured the same way. You'll then be able to abstract these services into your own layer, thus eventually replacing only that layer with the engine.

> How can I even achieve loose coupling if all important subsystems like event handling, physics, renderer and even main loop itself are baked in the engine?

You add another layer that handles all of this. Yes, you'll have to re-code a lot of stuff, but your game will ignore (mostly) completely what engine it uses.

> Or should I ignore this since an engine is not a database and it'd be highly unlikely to think about changing it as the project goes by?

Although you raise valid questions here, yes, I think you should ignore this :)

If you can't really justify all the overhead that would imply wrapping Unity's `Vector3` class into your own `vec3` class because you don't want to couple your game to Unity, then stick to one engine, make the game, release it, make a post-mortem and decide if it was the right engine for you and if it is the right engine for your next game, then produce the next game and make money.
> 0 votes

---
Tags: architecture
---