# Question
Title: Unity FPS Offline Multiplayer (MultiLan) Player Animation
I am creating an FPS game in local multiplayer. One player creates the hot-spot game, and the other one connects through WiFi network and plays the game. And i am doing this using unity MultiLan Package available in Unity Assets Store.

when the player connect to the Game i play the player animation like walk , jump etc. But the problem is animation can play only which player who host the Game, not play to other player who join the Game in host network.

That is Player Script.

```
private MNetwork networkSrc;
public Btn_Jump jumpScript;
public Btn_DPad Btn_DpadScript;

void Awake() {
    if (GetComponent<NetworkView>().isMine) {
        trans = transform;
        contr = trans.GetComponent<CharacterController>();

        if (jumpScript == null) {
            jumpScript = GameObject.Find ("3 Jump").GetComponent<Btn_Jump> ();
        }
        if (Btn_DpadScript == null) {
            Btn_DpadScript = GameObject.Find ("6 D-Pad").GetComponent<Btn_DPad> ();
        }
    }
}

void Start() {
    if (GetComponent<NetworkView>().isMine) {

        // If it's my player : search the networkManager component
        networkSrc = GameObject.Find("MNetwork").GetComponent<MNetwork>();
        PlayerAnimatorComponent = GameObject.Find ("Swat").GetComponent<Animator> ();

        FPS_Events.ChangeCharacterMotor(motor);
    }

}
 void Update() {

    if (!networkSrc.isPlayerExitGame) {

            if (currentMotor == null)
                FPS_Events.ChangeCharacterMotor (motor);
            try {

                currentMotor.Update ();
            } catch {
            }

            if (jumpScript.Player_jump) {

            }
            if (Btn_DpadScript.Player_Run) {
                RunAnimation ();
            }

    }
}

void RunAnimation(){
    GetComponent<NetworkView> ().RPC ("SyncAnimation", RPCMode.All);
}

[RPC]
void SyncAnimation(){
    if (Btn_DpadScript.Player_Run) {
        PlayerAnimatorComponent.SetFloat ("Walk",2f,0.1f,Time.deltaTime);

    }
}

```

In this Script there is "Btn\_DpadScript" object of Virtual joystick Script name is "Btn\_DPad" for Player Movement.

When player move then "Player\_Run" Boolean variable is true and play the Walk animation of player in SyncAnimation() method.

But it is stuck to play animation in all player in same network.

Any one can know how to play animation in all network player using MultiLan Package then tell me. I can't found in Google Search about player Animation in network using MultiLan Package.

what should i do don't know any one can suggestion then i really appreciate thank you.

# Answer
You should need to use **NetworkAnimator** for your animation sync on clients

> The NetworkAnimator is used to synchronize animations across the network.

Grab this simple **Tutorial**.
> 0 votes

# Answer
This line looks suspect:

```
PlayerAnimatorComponent = GameObject.Find ("Swat").GetComponent<Animator> ();

```

This says "Find *some* object in the scene named Swat. I don't particularly care which one."

So if you spawn multiple player avatars, each one called "Swat", this line is liable to return just the first one (ie. the host player's avatar) every time, and never apply animation state variables to the other avatars in the game. The same will happen if remote players' avatars get spawned with a modified name, like "Swat (clone)" which no longer matches the search string.

In general, you should avoid looking up GameObjects by name \- especially when searching the whole scene. Assigning them via an inspector variable, or via the script that spawns them, will be much more robust under a variety of use cases.
> 0 votes

# Answer
Both answers already showed whats wrong. You also odnt use networkview.isMine with Unet but the implemented network behaviour (!isLocalPlayer) together with the network identiy object.

In order to be able to use this, you first have to import the libary:

use UnityEngine.Networking

Then, your script must inherit from this libary, which you can do by changing the MonoBehavour to NetworkBehaviour, lkke so:

```
public Class YourClass : NetworkBehaviour {

ShootingScript shoot;

void Start(){

if(isLocalPlayer){

shoot = GetComponent<ShootingScript>();
shoot.enabled(true);

}
}

```

}

Theres no real need to activate your anim per player, because unity offers the transform view & the animator view. Simply add those two components and the network identity component. Make also sure to check "isLocal" on the network identity component. This way, unity will knows who is the localplayer and who not. Check out the starting guide whenever you are wondering how to do certain things. You need to approach Network Stuff much different then Non Network things. GameObject.Find is something you wouldnt want to use in a network based environment.

Greetings!
> 0 votes

---
Tags: unity, animation, networking, multiplayer
---


# Question
Title: Is it possible to store ALL game data on the sever side
I want to make a game where everything is supposed to be a surprise. Everything from the maps to the enemies, no guides what so ever. For a normal player it may not be a big deal but some people may try looking into the game files to find various information.

In order to prevent this, is it possible to store all game files or at least the files that has the info on all the different items, areas, magic spells and such on the server side. In that case, the items and things players unlocked will be stored on the player’s PC and they won’t be able to know details about things they haven’t unlocked yet.

In the case all or at least most game data is stored on the server side, does it even prevent players looking into the game files and will it work on a large scale game.

# Answer
It's not an approach worth to use.

> For a normal player it may not be a big deal but some people may try looking into the game files to find various information.

Even if you download the content at run-time, there are various ways that the cheater can inject code into your game and read or write the memory.

> In order to prevent this, is it possible to store all game files or at least the files that has the info on all the different items, areas, magic spells and such on the server side. In that case, the items and things players unlocked will be stored on the player’s PC and they won’t be able to know details about things they haven’t unlocked yet.

Nothing prevents one advanced player passing the list of items to a newer player to have access to those items yet unknown.

> In the case all or at least most game data is stored on the server side, does it even prevent players looking into the game files and will it work on a large scale game.

You will have to have a server running 24/7, and it will consume bandwidth extensively. Meaning, it will be expensive (for you) and players will experience lag frequently. And as I said before, it won't prevent players from hacking to read or write in the game's memory.
> 3 votes

# Answer
Yes it is possible.

However not without drawbacks and paradigm shifts.

1) you can leave code, database entries and game content server side and only download / access during runtime one level at a time or as needed.

This obviously will have possibly long loading times and will be very bad for game experience. You should only keep "spoiler content" server side.

This will leave your game (client - server) communication prone to the usual hacks.

2) a better approach is actual cloud gaming. ALL game content is stored on servers, even code execution (including graphics engine) is NOT client side. You'll actually only stream the display content to the client like you would a movie from Netflix, Amazon and the likes while the client returns user input to the server.

This is currently in heavy development.

Nvidia being just one example: https://www.nvidia.com/object/cloud-gaming.html

This seems to be one offering something like that, I just did a quick search, so it may not be what you need. https://parsecgaming.com

Amazon and google also offer cloud services and game servers as far as I know.

Your clients need access to a very(!) low latency internet connection but depending on resolution and compression app.10-20Mbps bandwidth should suffice for HD/4k.

Since all game logic is server side, there is no communication to intercept or code residing in local memory, thus making cheating and hacking the game itself really difficult if not impossible.

Incidentally this also should make piracy very difficult and will most likely shift it towards access hacks and internal leaks instead.

Brave new gaming worlds...
> 0 votes

# Answer
It really depends on what you're trying to achieve. All browser game are like that for example so it is indeed possible. However sending to the client the 3d model of the game world, even if it's indeed possible, it's not smart.
> 0 votes

---
Tags: multiplayer, server, data, storage
---


title: Emission for Mobile Shaders?

text:
# Question
Title: Emission for Mobile Shaders?
I need to use Emission texture to my model, but I can't find any emission parameters in mobile shaders.

I searched this on google, but there's nothing helpful to me.

How do I add emission for mobile shaders, without writing own shader code? (I'm keep studying shader but still not good at)

# Answer
Somewhere I found the source code of built in shaders in Unity. So I just added emission property and apply it to result output and it works.

Hope might be helpful who needed it.

```
Shader "Custom/MobileBumpedDiffuse" {
    Properties {
        _Shininess ("Shininess", Range(0.03, 1)) = 0.078125
        _MainTex ("Base (RGB)", 2D) = "white" {}
        _Glossiness ("Glossiness", 2D) = "black" {}
        _BumpMap ("Normalmap", 2D) = "bump" {}
    }

    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 300

        CGPROGRAM
        #pragma surface surf MobileBlinnPhong exclude_path:prepass nolightmap noforwardadd halfasview

        inline fixed4 LightingMobileBlinnPhong(SurfaceOutput s, fixed lightDir, fixed3 halfDir, fixed atten)
        {
            fixed diff = max(0, dot(s.Normal, lightDir));
            fixed nh = max(0, dot(s.Normal, halfDir));
            fixed spec = pow(nh, s.Specular * 128) * s.Gloss;

            fixed4 c;
            c.rgb = (s.Albedo * _LightColor0.rgb * diff + _LightColor0.rgb * spec) * (atten * 2);
            c.a = 0.0;

            return c;
        }

        sampler2D _MainTex;
        sampler2D _Glossiness;
        sampler2D _BumpMap;
        half _Shininess;

        struct Input {
            float2 uv_MainTex;
        };

        void surf(Input IN, inout SurfaceOutput o) {
            fixed4 tex = tex2D(_MainTex, IN.uv_MainTex);
            o.Albedo = tex.rgb;
            o.Gloss = tex2D(_Glossiness, IN.uv_MainTex).rgb;
            o.Alpha = tex.a;
            o.Specular = _Shininess;
            o.Normal = UnpackNormal(tex2D(_BumpMap, IN.uv_MainTex));
        }

        ENDCG
    }

    Fallback "Mobile/VertexLit"
}

```
> 0 votes

---
Tags: unity, shaders
---


# Question
Title: Normalmap texture in Unity from SP disorted a lot
As title said, normalmap made from Substance Painter in Unity disorted. Here is the picture:

I made red rectangles to see more cleary. You can see that the some of line of normal were disorted obviously.

I have no Idea why this happens. Model made from Blender 2.78c and exported as FBX. Used Substance Painter 2017.3.3 and tested in Unity 5.6.x and 2017/2018.1.f1.

Any advice will very appreciate it.

# Answer
> 0 votes
According to Allegorithmic forum, Blender and Substance Painter handles 3d object differently.

Before export FBX from Blender, make sure triangulate object, and in my case it works.

Importing in Unity doesn't have to triangulated, and works perfect with texture painted from Substance Painter that triangulated.

---
Tags: unity, textures, uv-mapping, normal-mapping
---


# Question
Title: How do I check if a window has focus in SDL2?
Is there a replacement for `SDL_GetAppState` function in SDL2 from older SDL versions? Why was it removed? I want to use it so I can check if the user has focused the framebuffer window or not.

I found it in the documentation of the SDL 1.2.15 (Documentation page) but it seems like it disappeared in SDL2.X.

# Answer
You can use `SDL_GetWindowFlags`, it returns similar flags (among others) that you can use to check if the window has mouse/input focus.

The API has changed because SDL2 supports multiple windows.
> 6 votes

---
Tags: c++, sdl, sdl2, c
---


title: Tank movement based on track speeds

text:
# Question
Title: Tank movement based on track speeds
I want a system, where a tank moves and rotates based on the speeds I give him for the two tracks, for example, if I give the left track a speed of 1 and the right one a speed of -1, then I want the tank to stay still and rotate right, while if I give the left track 1 and the right track -0.5, I want it to rotate, but at the same time move forward

Of course the speeds will be between -1 and 1

# Answer
Disclaimer: this is based on intuition only, and there's definitely a missing piece for it to be mathematically exact. However, as far as I can tell, it should be a good enough approximation for small displacement values.

The idea is that the center of each tread describes a perfect motion, without skidding. Let's draw a diagram:

**O** is your tank's origin, **L** and **R** are the treads' centers. Then you'd perform as follows:

* **L** and **R** are found by taking the left and right orthogonal rotations of your direction vector **d**, and adding them to the origin;
* **L'** and **R'** are found by applying the two lateral speeds to **L** and **R** WRT the direction vector.
i.e. **L' = L + speed(L) x d** and **R' = R + speed(R) x d**;
* **O'** is the middle of **\[L'R'\]**, i.e. **(L' + R') / 2**;
* The new direction vector is orthogonal to **\[L'R'\]**.

The approximation comes from the fact that **L'R' \> LR**, that is, the tank actually stretches slightly when turning. Fixing that would require more advanced tools (some sort of curved vector ? I have no clue :p). However, as long as the speeds for each frame remain relatively small, this should be good enough.
> 3 votes

# Answer
The following example code shows a simple way to move a tank around realistically. It animates a 2D tank from a bird's eye view, but the calculations are the same in any case.

It assumes you have created a sprite named `tank`, and that you have centred its origin. There are some general notes after the code.

```
const hone = function(current, target) {

    // This helper takes current and target speeds, and returns
    // the value that the current speed should update to next.

    return current - Math.sign(current - target) / 100;
};

let speed, differential; // the tank speed and track differential

// The user can only set the *target* speed of a track. The actual
// track will usually take some time to reach that speed:

let leftSpeed = 0;  // the actual speed of the left track
let rightSpeed = 0; // the actual speed of the right track
let leftTargetSpeed = 0;  // the target speed of the left track
let rightTargetSpeed = 0; // the target speed of the right track

engine.update = function() {

    // Update the target speeds, then update the actual speeds:

    [leftTargetSpeed, rightTargetSpeed] = ui.levers.getState();
    leftSpeed = hone(leftSpeed, leftTargetSpeed);
    rightSpeed = hone(rightSpeed, rightTargetSpeed);

    // Calculate the `speed` and `differential`:

    speed = (leftSpeed + rightSpeed) / 2;
    differential = leftSpeed - rightSpeed;

    // Then the magic happens...

    tank.rotation += differential;
    tank.position.x += Math.cos(tank.rotation) * speed;
    tank.position.y += Math.sin(tank.rotation) * speed;
};

```
* The `engine.update` function will be invoked on every animation frame.
* The `ui.levers.getState` method returns a list of two floats (each between `-1` and `1`), representing the state of two levers that the user pushes and pulls to control each track.
* In practice, you'll need to multiply or divide some values, else your tank will drive too fast, or spin too slowly or something.
> 0 votes

# Answer
Have a vector for each wheel and then calculate the cross product for the direction the tank should be facing with the result of cross(leftWheel, rightWheel);
> -1 votes

---
Tags: rotation, movement
---


# Question
Title: Unity Rotations Not Following Local Nor Global Axis?
In the gif below, you can see that rotating on X moves all 3 axis including the X axis. It's possible it's rotating on the global X rather than local X (hard to tell). But Y looks more like it's rotating on global Z and Z is quite clearly rotating on *local* Z. What is going on? Why is there no consistency?

# Answer
> 3 votes
It's a common misconception that the three numbers in the Euler angle fields correspond in a simple 1:1 way with the three axes of the rotation gizmo on an object that we can see spatially in the editor. It's easy to disprove this though - once we've rotated the object on two axes, subsequent rotations using the editor gizmos will tend to change all three Euler angles at once:

That the three axes of the Euler angles happen to line up with the local axes / rotation gizmos when one or more axes are zero is something I'd recommend regarding as coincidence. In the general case, there's no simple relationship between Euler angles and the object's axes of rotation as shown & used in the editor or via Transform.Rotate calls.

So, what *do* the Euler angles represent? They specify a *sequence* of rotations, applied in the following order:

1. Rotation by `z` degrees about world Z+
(This is why it looks like the z parameter rotates around local Z+: since it's applied first, the local and world z are identical at first.)
2. Rotation `x` degrees about world X+
(If our `z` rotation was zero, this is the same as rotating about local X+. If not, then the rotation we applied in the previous step affects the relationship between the object and the x rotation axis, and so on down the chain...)
3. Rotation by `y` degrees about world Y+
(Since this one comes last, it's the "most global" of the three, which is why it tends to align with world Y in the final transformation - unless we're inside a rotated parent object which then turns this axis somewhere else...)
4. Parent's rotations
(again in the order Z-X-Y, all the way up the transform hierarchy)

Each of these three fields is applied all at once as a total when its turn in the sequence comes. Since rotations are not commutative, that means you get a different result than if you saved some of the rotation to apply "on top" as an increment after the rest. That's why it doesn't behave in a very intuitive way once you've already rotated an object.

If you have an object rotated at (-54, 38, -25) in Euler angles, and then you change the `x` value to -79, the Euler angles don't "remember" that the first -54 degrees were applied first, and then apply the remaining 25 degrees relative to *those* resulting axes. The Euler angles are just numbers. So they give you the result of rotating -25 on Z, *then* -79 on X, *then* 38 on Y.

Because any changes to the numbers get folded-in this way, Euler angles can behave in profoundly non-intuitive ways if you're trying to manipulate them one angle at a time. They're an effective way of storing / printing a rotation in a way that's concise and human-readable, but not a good way of modifying or computing a rotation.

For those manipulating orientations, you'll more often want to use the editor gizmos (which represent incremental rotation about a specific axis), Transform.Rotate, quaternion composition, or constructing your desired orientation from forward & up basis vectors.

---
Tags: unity, rotation
---


title: Can you publish game on multiple sites?

text:
# Question
Title: Can you publish game on multiple sites?
Is it normal (or even allowed) to publish games on multiple sites i.e Itch.io, Gog and Humble Bundle.

Specifically in my case I am thinking of web games.

Thanks

# Answer
General rule: YES. You have the copyrights of the game you made? Then you can distribute anywhere you want.

Exception: if you made a contract that gives any publisher/platform the copyright or exclusivity. As of today, none of these platforms (Steam, GOG, Itch) ask for exclusivity. But publishers, if you distribute your game through one of them, usually ask the copyrights of the game. In this case, you are still the author, but you are not copyright holder.

Before submitting your work to any of these sites, or other sites, you should always read their EULA.
> 3 votes

# Answer
Yes. But as mentioned above, it depends on your license terms if there are any. If plan on posting on gaming websites like Miniclip or Armor games, you'll definitely want to get a license agreement with them. Otherwise if you go onto sites like itch.io or GoG then you are on your own and your success is dependant on luck, how well you can market your game, the game itself, etc.
> 0 votes

---
Tags: web, publishing, webapp
---


# Question
Title: How can I make an object rotate a certain number of degrees per second within _physics_process?
I used delta to help with this but the object ended up rotation to much within a second.

```
extends KinematicBody2D
export var speed = 10.0

onready var sprite = $Sprite

var initpos = Vector2()
var dir = Vector2()
var velocity = Vector2()

#attack variables
var attacking = false
var max_attack_counter = 0.5
var attack_counter = max_attack_counter
var attack_speed = 200
var attack_rotation_speed = 1
var attack_rotation_distance = attack_rotation_speed * max_attack_counter
var attack_rotation = 0
var sword_init_x = 0
var sword_init_y = 0
var attack_type = 0
#Find way to get frames per second
var one_sec = 60

var counter = 0.0
var moving = false
var jumping = false
var col_inf = 0

class entity_input :

    var move_up = false
    var move_down = false
    var move_right = false
    var move_left = false
    var move_h = 0.0
    var move_v = 0.0
    var move_average = 0.0
    var clockwise = 0.0
    var counter_clockwise = 0.0
    var stance = 0
    var dodge = 0
    var sword_move_h = 0.0
    var sword_move_v = 0.0
    var sword_down = 0.0
    var sword_up = 0.0
    var sword_center = false
    var jump = false
    var aim
    var attack = false

var ei = entity_input.new()
enum direction { UP, DOWN, LEFT, RIGHT }
var facing = direction.DOWN

func _ready():

    initpos = position
    pass

#The z_index property wasn't working because the textue has multiple frames of sprites added to gether
#which made the texture 4 times as big as it thought it was
func _physics_process(delta):
    if(one_sec == 0):
        one_sec = 60

    get_input()
    use_input()
    set_dir()
    #Sword Stuff here

    sword(delta)

    move(delta)

    if facing == direction.DOWN:
        sprite.frame = 0
    elif facing == direction.UP:
        sprite.frame = 12
    elif facing == direction.LEFT:
        sprite.frame = 4
    elif facing == direction.RIGHT:
        sprite.frame = 8

#
func sword(delta):
    if($Sword):
        if($Sword and !attack(delta)):
            $Sword.look_at(ei.aim)

func set_dir(): #set moving
    dir = get_dir()

    if dir.x != 0 or dir.y != 0:

        if dir.x > 0:
            facing = direction.RIGHT
        elif dir.x < 0:
            facing = direction.LEFT
        elif dir.y < 0:
            facing = direction.UP
        elif dir.y > 0:
            facing = direction.DOWN

        moving = true
        initpos = position

func get_dir(): #user input
    velocity = Vector2()

    var v_input = (Vector2(ei.move_h, ei.move_v))
    var v_angle = v_input.angle()
    var v_length = 1
    #for game_pad
#   var v_length = v_input.length()
    if(ei.move_h != 0 or ei.move_v != 0):
        velocity += Vector2(speed * v_length, 0).rotated(v_angle)
        velocity.x = round(velocity.x)
        velocity.y = round(velocity.y)

    return velocity

func move(delta): # move the player linearly

    var collision = move_and_slide(velocity)
#add guided missle attack
#returns bool

func attack(delta):
    attack_type = 1

    match attack_type:
        0:
            return stab(delta)
        1:
            return swing(delta)

    return false

func stab(delta):
    if(!attacking and ei.attack):

        if($Sword):
            attack_counter = max_attack_counter
            attacking = true
            attack_rotation = $Sword.rotation
            if(is_in_group("Player")):
                $Sword.set_collision_mask_bit(2, true)

    if(attacking):
        var collision_info = $Sword.move_and_collide(Vector2(attack_speed, 0).rotated(attack_rotation + rotation) * delta)
        if(attack_counter > 0 and !collision_info):
                attack_counter -= delta

        else:
            attack_counter = 0
            attacking = false
            $Sword.position.x = sword_init_x
            $Sword.position.y = sword_init_y
            $Sword.set_collision_mask_bit(2, false)

        return true
    return false
#Must return bool
func swing(delta):
    #Start Attack
    if(!attacking and ei.attack):

        if($Sword):
            attack_counter = max_attack_counter
            attacking = true

            if(is_in_group("Player")):
                $Sword.set_collision_mask_bit(2, true)

    #When attacking
    if(attacking):
        $Sword.rotation += attack_rotation_speed * delta/one_sec
        var collision_info = $Sword.move_and_collide(Vector2())
        if(attack_counter > 0 and !collision_info):
                attack_counter -= delta

        else:
            attack_counter = 0
            attacking = false
            $Sword.position.x = sword_init_x
            $Sword.position.y = sword_init_y
            $Sword.set_collision_mask_bit(2, false)
        return true
    return false

func get_input():
    pass

func use_input():
#   if(ei.jump and !jumping):
#       jumping = false
#       set_collision_mask_bit(0, false)
#       set_collision_mask_bit(1, true)
#       set_collision_layer_bit(0, false)
    pass

```

Here is where I want to rotate the sword the amount that I set with the attack\_rotation\_speed but unless I divide delta by 60 it goes to fast. I don't like using magic constants but I don't know why it doesn't work.

```
    #When attacking
    if(attacking):
        $Sword.rotation += attack_rotation_speed * delta/one_sec
        var collision_info = $Sword.move_and_collide(Vector2())
        if(attack_counter > 0 and !collision_info):
                attack_counter -= delta

```

# Answer
Solved the problem, godot uses radians instead of degrees, that's what was causing my issues. So if in the code:

```
#When attacking
if(attacking):
    $Sword.rotation += attack_rotation_speed * delta/one_sec
    var collision_info = $Sword.move_and_collide(Vector2())
    if(attack_counter > 0 and !collision_info):
            attack_counter -= delta

```

I remove /onesec from it and for attack\_rotation\_speed I use radians instead of degrees.
> 1 votes

---
Tags: godot
---


# Question
Title: How would I implement render scaling in a DX11 game?
I would like to implement render scaling that could render a scene at a certain % of the window resolution. How would I do this? I've tried resizing a number of things, then resizing them up or down to match the window size but I've never gotten it to work.

# Answer
> 1 votes
The most obvious one and probably most hacky is to:

1 - Create your rendertarget at the % of the screen size (MSAA or NON MSAA)

2 - Create a transition Rendertarget at the windowsize (NON MSAA) I advise NON MSAA as you then don't have to use the more expensive ResolveSubResource call.

3 - Upon completion of your rendering to your rendertarget, use this as a source texture for your rendering to a fullscreen quad into your NON MSAA transition target.

4 - Copy the resource into your swap buffer.

You could do a fullscreen quad straight to the swap buffer, but I cant remember if that means you can not utilise SWAP\_SEQUENTIAL or SWAP\_DISCARD.

---
Tags: directx11
---


# Question
Title: Unity: How do I only show parts of objects that overlap [2D]
I'm working on a 2D Unity project where the player can only see objects in their field of view. I have successfully created a mesh that overlaps anything that would be in the player's field of view, but now I'm having trouble with only showing parts of objects that the mesh overlaps with.

Here is what I have so far (the gray area is the player's field of view which is a mesh:

Here is the type of thing that I'm looking for:

What can I do to get that desired effect? Shaders (I have no clue how to use shaders)? Colliders? Any ideas would be greatly appreciated. If there is any info you need that I didn't provide, comment and I add the necessary info. Thank you in advance!

# Answer
> 5 votes
First, create a simple mesh (such as a quad or a cube). Place it over top the actual game area, and stretch it so that it covers the entire camera view.

Next, create a new shader named "ObscurityShader", and paste in the following shader code:

```
Shader "Custom/ObscurityShader"
{
    SubShader
    {
        Tags{"Queue" = "Transparent+1" "RenderType" = "Transparent"}

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            struct appdata
            {
                float4 vertex : POSITION;
            };

            struct v2f
            {
                float4 pos : SV_POSITION;
            };

            v2f vert(appdata v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                return o;
            }

            half4 frag(v2f i) : SV_Target
            {
                return 0;
            }
            ENDCG
        }
    }
}

```

Everything inside "Pass" is just a bare-bones vertex/fragment shader. The most important part for us is the "Tags" at the top of the code.

Now create a new material and set it to use ObscurityShader. Select the mesh we made earlier and set it to use this material.

Next, create a second shader named "VisibilityShader", and paste in the following shader code:

```
Shader "Custom/VisibilityShader"
{
    SubShader
    {
        Tags{"Queue" = "Transparent" "RenderType" = "Transparent"}
        ColorMask 0

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            struct appdata
            {
                float4 vertex : POSITION;
            };

            struct v2f
            {
                float4 pos : SV_POSITION;
            };

            v2f vert(appdata v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                return o;
            }

            half4 frag(v2f i) : SV_Target
            {
                return 0;
            }
            ENDCG
        }
    }
}

```

Note that this shader is near-identical to the first, with two small differences:

1. The rendering queue is "Transparent" rather than "Transparent+1", ensuring VisibilityShader is rendered before ObscurityShader.
2. We use ColorMask 0, which essentially sets an invisible pixel that the ObscurityShader doesn't overwrite.

Create a new material and set it to use VisibilityShader. Set your "visible area" mesh to use this material.

Finally, set your "visible area" mesh to sit above the obscuring mesh, and you should see a hole in the black void in the shape of your visibility mesh!

---
Tags: unity, 2d, shaders, mesh, materials
---


# Question
Title: How to Design a Generic Collision Detection System?
I'm designing a C++ 2D collision module, and I ran into a problem designing a system where the collider is unaware of the shape it's colliding against.

I'd like to have a abstract base class called Collision Component and the subclasses define the specific shape (circle, rectangle, polygon, etc...).

The Quad tree and Axis Aligned Bounding Box checks are fine. The difficulty I ran into is when I'm calculating intersection tests. I don't know how to define a function in the parent class similar to this:

```
bool CollisionComponent::IsIntersecting(CollisionComponent* other);

```

The easiest approach is to cast other to specific subclasses and invoke overloaded functions:

```
bool IsIntersecting(const Circle& a, const Circle& b);
bool IsIntersecting(const Rectangle& a, const Circle& b);
bool IsIntersecting(const Line& a, const Circle& b);
// on and on

```

I prefer not to implement functions this way.

I thought of breaking down polygons to its elements, and pass an array of segments into a function.

```
bool IsIntersecting(const std::vector<Line>& relevantSegments);

```

Although this would be more robust, I feel like this is more expensive, and I may lose precision when interpreting curves as polygons. This approach seems to be the best so far though since I can probably optimize it for complicated shapes.

Another approach I've considered was to find the closest point to the center of the other shape, and test if the shape encompasses the point. Unfortunately, this runs into issues with concave polygons, and cases where the shapes are barely clipping at the edges such as this example:

```
*------------------------------*
|                              |
|             C                |
|                            __+--*
*-------------------x-____-----* /
                ___---          /
          ___-x-               /
    ___---          C         /
_---                         /
                            /
---------------------------*

/*
C = center
* = vertex
x = point on shape that's closest to the other shape's center
*/

```

I feel like this problem was solved before, but my reading material doesn't cover this. How do I design a collision system where the base class does not care about specific shapes?

# Answer
> 1 votes
It doesn't get more general than checking Lines (possibly building curves out of sectors). The problem with just getting a bunch of lines is being able to tell if you're on the inside (no intersections).

In my previous experience with creating a collision detection system we went down the 'overloaded functions' approach.

1. Because it's easy
2. A number of shapes have short-cut maths on collision detection. (Eg: `IsIntersecting(Circle, Circle)` will be faster than the more general `IsIntersecting(Sector, Sector)`)
3. It's a form of generalized collision system

Most of the shape you'll use can probably be represented as one or more circles, quads, or triangles.

Eg. a car may be 2 circles, and a couple of squares and triangles:

```
    ______
___/|    |\___
---()----()---

```

Following some other component-driven game engine examples, we made our game support multiple collision shapes per entity.

If the intersection shape is useful to you, you could make a function to return a manifold structure, which contains the points of contact for any shape:

```
if (IsIntersecting(Shape, Shape)) {
    Manifold = GetManifold(Shape, Shape);
    /* Use manifold for something */
}

```

---
Tags: c++, collision-detection, architecture
---


# Question
Title: Rotating 2D positions without rotating graphics
I am working on a basic 2D game from an overhead/fake isometric perspective. Arrow keys move the camera left/right/up/down. The trouble occurs when I tried to add *rotation*.

I want the player to be able to rotate the camera (or map?) around the camera's center. The sprite positions should move during the rotation, but the sprite graphics should not rotate. For example, the sprites will always point "up" even as their position rotates around the screen.

I thought this was would be easy. Just keep track of the X, Y, and rotation of the camera. However, I am having some issues. Here is a snippet of my code (Go with the Pixel 2d library):

```
if win.Pressed(pixelgl.Key1) {
    camRot += camRotSpeed * dt
}
if win.Pressed(pixelgl.KeyLeft) {
    camX += camSpeed * dt
}
// similar for other key presses...

// Draw objects
for i, entity := range entities {
    sin := math.Sin(camRot)
    cos := math.Cos(camRot)
    adjustedCamX := camX*cos - camY*sin
    adjustedCamY := camX*sin + camY*cos
    adjustedMatrix := matrices[i].Moved(pixel.V(camX, camY)).Moved(pixel.V(adjustedCamX, adjustedCamY))
    entity.Draw(win, adjustedMatrix)
}

```

There are two issues: (1) after rotating, using the arrow keys now moves the camera at an angle instead of up/down/left/right and (2) I do not know how to rotate around the screen's center rather than whatever the current orientation is (0,0 in the bottom left?).

Note: The Pixel library makes use of transformation matrices rather than pure coordinates. At first I thought this was good (I can just do a rotation on the entire screen!) but then the graphics rotate as well. As such, I just try to emulate using pure coordinates and ignore the matrix (see the line with adjustedMatrix, the matrices\[i\] is just that entities' X Y position).

An example of what I am trying to achieve can be seen in the first few seconds of this video

# Answer
> 1 votes
Now that you've disconnected the Modelview/Projection coordinates from the World coordinates, you have to put the camera rotation back when you move the character (to have them move relative to the camera instead of the world).

This is accomplished by extending your movement from:

```
if win.Pressed(pixelgl.KeyLeft) {
    camX += camSpeed * dt
}

```

to

```
if win.Pressed(pixelgl.KeyLeft) {
    camX += camSpeed * dt * cos(camRot)
    camY += camSpeed * dt * sin(camRot)
}

```

The up/down will swap which cos/sin is used for x/y.

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


# Question
Title: Circle to Circle Collision of moving Sprites
i needed help attaching circle1 Sprite to circle2 Sprite on collision onto the same point where they are getting collided, and both circles are moving with Action. Like this,

Attaching means, when circle1 and circle2 sprites get collided, i am removing circle1 Sprite from scene and creating new sprite at that same position of circle1.

I have implemented following code for collision .... float dx = circle1.x - circle2.x; float dy = circle1.y - circle2.y; float distance = Math.sqrt(dx * dx + dy * dy);

if (distance \< circle1.radius + circle2.radius) { // collision detected // removing older sprite // creating of new sprite }

Its working perfectly when one circle sprite in motion and another is static.

But when both are in motion, at some points ( collision point like bottom-left/ up-right of circle2 ) its get attached little over circle2 sprite and it happens at random times so i couldn't able to detect the error.

I want to attach new Sprite at exact point where collision occurred like this,

Anybody have done it before..

# Answer
The problem you're encountering is common during collision resolution in physics systems.

You'll need to do some collision penetration resolution before you start removing/creating sprites.

This usually means finding how much the two objects overlap:
`penetration = (player.position - enemy.position).length() + abs(player.radius - enemy.radius)`
Then move them away from each other:
`player.position += (player.position - enemy.position).unit() * penetration * 0.5
enemy.position -= (player.position - enemy.position).unit() * penetration * 0.5`

I assume that player and enemy's position is a Vector3 with length and unit functions. You may have to adjust who is += and -=. Also, you have an abs function somewhere.

The 0.5 will move both objects away 50% of the distance, this is usually adjusted to reflect the relative weight of each object (eg. `player.weight / (player.weight + enemy.weight`).
> 0 votes

---
Tags: c++, cocos2d-x
---


# Question
Title: Separating game logic and rendering logic in separate static libraries
I'm trying to write a game in C++ using OpenGL. I've tried to separate my game logic and my rendering logic as much as possible, and up until now, this has worked for me. I haven't written a lot of code, and right now, I'm getting to the point where I have all my separate parts, and I'm trying to put them together.

In order to keep game and rendering logic separated, I've written them both in separate static libraries (So I have a `libCore` and a `libRendering`. There's also a third static library that contains code that is shared between the two libraries (Things like utility methods for reading files, custom exceptions, ...), this library is called `libShared`. Both of my libraries (`libCore` and `libRendering`) are first linked against `libShared` and then the game executable is linked against `libCore` and `libRendering`.

I've been using an entity-component-system (Which is part of `libCore`) to keep track of all my entities, now I'd like to introduce a `RenderingComponent` which contains all the data necessary for actually rendering an object (Things like VAO's, VBO's, Textures, Normal Maps, ...).

The problem is, that doing this would bring part of the rendering code into the game logic code. And I'm wondering what the best course of action would be here.

Should I move the ECS into `libShared`?

Should I just create a single `libEngine` that I can link my game against, instead of 3 different libraries?

Do you have any other solutions?

*Note: I do realize that separation of game and rendering logic has been discussed before, my question is specifically about the architecture of the various libraries I have layed out in this question, and other peoples' opionions on it.*

To clarify what I mean, here's what my CMakeLists.txt looks like (They're actually separate files, but I'll keep them together for simplicity's sake).

```
...

add_library(Shared ${SHARED_HEADER_FILES} ${SHARED_SOURCE_FILES})

...

add_library(Rendering ${RENDERING_HEADER_FILES} ${RENDERING_SOURCE_FILES})
target_link_libraries(Rendering Shared ${OPENGL_LIBRARIES} ${GLEW_LIBRARIES} ${GLFW_LIBRARY})

...

add_library(Core ${CORE_HEADER_FILES} ${CORE_SOURCE_FILES})
target_link_libraries(Core Shared ${LUA_LIBRARIES})

...

add_executable(Game ${GAME_HEADER_FILES} ${GAME_SOURCE_FILES} src/main.cpp)
target_link_libraries(Game Core Rendering)

```

*Second Note: If this is better suited for Code Review or Software Engineering StackExchange, I'll happily move my question over there.*

# Answer
It depends on where you want the `RenderingComponent` to live. If `RenderingComponent` is itself part of the *rendering* code, then you are asserting the rendering code depends on (and is thus aware of) the entity system. This means the layers of abstraction in your code should look like (`A > B` indicating that `A` is "higher level" than `B`; `A` can see and make use of `B`, but generally not the other way around):

```
Gameplay Logic > Rendering > Entity System > Shared Core Stuff

```

If, on the other hand, you want the `RenderingComponent` to be a part of the entity system, the entity system has to be aware of the rendering system to implement this. So your abstraction layers should end up like:

```
Gameplay Logic > Entity System > Rendering > Shared Core Stuff

```

Either is approach is fine (it's perfectly fine for gameplay or other high-level stuff to understand the *idea* that they will be drawn, you just don't want them directly handling the actual drawing; the component would contain the references to the rendering primitives required of your rendering library to draw the relevant data).

I would generally advocate for the latter approach, where whatever entity system you're using is a high-level system that may have components that just *wrap* lower level functionality (rendering, physics, audio, et cetera) to provide the functionality of those lower-level systems in "entity ready" form. I suspect this will also be a more direct solution for you, as opposed to the first option which sounds like it might involve moving your entity system down a few levels of abstraction and thus decoupling it from other high-level gameplay code.

---

As for your query about one static library versus many... that's largely up to you, it's orthogonal to the design issue (generally speaking). I would advocate for a single monolithic static library unless you *seriously* plan to mix-and-match the smaller static libraries. In practice I suspect you will not, and so the overhead of working in one "engine library" is smaller and more digestible for you.
> 0 votes

---
Tags: opengl, c++, architecture, build-process
---


# Question
Title: why is my mesh black in blender even though the color is set to white
I set my mesh black then wanted to set it back to white but can't. How do i do it ?

# Answer
> 1 votes
This would be clearer to answer if you also showed the material tab in the properties window, but it could be that you've changed the ViewPort Display Color to black, which overrides the material color when you're not in rendered view mode.

# Answer
> 1 votes
It could be that your normals are backword try recalculating them.

Select your object and use ctrl + N.

---
Tags: blender
---


# Question
Title: Only make camera follow player on x axis?
I need a script to make the camera follow the player but only on the x axis so its like mario where when I jump the camera doesnt go up.

# Answer
> 3 votes
Attach a new script to the camera and add something like this:

```
public Transform targetTransform;
Vector3 tempVec3 = new Vector3();

LateUpdate() {
    tempVec3.x = targetTransform.position.x;
    tempVec3.y = this.transform.position.y;
    tempVec3.z = this.transform.position.z;
    this.transform.position = tempVec3;
}

```

Set the `targetTransform` in the inspector to the player object.

It's using `LateUpdate` so that the position is updated after the player position has been updated. And it's using a local `tempVec3` variable so you're not creating a new Vector3 every frame.

# Answer
> 0 votes
Here is the simplest way I could think of. Attach below to the camera

```
//define player game object
public GameObject player;

//wait for lateupdate
void LateUpdate()
  {
   transform.position = new Vector3(player.transform.position.x, 0f, -10f);
  }
}

```

You can adjust your y and z values to your actual needs to hold the camera on those axis. You can also attach an if statement to stop following after x reaches a certain value. E.G. at end of the level where you don't want the camera to go past a certain point.

```
//define player game object
public GameObject player;

//wait for lateupdate
void LateUpdate()
  {
   //define start and end of level.
   //This will detach the camera from the player until it enters the range again

     if(player.transform.position.x > 0f && player.transform.position.x < 10f)
     {
         transform.position = new Vector3(player.transform.position.x, 0f, -10f);
     }
   }
}

```

# Answer
> 0 votes
I personally like to not attach the camera object to the player directly. Instead of that I write a CameraController script which references the player and corrects the position of the camera in its `Update` method. This allows you to do things like lazy scrolling (don't scroll until the player gets close to the screen border), smooth scrolling (dampen the camera movement so erratic player movements do not translate to camera shaking) or temporarily take control of the camera and have it focus on something else.

Following the player on just one axis is another use-case for such a script.

# Answer
> -2 votes
This is the easiest way i think,

```
public Transform player;

void Update () {

transform.position = new Vector2(player.position.x, 0f);

```

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


# Question
Title: What is "mapping seams" and "hard edges (doubled-up vertices)" in UV?
According to GPU: Optimizing model geometry:

> Try to keep the number of UV mapping seams and hard edges (doubled-up vertices) as low as possible

What is "mapping seams" and "hard edges (doubled-up vertices)"? Can someone point it out with image (use software like Maya/3Ds Max/Blender)?

---

Here are my guesses, but I don't know if my guesses are right:

I guess "mapping seams" is the "UV edge"

But I think it doesn't make sense when they said keep the number of UV edges as low as possible, of course I can't reduce the number of edges in my model, so I don't know what is "mapping seams".

About "hard edges (doubled-up vertices)", I guess it's double edge overlap each other by human's accident.

# Answer
Inside the GPU pipeline, each vertex represents a unique combination of:

* a position (so we know where to draw this corner of the adjacent polygon(s) on the screen)
* a normal vector (which way the surface is facing at this point, so we can light & shade the attached polygons accordingly)
* texture coordinates (so we know which part of the texture to sample for this part of the surface)

If multiple polygons share one of these GPU vertices, they share all of the above. That means:

* shared position: the polygons will meet at exactly the same corner. When both vertices along an edge are shared in this way, the result is a "watertight" join between the polygons, with no crack or gap in-between them.
* shared normal: the polygons will have the same shading at this corner. When both vertices along an edge are shared in this way, the result is a "smooth" edge, where the lighting is flat or a smooth gradient across the edge, rather than a "hard edge" that shows a sharp crease between darker and lighter shaded polygons.
* shared texture coordinates: the polygons will reference the same part of the texture at this corner. When both vertices along an edge are shared in this way, the texture will wrap continuously across this edge, with no discontinuity or "seam" where different parts of the texture butt up against each other.

We don't always want all of the above though. Consider this image of a texture mapped cube by Zephyris, via Wikipedia:

Here we can see as we unwrap the cube onto the flat plane of texture space, we have to cut it along certain edges (making a "net" we can unfold flat). Some faces of the cube that meet at the same place in 3D space end up sitting in very different parts of the flattened texture space (like the two far edges of the cross). That's a texture discontinuity, called a "seam" (by analogy with sewing, where to make this cube out of a sheet of fabric, we'd have to stitch-together these cut edges).

In 3D modelling software, the vertices on both sides of a texture seam corner are commonly still counted as "one" vertex, that just happens to have different texture coordinates associated with it on each face. When exporting to a game's GPU pipeline though, these vertices get split into separate copies: one with the texture coordinates for the faces on one side of the seam, one with the texture coordinates for the faces on the other side of the seam (and the other, and the other, for vertices at the meeting point of several seams)

This has a slight overhead, since it's increasing the vertex count of the model, meaning more data to transfer to the GPU and process when rendering. So that's why you'll find some guides recommending to minimize cases where you need to split vertices in this way. Avoiding unnecessary seams also helps when painting the texture, as it cuts down on places where the artist needs to match the texture on one edge to that on another edge elsewhere in the texture to avoid visible seams, or where mipmapping can cause unwanted colour leaks.

The same thing happens wherever we want a "hard" edge, where the shading changes sharply On the cube above, all six faces point in different directions, with hard edges in between. So we'd need to split every corner vertex to provide a different normal vector for each of the three faces that meet there. So in the 3D modelling program it might look like we have 8 vertices, but we actually end up sending 24 down the rendering pipeline.

This overhead is quite minor compared to other costs in the rendering pipeline, so it's not something you need to go out of your way to avoid entirely. Every textured 3D object that isn't just a mostly-flat sheet will need a texture seam somewhere, so it's usually just a matter of choosing where to put it to make your texture artists' lives easier. ;)
> 4 votes

# Answer
When you have mapping seams, there are 2 texture coordinates in one position to make sure the triangles lie on completely different parts of the UV coordinate system. Since you can't do that normally, you have to cut the model at that edge and duplicate the vertices. They'll have the same position and nornal, but different UV coordinates.

Hard edges are almost the same, except it aims to separate the normals. This is required to achieve that usual low-poly style, since if the normals weren't separated, the lighting would be very smooth.

So the only real reason you need to avoid this is because it's just more data to push to the GPU, but since these techniques are mandatory for some effects you really shouldn't care about it that much.
> 1 votes

# Answer
Thank DMGregory for the detailed answer. But I like to explain it visually, I think it's best to read the answer of DMGregory first and check the visual explain below.

## 1. Mapping seams

## 2. Hard edges
> 1 votes

---
Tags: terminology, uv-mapping, 3d-modeling
---


title: How to use a .mtl file in Unity?

text:
# Question
Title: How to use a .mtl file in Unity?
I want to use a .mtl file to draw my objects in unity. Can I somehow convert a .mtl file into a normal Unity material?

My .mtl file is like this:

```
newmtl phongE1SG
illum 4
Kd 0.00 1.00 0.00
Ka 0.00 0.00 0.00
Tf 1.00 1.00 1.00
Ni 1.00
Ks 0.50 0.50 0.50

```

Is this the same as a Unity material which has the sliders "albedo", "metallic", "smoothness", etc?

Or is there any shader to do it?

# Answer
Yes. You can use `.mtl` file directly to create a material and apply a texture, used in unity. (Yet I have only tested it on `.obj` files).

For example: Just create `Cube.obj` or take any `.obj` file. Edit the .obj file in any `TextEditor` and get the `Material name` used in the object,.

Then create a `.mtl` file and assign whatever value you want, like `color`, `texture map`, etc.

If you still don't understand it, comment here. I will make a video to help you understand.
> 0 votes

---
Tags: unity, shaders
---


# Question
Title: I can add event animation but I can't add keyframe?
I am trying to add animation to my UI panel but the problem is I can't add a keyframe to my animation (the button is grayed out). But I can add event animation (the button is not grayed out).

Here is the video of what's happening. Anyone know how I can resolve my problem?

# Answer
Try adding a property first. Then you will be able to keyframe that property.
> 1 votes

---
Tags: unity, animation
---


# Question
Title: Changing CharacterController's height causes jittering issue in Unity
As title said changing height of Character Controller causes jittering issue.

For example when I reduced the height of CharacterController, it seems CharacterController was floating at each frame and it keeps falling to the ground. Opposite situation has same issue, different is collider is actually already passing the ground so it just push up the object by physics engine.

(I saw some similar issue with Terrain, in this case it's worse, it just falling through the terrain)

Anyway someone told that I have to change center of CharacterController too, with foot offset(I don't know what exactly that is), so I tried to change the center of CharacterController when resizing height but it still have same problem, nothing different.

This is the code that I'm using:

```
void Update() {
    if(Input.GetKeyDown(KeyCode.LeftControl)) {
        isCrouched = !isCrouched;
    }

    float newHeight = isCrouched ? crouchingHeight : originalHeight;
    controller.height = Mathf.Lerp(controller.height, newHeight, Time.deltaTime * smooth);

    Vector3 newCenter = isCrouched ? new Vector3(0, 0.2f, 0) : Vector3.zero;
    controller.center = Vector3.Lerp(controller.center, newCenter, Time.deltaTime * smooth);

    float newCamPos = isCrouched ? origCamPos.y - 0.2f : origCamPos.y;
    Vector3 newPos = new Vector3(cam.localPosition.x, newCamPos, cam.localPosition.z);

    cam.localPosition = Vector3.Lerp(cam.localPosition, newPos, Time.deltaTime * smooth);
}

```

Is there a way to rid off that jittering issue while changing height of Character Controller? Any advice will very appreciate it.

# Answer
I'm assuming this is the issue you're having:

You can fix this by offsetting the CharacterController's center so that the bottom of the collider is always at the foot of your character. Specifically, you vertically offset the center by the difference between `originalHeight` and the current height, divided by two.

In your code, replace:

```
Vector3 newCenter = isCrouched ? new Vector3(0, 0.2f, 0) : Vector3.zero;
controller.center = Vector3.Lerp(controller.center, newCenter, Time.deltaTime * smooth);

```

with:

`controller.center = Vector3.down * (originalHeight - controller.height) / 2.0f;`

And this is the result:
> 3 votes

---
Tags: unity, physics, collider
---


# Question
Title: Enter in a match that is already started
In my Unity mobile game, I need multiplayer online functionalities. All the players should be visible in the world at any given time (of course, with some filtering), and a player should be able to connect at any time. Let's say that, for the purpose of this question, only 100 players at the time will log into the game.

My first try involved using Unity's built-in `NetworkManager`, but the two problems that arose are that:

1. One player is always the host, meaning that if that player logs out all the other players.
2. I did not manage to make it work on two different networks.

The implementation I used comes from this tutorial.

Next try was using an extension of `NetworkLobbyManager`, that allows through the Matchmaking system to solve problem 2.

This is my implementation:

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

public class AutoLobbyManager : NetworkLobbyManager {

    protected int currentPage = 0;
    protected int previousPage = 0;

    public void CreateOrJoin() {
        StartMatchMaker();
        RequestPage(0);
    }

    public void OnMatchListReceived(bool success, string extendedInfo, List<MatchInfoSnapshot> matches)
    {
        if (matches.Count == 0) {
            // Server does not exist yet. Create one.
            CreateMatch();
            return;
        }

        // There is then a server. Join it.
        JoinMatch(matches[0]);

    }

    public void RequestPage(int page) {
        matchMaker.ListMatches(page, 1, "", true, 0, 0, OnMatchListReceived);
    }

    public void CreateMatch() {
        matchMaker.CreateMatch( "Main Match", (uint)maxPlayers, true, "", "", "", 0, 0, OnMatchCreate);
    }

    void JoinMatch(MatchInfoSnapshot match) {
        matchMaker.JoinMatch(match.networkId, "", "", "", 0, 0, OnMatchJoined);
    }

    public override void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo) {
        base.OnMatchCreate(success, extendedInfo, matchInfo);
        Debug.Log("Match created!");
        ServerChangeScene(playScene);
    }

     public override void OnClientSceneChanged(NetworkConnection conn) {
         string loadedSceneName = SceneManager.GetSceneAt(0).name;
         if (loadedSceneName == lobbyScene) {
           if (client.isConnected)
               CallOnClientEnterLobby();
         } else {
           CallOnClientExitLobby();
         }

         OnLobbyClientSceneChanged(conn);
    }

    void CallOnClientEnterLobby() {
        OnLobbyClientEnter();
        foreach (var player in lobbySlots)
        {
            if (player == null)
                continue;

            player.readyToBegin = false;
            player.OnClientEnterLobby();
        }
    }

    void CallOnClientExitLobby() {
        OnLobbyClientExit();
        foreach (var player in lobbySlots)
        {
            if (player == null)
                continue;

            player.OnClientExitLobby();
        }
    }

}

```

This makes possible to create a Lobby if there is no Lobby, and join the first if there is. It works, if we remove the highlighted line here:

```
public override void OnMatchCreate(bool success, string extendedInfo,
MatchInfo matchInfo) {
    base.OnMatchCreate(success, extendedInfo, matchInfo);
    Debug.Log("Match created!");
    ***** ServerChangeScene(playScene); *****
}

```

Because this starts the game. If that line is activated (since I want to start the game as soon as possible), when a client tries to connect, the Server logs:

```
NetworkLobbyManager can't accept new connection [hostId: 0 connectionId: 1 isReady: False channel count: 2], not in lobby and game already in progress.

```

And the client is not added to the game. I understand that lobbies *usually* work like that, but:

**1. Is it possible to add a client after a game is added, with `NetworkLobbyManager`?**

**2. Is it the right approach to achieve a multiplayer, non-lobby-based, non-host-based, online game in Unity?**

# Answer
> 1 votes
First and foremost no, you may not add players to an already started game with lobbies because they were designed to host short term games with a set number of players. Because of the rigid structur they can simplify the code they use, but as you noticed it does restrict its use a fair bit.

I would suggest looking into the parent class of the network lobby manager, the network manager, directly as it seems to have all the pieces needed for you to make a system of the type you desire, although it may require a bit more work.

That being said the unity asset store is wide and I would not be surprised to hear that there is a premade system that works the way you intend.

---
Tags: unity, unity-networking
---


# Question
Title: Welzl Algorithm to find the Smallest Bounding Sphere
I'm implementing Welzl's Algorithm to find the Smallest Bounding Sphere.

In brief, the algorithm works by maintaining:

* a set of points to contain in the sphere (inside its interior, or on its boundary)
* a set of points known to be on the boundary of the sphere (the "set of support")

It works recursively, starting with the full set of points in the contained set and no boundary points in the set of support. At each level, it tries removing a point from the contained set, and recursively finding the minimal bounding sphere of this reduced set (with the current set of support).

* If the removed point is in/on the resulting sphere, then it returns that result up the recursive chain.
* If not, then the removed point must be on the boundary of the minimal bounding sphere, so it adds it to the set of support and recurses again.

Once it boils down to no remaining contained points or 4 boundary points, the recursion bottoms-out and returns an explicitly calculated sphere based on the boundary points found.

---

I'm not sure of a few details of the implementation, and haven't found on the net the answer to my questions :

* How can I construct a sphere is uniquely defined by four (non co-planar) points?
* Do I have to check in the algorithm if these four points are non co-planar?
* I used the barycenter (centroid) of the boundary points in by set of support when the number such points is three or more. Is that correct ?
* My algorithm may fall into cases with more than four boundary points in the set of support, so I had to add a `default` case to handle this - is this normal?

Here's my current code:

```
Sphere ComputeMinimalBoundingShpere(glm::vec3*              points,
                                    std::size_t             numberPoints,
                                    std::vector<glm::vec3>& sos,
                                    std::size_t             numberSos)
{
  // Stop the recursion when we have no more points
  // Or the number of support is more than three
  if (numberPoints == 0 || numberSos >= 4) {
    switch (numberSos) {
      case 0: return Sphere();
      case 1: return Sphere(sos[0], 0.000f);
      case 2: {
        const glm::vec3 center = (sos[1] - sos[0]) * 0.5f;
        return Sphere(center, glm::length(center) * 0.5f);
      };
      case 3: {
      // If we have three points: Look for the barycenter
        const glm::vec3& A = sos[0];
        const glm::vec3& B = sos[1];
        const glm::vec3& C = sos[2];
        const float      v = 1.0f / 3.0f;
        const float      w = 1.0f / 3.0f;

        const glm::vec3 P      = ((1 - v - w) * A) + v * B + w * C;
        const float     radius = glm::length(P - A);
        return Sphere(P, radius);
      };
      case 4: {
      // If we have four points: Look for the barycenter
        const glm::vec3& A = sos[0];
        const glm::vec3& B = sos[1];
        const glm::vec3& C = sos[2];
        const glm::vec3& D = sos[3];
        const float      v = 0.25f;
        const float      w = 0.25f;
        const float      x = 0.25f;

        const glm::vec3 P = ((1 - v - w - x) * A) + v * B + w * C + x * D;
        const float     radius = glm::length(P - A);
        return Sphere(P, radius);
      };
      default:
        assert(false && "We cannot have more than four Set of Support");
    }
  }

  const int    indexPoint = numberPoints - 1;
  const Sphere smallestSphere =
    ComputeMinimalBoundingShpere(points, numberPoints - 1, sos, numberSos);
  if (smallestSphere.contains(points[indexPoint])) { return smallestSphere; }

  sos[numberSos] = points[indexPoint];
  return ComputeMinimalBoundingShpere(points, numberPoints - 1, sos,
                                      numberSos + 1);
}

```

# Answer
> 4 votes
Your base cases for 2, 3, and 4 boundary points are incorrect.

* For two boundary points, you want the center to be half the *sum* of the two boundary points (ie. their average), not half their difference. The radius will be half the length of their difference, not a quarter. We can adjust your code as follows:

```
const glm::vec3 halfSpan = (sos[1] - sos[0]) * 0.5f;
return Sphere(sos[0] + halfSpan, glm::length(halfSpan));
```
* For three boundary points, you want the circumcenter of the triangle, not the centroid as you're computing now. Using the formulas given on Wikipedia here, we can write:

$$\begin{align} a &= sos\[1\] - sos\[0\]\\ b &= sos\[2\] - sos\[0\]\\ c &= sos\[0\]\\ \\ center &= \frac {\left(\\|a\\|^2 b - \\|b\\|^2 a \right) \times \left( a \times b \right)}{2 \\|a \times b\\|^2} + c \end{align}$$

It is not normal for the algorithm to try to add more than four boundary points to the set of support. Since we only ever add one boundary point at a time, if a particular invocation of the method tries to add a fifth boundary point, then it must have itself been called with four, which means it would have fallen into the 4-boundary-point base case above and returned a circumsphere of those four points without any attempt at a further recursive call.

You do not need to check whether the 4 boundary points are co-planar. If we try to add a point to our set of support, then that means we already checked and found the minimal sphere containing the rest of the set does not contain that point. This can be true of at most three points on any given plane. Of any set of four points on a plane, one must be inside or on the circumcircle defined by the other three, and so already contained in any sphere containing the other three.

Also, note that the algorithm is designed to work by removing a random point from the set in each recursion. If you make this selection non-randomly, in a fixed order as you're doing here, then the performance characteristics proven in Welzl's paper may no longer apply, and on pathological data you could get runtimes much longer than expected.

---

Edit: Here's a working C# implementation I wrote up to understand the algorithm. I know you're using C++, but this should help disambiguate some of the details.

```
public static BoundingBall GetBoundingBall(List<Vector3> points) {
    if (_boundaryPoints == null)
        _boundaryPoints = new List<Vector3>(4);
    else
        _boundaryPoints.Clear();

    return BallWithBounds(points);
}

static BoundingBall BallWithBounds(List<Vector3> contained) {
    if (contained.Count == 0 || _boundaryPoints.Count == 4) {
        switch (_boundaryPoints.Count) {
            case 0:
                return BoundingBall.EMPTY;
            case 1:
                return new BoundingBall(_boundaryPoints[0], 0);
            case 2:
                var halfSpan = 0.5f * (_boundaryPoints[1] - _boundaryPoints[0]);
                return new BoundingBall(
                         _boundaryPoints[0] + halfSpan,
                         halfSpan.magnitude
                );
            case 3:
                return TriangleCircumSphere(
                         _boundaryPoints[0],
                         _boundaryPoints[1],
                         _boundaryPoints[2]
                );
            case 4:
                return TetrahedronCircumSphere(
                         _boundaryPoints[0],
                         _boundaryPoints[1],
                         _boundaryPoints[2],
                         _boundaryPoints[3]
                );
        }
    }

    int last = contained.Count - 1;
    int removeAt = Random.Range(0, contained.Count);

    Vector3 removed = contained[removeAt];
    contained[removeAt] = contained[last];
    contained.RemoveAt(last);

    var ball = BallWithBounds(contained);

    if(!ball.Contains(removed)) {
        _boundaryPoints.Add(removed);
        ball = BallWithBounds(contained);
        _boundaryPoints.RemoveAt(_boundaryPoints.Count - 1);
    }

    contained.Add(removed);
    return ball;
}

static BoundingBall TriangleCircumSphere(Vector3 a, Vector3 b, Vector3 c) {
    Vector3 A = a - c;
    Vector3 B = b - c;

    Vector3 cross = Vector3.Cross(A, B);

    Vector3 center = c + Vector3.Cross(A.sqrMagnitude * B - B.sqrMagnitude * A, cross)
                   / (2f * cross.sqrMagnitude);

    float radius = Vector3.Distance(a, center);

    return new BoundingBall(center, radius);
}

static BoundingBall TetrahedronCircumSphere(
          Vector3 p1,
          Vector3 p2,
          Vector3 p3,
          Vector3 p4
) {
    // Construct a matrix with the vectors as columns
    // (Xs on one row, Ys on the next... and the last row all 1s)
    Matrix4x4 matrix = new Matrix4x4(p1, p2, p3, p4);
    matrix.SetRow(3, Vector4.one);

    float a = matrix.determinant;

    // Copy the matrix so we can modify it
    // and still read rows from the original.
    var D = matrix;
    Vector3 center;

    Vector4 squares = new Vector4(
             p1.sqrMagnitude,
             p2.sqrMagnitude,
             p3.sqrMagnitude,
             p4.sqrMagnitude
    );

    D.SetRow(0, squares);
    center.x =  D.determinant;

    D.SetRow(1, matrix.GetRow(0));
    center.y = -D.determinant;

    D.SetRow(2, matrix.GetRow(1));
    center.z =  D.determinant;

    center /= 2f * a;
    return new BoundingBall(center, Vector3.Distance(p1, center));
}

```

---
Tags: c++, algorithm, bounding-spheres
---


title: Do I need to dispose Pixmap in Actor?

text:
# Question
Title: Do I need to dispose Pixmap in Actor?
I create Pixmap in Actor and don't know how to dispose it. Is it necessary in my case?

```
class MyActor(x: Float = 0f, y: Float = 0f): Actor() {

    var pixmap = Pixmap(1, 1, Pixmap.Format.RGBA8888)
    var texture = Texture(pixmap)
    var sprite = Sprite(texture)

    init {
        setPosition(x, y)
        sprite.setSize(32f, 32f)
        sprite.setPosition(this.x - sprite.width/2, this.y - sprite.height/2)
    }

    override fun act(delta: Float) {
        sprite.setPosition(x - sprite.width/2, y - sprite.height/2)
    }

    override fun draw(batch: Batch?, parentAlpha: Float) {
        sprite.draw(batch)
    }
}

```

# Answer
> 1 votes
As other answer stated, in this case it is fine to dispose the Pixmap right after the Texture creation.

However, (especially) if you are on Android (but elsewhere too), you should load your Textures via AssetManager, as Android may discard your textures when application switches to background and AssetManager takes care of reloading them.

Also, if you end up creating more than one instance of `MyActor` (which you probably will, by the looks of it), you should share the texture between them:

```
val blankTexture = run {
    val pixmap = Pixmap(1, 1, Pixmap.Format.RGBA8888)
    val texture = Texture(pixmap)
    pixmap.dispose();
    texture
}

class MyActor(x: Float = 0f, y: Float = 0f): Actor() {

    val sprite = Sprite(blankTexture)
    ...

```

Edit:

Example with AssetManager:

* Create 1x1 image file and store it in your assets (or you can download this one from libGDX repository)
* Create AssetManager and load the texture (and everything else you need)

```
class MyGame : ApplicationAdapter {

    companion object {
        lateinit var assetManager:AssetManager
        lazyinit var white: Texture
    }

    override fun create() {
        // Create new AssetManager (I am assuming here that this method will be called only once per game lifecycle)
        assetManager = AssetManager()
        // Preload the texture
        assetManager.load("white.png", Texture::class.java)
        // Make sure that it is loaded
        assetManager.finishLoading()
        // Cache it into a variable
        white = assetManager.get("white.png", Texture::class.java)
    }

    fun dispose() {
        assetManager.dispose()
    }
}

```
* Use that texture in your actor

```
class MyActor(x: Float = 0f, y: Float = 0f): Actor() {
    val sprite = Sprite(MyGame.white)
    ...
}

```

Note: As the wiki article about AssetManager mentions, static variables on Android (or in the case of Kotlin - `object`s) are somewhat tricky. But as long as you reinitialize them all when the game starts (in `create()` or somewhere similar) you should be fine. (That is why I used `lateinit var` instead of `val`.)

This solution is a quite bit more verbose and completely sidesteps the original question about Pixmap. If you are making only a small learning project without any other textures, or don't target Android, feel free to stay with the original AssetManager-less solution.

# Answer
> 0 votes
Its safe to dispose the pixmap straight after creating a texture from it as its no longer needed.

```
var pixmap = Pixmap(1, 1, Pixmap.Format.RGBA8888)
var texture = Texture(pixmap)
pixmap.dispose();
var sprite = Sprite(texture)

```

---
Tags: libgdx, kotlin
---


title: Queued rendering in LibGDX 2D

text:
# Question
Title: Queued rendering in LibGDX 2D
In my 2D game project, as well as in LibGDX in general, are a lot of different entities that need to be rendered(static images, sprites, animations, etc...), as well as have certain effects applied (shaders). Most, if not all, tutorials show a simple hardcoded way of rendering each sprite instance, or at the most, a loop iterating over one type of renderable entity and rendering it.

I have a need to render a decent number of entities (~1000 static(background/tilesets) and dynamic(characters) per screen) where certain entities might have one or even multiple shaders applied to them. I'll also probably have to deal with rendering to FBO's to be able to apply multiple shaders on entities, though I haven't yet reached that point so I'm not sure yet (so far my entities have either 0 or 1 shader, but I'm planning on placing multiple shaders per entity soon so I need to take that into account).

I don't know what rendering techniques would allow me to accomplish this task however I've got some ideas I'm stuck with.

For more context I'm also using an ECS but I'm not coupling rendering to it.

My current idea is to have a `RenderingEngine` of sorts, decoupled from ECS. It would basically contain a queue of... something, some message POJO describing what and where to render. This queue would then, each render cycle, be sorted according to layer, type, shader and then be distributed to their own appropriate renderer.

The gist is that other game systems send a message to the `RenderingEngine` describing what they want rendered and then the engine works out what to do with it the next rendering cycle.

Current issues I've got with this idea:

* Messages might prove to be a performance overhead as they are plain objects created for the sole purpose of sending a message over. This could probably be alleviated via pooling.
* Shaders. Without shaders rendering logic is fairly simple \[sort by layer -\> for each layer sort by type -\> render\]. Shaders however are applied per batch and that confuses me. I am not sure where in the above rendering logic would shaders fit in...

Am I reinventing the wheel? Is there a standard technique of accomplishing this kind of "flexible" rendering?

Is the queueing idea I've described above a part of some well known technique I could investigate for clues?(My searches have given me no anwsers so far)

# Answer
> 1 votes
You have started reinventing the wheel the moment you have started writing your own engine, but there is nothing wrong with that, that is why game frameworks exist (and this approach has many benefits over using an existing engine).

What you describe is somewhat similar to how libGDX's ModelBatch works. It deals with 3D graphics, but the sorting is similar, just instead of messages it uses `Renderable`s, which are your "POJOs of what needs to be rendered". By the way, you may also want to sort by texture, unless you have everything on single texture atlas page.

---

> The gist is that other game systems send a message to the RenderingEngine describing what they want rendered and then the engine works out what to do with it the next rendering cycle.

Have you considered creating a "Render" component and system in your ECS? Typically every system in ECS decomposition does only one thing (and does not concern itself with rendering - unless it is a render system, in which case it does not do anything else).

I am not saying that this is a bad idea or that it won't work, but it might simplify your code by gathering everything render-related into one single system. Then you can apply all sort of sorting/batching optimizations (if you need them) without affecting whole codebase.

---
Tags: 2d, libgdx, rendering
---


title: Move object at angle like a sine wave

text:
# Question
Title: Move object at angle like a sine wave
I currently have this code, which moves an object in a straight line at an angle, where "dir" is the angle.

`velX = (float)(Math.cos(Math.toRadians(dir))) * speed;`

`velY = (float)(Math.sin(Math.toRadians(dir))) * speed;`

`x += velX;`

`y += velY;`

What I need now is to have the object move like a sine wave, do I have to change the way I calculate velX and velY or is there some way of changing dir that would make it work?

I tried this but it didn't work, my objects would just got bunched up near 0, 0.
Move a sprite in a sine wave along different angles

# Answer
Let's take a unit vector \\$\vec u\\$ in the direction we want to travel, and a vector perpendicular to it, \\$\vec v\\$:

$$\vec u = \begin{bmatrix}cos \Theta\\sin \Theta\end{bmatrix}, \vec v = \begin{bmatrix}-sin\Theta\\cos \Theta\end{bmatrix}$$

Then we can define a point on a sinusoidal curve through starting point \\$\vec p\_0\\$, travelling in the direction \\$\vec u\\$, with a given speed, frequency, and amplitude, after time \\$t\\$ as:

$$\vec p(t) = \vec p\_0 + \vec u \cdot speed \cdot t + \vec v \cdot amplitude \cdot sin(frequency \cdot t)$$

Taking the derivative, we get:

$$\frac{\delta \vec p(t)}{\delta t} = \vec u \cdot speed + \vec v \cdot amplitude \cdot cos(frequency \cdot t) \cdot frequency$$

So, we can rewrite your velocity expressions as...

```
c = (float)(Math.cos(Math.toRadians(dir)));
s = (float)(Math.sin(Math.toRadians(dir)));

wobble = amplitude * (float)Math.cos(frequency * t) * frequency;

velX = c * speed - s * wobble;
velY = s * speed + c * wobble;

```

Note that steering the object purely by velocity, you can accumulate rounding and integration errors. While the path will have the overall shape, it may stray from the parametric equation \\$\vec p(t)\\$ above. To fix this, you could instead compute your next position directly from the parametric equation, then compute a velocity to reach it.
> 2 votes

---
Tags: java, trigonometry
---


# Question
Title: Drag and drop more than one sprite (image) on Libgdx
well i am trying to achieve the same effect of windows desktop , you can select multiple icons and drag all of them to differents positions.

here you can see how i select the images

in the second image you can see the three sprites selected.

my problem is the only one of the images are moving! not the three :/

here is my code:

```
public class Nivel extends GameState implements InputProcessor {

    private Texture tex;
    private Sprite sprite;
    private Array<Sprite> sprites;

    private boolean isdragged = false;

    private float x1 = 0;
    private float y1 = 0;
    private float x2 = 0;
    private float y2 = 0;
    private Rectangle rec;
    private Array<Sprite> seleccionados;
    private Vector3 vector = new Vector3();
    private boolean selected = false;
    private TextureRegion region;

    public Nivel(GameStateManager gsm) {
        super(gsm);
        tex = new Texture(Gdx.files.internal("badlogic.jpg"));
        tex.setFilter(TextureFilter.Linear, TextureFilter.Linear);
        sprites = new Array<Sprite>();
        seleccionados = new Array<Sprite>();//sprites inside the rectangles
        for (int i = 0; i < 6; i++) {
            sprite = new Sprite(tex);
            sprites.add(sprite);
        }
        rec = new Rectangle(-100, -100, 0, 0);
        Gdx.input.setInputProcessor(this);
    }

    @Override
    public void handleInput() {}

    @Override
    public void update(float dt) {
        for (int i = 0; i < sprites.size; i++) {
            sprites.get(i).setOrigin(sprite.getWidth() / 2, sprite.getHeight() / 2);
            if (rec.contains(sprites.get(i)
                    .getBoundingRectangle()) && !isdragged)//check if rectangle collide with sprites and select them
            {
                sprites.get(i).setColor(Color.GREEN);
                seleccionados.add(sprites.get(i));
                selected = true;
            }
        }

        if (!isdragged) {
            rec.set(-100, -100, 0, 0);
        }
    }

    @Override
    public void render() {
        sb.setProjectionMatrix(camera.combined);

        sb.begin();
        for (int i = 0; i < sprites.size; i++) {
            if (seleccionados.contains(sprites.get(i), true))
                continue;
            sprites.get(i).setBounds(i * 110, 100, 100, 100);
            sprites.get(i).draw(sb);
        }

        for (int i = 0; i < seleccionados.size; i++) {//array of sprite that has been selected

            if (!isdragged)
                seleccionados.get(i).setBounds(seleccionados.get(i).getX(), seleccionados.get(i).getY(), 100, 100);
            else
                seleccionados.get(i).setBounds(x2 - seleccionados.get(i).getWidth() / 2, y2 - seleccionados.get(i)
                        .getHeight() / 2, 100, 100);//move the selected sprites , only work for one :c

            seleccionados.get(i).draw(sb);
        }
        sb.end();

        renderer.setProjectionMatrix(camera.combined);
        renderer.begin(ShapeType.Line);
        renderer.setColor(Color.GREEN);
        if (isdragged && !selected) {
            float px = Math.min(x1, x2);
            float py = Math.min(y1, y2);
            float pw = Math.abs(x1 - x2);
            float ph = Math.abs(y1 - y2);

            rec.set(px, py, pw, ph);
            renderer.rect(px, py, pw, ph);
        }
        renderer.end();
    }

    @Override
    public void dispose() {
        tex.dispose();
    }

    @Override
    public boolean keyDown(int keycode) {
        return false;
    }

    @Override
    public boolean keyUp(int keycode) {
        return false;
    }

    @Override
    public boolean keyTyped(char character) {
        return false;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        Vector3 vector = new Vector3(screenX, screenY, 0);
        vector = camera.unproject(vector);
        x1 = vector.x;
        y1 = vector.y;
        return false;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        isdragged = false;

        return false;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        Vector3 vector = new Vector3(screenX, screenY, 0);
        vector = camera.unproject(vector);
        x2 = vector.x;
        y2 = vector.y;
        isdragged = true;

        return false;
    }

    @Override
    public boolean mouseMoved(int screenX, int screenY) {
        return false;
    }

    @Override
    public boolean scrolled(int amount) {
        return false;
    }
}

```

# Answer
It is because you assign each selected Sprite the same coordinates and they end up being drawn on top of each other:

```
seleccionados.get(i).setBounds(x2 - seleccionados.get(i).getWidth() / 2, y2 - seleccionados.get(i)
                    .getHeight() / 2, 100, 100);

```

Each sprite in `seleccionados` has the same width and height, so `x2 - seleccionados.get(i).getWidth()` always evaluates to the same number.

Also, here are multiple suspicious things / tips I noticed in this code:

* While you add to `seleccionados` on every frame, you never clear it, so each frame will be a little slower until the game crashes as it runs out of memory
* You don't have to do `seleccionados.get(i).setBounds(seleccionados.get(i).getX(), seleccionados.get(i).getY(), 100, 100);`, Sprite has `setSize(float, float)` method which does the same. But do you really need to set the size on each frame?
* Using `for (Sprite selected : seleccionados)` (for-each loop) instead of `for (int i = 0; i < seleccionados.size; i++)` will make the code more readable
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: Why is this Mono Behavior in the animator?
I'm looking through the 3D Game Kit from the asset store to accustom myself with the animator, and I'm just wondering what this is referring to. I was looking into controlling MonoBehaviors through the animation controller the other day and thought I had come to the conclusion that it couldn't be done directly, so what's this?

# Answer
Seems to be covered in the documentation:

> MonoBehaviour is the base class from which every Unity script derives.
> -1 votes

---
Tags: unity
---


title: Game freezes, cannot see why

text:
# Question
Title: Game freezes, cannot see why
My game freezes randomly, mostly when changing from one level to the next. I cannot tell why this is the case. There are no errors or warnings. This happens when i build the game and when I am testing the game in the Unity editor. It will say unfreeze itself after a few seconds. I have attached one of the level codes and the timer code. I have also attached a picture of how it looks when it freezes. This is one of the level codes :

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
public class Arduino5 : MonoBehaviour
{
    SerialPort sp = new SerialPort("\\\\.\\COM5", 9600);// Com port and the baud rate of the arduino
    Material m_Material;
    GameObject Sphere;

    void Awake()
    {
        Sphere = GameObject.FindWithTag("Player");
        m_Material = GameObject.FindWithTag("Player").GetComponent<Renderer>().material;
    }
    void Start()
    {
        if (!sp.IsOpen)
        { // If the erial port is not open
            sp.Open(); // Open
        }
        sp.ReadTimeout = 250; // Timeout for reading
    }

    // Update is called once per frame
    void Update()
    {
        if (sp.IsOpen)
        { // Check to see if the serial port is open
            try
            {
                string portreading = sp.ReadLine(); // get the string output of the serial port
                float amount = int.Parse(portreading);

                if ((amount > 50f) )
                {
                    m_Material.color = Color.grey;
                    Renderer _rend = Sphere.GetComponent<Renderer>();
                    Sphere.GetComponent<Renderer>().material = _rend.material;
                    _rend.material.mainTexture = Resources.Load("face4") as Texture;

                }
                else
                {
                    m_Material.color = Color.white;
                }
            }
            catch (System.Exception)
            {

            }
        }
    }
}

```

and this is the Timer code:

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class Timer : MonoBehaviour
{
    public int timeLeft = 5;
    public Text countdownText;

    // Use this for initialization
    void Start()
    {
        StartCoroutine("LoseTime");
    }

    // Update is called once per frame
    void Update()
    {
        countdownText.text = ("Time Left = " + timeLeft);

        if (timeLeft <= 0)
        {
            StopCoroutine("LoseTime");
            countdownText.text = "Times Up!";
            Invoke("ChangeLevel", 1.0f);
        }
    }

    IEnumerator LoseTime()
    {
        while (true)
        {
            yield return new WaitForSeconds(1);
            timeLeft--;
        }
    }
    void ChangeLevel()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
    }
}

```

In terms of trying to close the serial port, would something like this work:

```
void Start()

```

{ if (!sp.IsOpen) { // If the erial port is not open sp.Open(); // Open sp.ReadTimeout = 250; }

```
// Timeout for reading
else if (sp != null)
{

    {
        sp.Close();
    }
}

```

}

# Answer
> 1 votes
I'd be tempted to pull the serial port processing out of Unity's game loop, to ensure:

a) the I/O can't stall and cause our game loop to stutter or lag.

b) stuff we do in the scene can't inadvertently break the serial connection or misuse the shared COM resources in some way.

I can't guarantee either of those points above relates to your issue, but I have experienced stalls in the past when working with external connections if I got sloppy and tried to open two of the same connection / left a connection open after I was done with it / closed & re-opened connections excessively.

Here's one way we can make this a bit easier to tame:

```
public class SerialReader {

    // Keep just one open reader at a time for each port, so we don't
    // accidentally pile up several on the same shared resource.
    static Dictionary<string, SerialReader> _readers;

    public static SerialReader GetOrOpen(string portName, int baudRate) {
        SerialReader reader;

        if(_readers == null)
            _readers = new Dictionary<string, SerialReader>();
        else if(_readers.TryGetValue(portName, out reader))
            return reader;

        reader = new SerialReader(portName, baudRate);
        _readers.Add(portName, reader);

        return reader;
    }

    // Expose a master kill switch we can pull on application quit, to simplify.
    public static void StopAll() {
        if(_readers == null)
            return;

        foreach(var pair in _readers)
            pair.Value.Stop();
    }

    // Port configuration parameters.
    public readonly string portName;
    public readonly int baudRate;

    // Let other scripts read the current value of this reader.
    public volatile float value { get; private set; }

    // Local kill switch to stop just this one reader when we need to.
    volatile bool _continueReading = true;

    // Private constructor, so we can only call this via the request method above.
    // Starts a thread so the serial port I/O can happen in parallel.
    SerialReader(string portName, int baudRate) {
        this.portName = portName;
        this.baudRate = baudRate;
        var thread = new Thread(ReadLoop);
        thread.Start();
    }

    void ReadLoop() {
        // "Using" automatically disposes of the port once we exit this block.
        using(var port = new SerialPort(portName, baudRate) {
            port.Open();

            // Keep listening for new serial data until we're told to stop.
            while(_continueReading) {
                try {
                    string portreading = sp.ReadLine();
                    value = int.Parse(portreading);
                } catch (System.TimeoutException e) {
                    // Timeouts are expected and harmless, so we ignore these.
                }
                // Optionally, sleep before checking again.
            }

            // If we exit the loop, it's time to shut down.
            // Remove this reader from the index, and close the port.
            _readers.Remove(portName);
            port.Close();
        }
    }

    // Tell this reader we're done with it, so the read loop will exit.
    public bool Stop() {
        _continueReading = false;
    }
}

```

Now your script that relies on the reader might look something like this:

```
public class MaterialChanger : MonoBehaviour {

    public string portName = @"\\.\COM5";
    public int baudRate = 9600;

    SerialReader _reader;

    // On startup: request a reader - this will recycle one that's already
    // open if possible, instead of spinning up a new one.
    void Start() {
        _reader = SerialReader.GetOrOpen(portName, baudRate);
    }

    // Each frame, check & act on the latest value from the reader.
    // Note that this is now non-blocking: we don't stall waiting for changes.
    void Update() {
        if (_reader.value > 50f) {
            // Do some material changes...
        } else {
            // Or do some other material changes...
        }
    }

    // When we're all done, close the connection.
    // This is safe even if multiple scripts try to close the same reader.
    void OnApplicationQuit() {
        if(_reader != null)
            _reader.Stop();
    }
}

```

---
Tags: unity, arduino
---


# Question
Title: How do Axis-Aligned Bounding Boxes update with rotations?
I have a bounding box class with a min (x,y,z) and max point (x,y,z). The object that is being rotated has a rotation matrix (3x3 matrix), but I don't know how to update the bounding box with rotations.

I'm also a little confused if I should be using Oriented Bounding Boxes instead. For example, if the 3D object is a cube then the bounding box would rotate with it so they share the same 8 vertices at whatever rotation the cube is in.

What's the best way to represent the bounding box for rotations and test for collisions?

# Answer
Given an original axis-aligned bounding box and a transformation matrix, you can compute a new axis-aligned bounding box from the extents of the original box, transformed by the matrix, like so:

```
// Keep a scratchpad array we can re-use for listing all 8 corners of a box.
Vector3[] corners = new Vector3[8];

// Fill our scratchpad array with the corners of an axis-aligned bounding box.
void PopulateCorners(AABB bounds) {
    corners[0] = bounds.Min;
    corners[1] = new Vector3(bounds.Min.x, bounds.Min.y, bounds.Max.z);
    corners[2] = new Vector3(bounds.Min.x, bounds.Max.y, bounds.Min.z);
    corners[3] = new Vector3(bounds.Max.x, bounds.Min.y, bounds.Min.z);
    corners[4] = new Vector3(bounds.Min.x, bounds.Max.y, bounds.Max.z);
    corners[5] = new Vector3(bounds.Max.x, bounds.Min.y, bounds.Max.z);
    corners[6] = new Vector3(bounds.Max.x, bounds.Max.y, bounds.Min.z);
    corners[7] = bounds.Max;
}

// Compute a new axis-aligned bounding box that will contain whatever the original
// bounds did, after an affine transformation. (Note this is a lossy operation)
AABB GetTransformedBounds(AABB original, Matrix transformation) {
    PopulateCorners(original);

    Vector3 min = new Vector3(1, 1, 1) * float.PositiveInfinity;
    Vector3 max = new Vector3(1, 1, 1) * float.NegativeInfinity;

    // Transform all of the corners, and keep track of the greatest and least
    // values we see on each coordinate axis.
    for(int i = 0; i < 8; i++) {
        Vector3 transformed = transformation * corners[i];
        min = Vector3.ComponentwiseMin(min, transformed);
        max = Vector3.ComponentwiseMax(max, transformed);
    }

    return new AABB(min, max);
}

```

Note that you'll want to save the object's original "neutral orientation" bounding box separately. Anytime you want to compute a set of rotated bounds for the object, always work from this original, not from a previous rotated result. The reason is that an AABB might not be a tight fit - it might leave some room at the corners for example. If we rotate that box, then take the axis-aligned bounds of the rotated box, we'll tend to accumulate extra padding around the object, and our bounds will become less and less tight. Working always from the original ensures this error can't accumulate, and we get the best fit we can under the circumstances.

Of course, you can be more accurate still by always working from the source object/mesh/primitives. Transform all the points of the object (or its convex hull for simplicity) and then compute a new min & max from scratch off of those values. That will get the absolute tightest axis-aligned bounding box, like the one shown in the gif of the rotating knot in the article you link. But it's also often more work than just transforming the AABB.
> 2 votes

---
Tags: collision-detection, rotation, matrix, bounding-boxes, aabb
---