# Question
Title: How to prevent unbalanced population in MMO game factions?
In games such as World of Warcraft, the imbalance between factions is often a matter of controversy.

To compensate, WoW applied the Tenacity buff to the outnumbered faction to balance PvP.

However, this only applies to PvP and I wonder if this kind of bonus can be used to encourage character creation in the least populated faction.

**Something like an XP bonus for the least populated faction?** For example, 5% XP bonus if the faction represents 45% of the server. The bonus would be highlighted when creating a character and it would be 0 when the two factions have the same size.

**Or a bonus on the economy by lowering auction fees proportionately to the imbalance?**

# Answer
Encouraging people to pick the underrepresented faction when they start playing is not going to work. Faction imbalance isn't static. It changes over the history of the game, it might be different in different locations, it might be different in different level brackets (if these are relevant in your game), it might even be different depending on the time of the day. Player Allegiance, however, is often not. If you force players to choose a faction at game start, they will often stay loyal to their faction. And faction allegiance only starts to matter when the players reached a level high enough that they actually have an impact on faction warfare.

So when a newbie creates a new character today, they will have a weak character and they will lack skills and metagame knowledge. It might take months until they have the competence to gain significant influence in the faction-vs-faction gameplay. Some might in fact *never* play faction warfare on a high skill level. So the faction you wanted to boost will soon look good according to player numbers, but still gets their ass kicked because a lot of their players do not contribute effectively.

Regarding your idea to solve this problem with giving an Exp bonus to the underrepresented side. Let's assume that your game is similar to World of Warcraft, where you have separated PvE and PvP content, with the PvE content being the main way to earn Exp points. An Exp bonus will not be a good incentive for faction warfare in such a game, because it would be primarily an incentive for PvE gameplay. The main beneficiaries of this would be those players who **don't** participate in faction warfare. So you would make the situation even worse. It might, however, work in a game where faction warfare is the primary source of Exp in your game. When the underrepresented faction receives more rewards *in faction warfare*, it would incentivize more players to participate in it... but only if the reward actually outweights the penalty for fighting on the losing side (both material and emotional).

A better approach than to force players to play the faction they don't actually want to play is to look at your faction-vs-faction gameplay and look for how you can design it to mitigate a numerical advantage. See how you can design it in a way which makes it fun and fair to play even if one side outnumbers the other. Also look for ways to make the game fun even if you are losing. But this task would be highly game-specific. Doing it like WoW and giving a stat buff to the side with less people is a simple and effective solution, but far from the only one. If you post a new question with more information about your faction-vs-faction game mechanics we might help you to balance them better when the factions are asymmetrical.
> 3 votes

# Answer
As RL has done, create plagues, town fires, social sloth, and organisational inertia to balance these out. ;) That'll teach people to stay away from large groups! And if that doesn't do it, suicide bomber attacks will! There have been many stories about how the small group is more agile than the large organisations it faces... take the Three Musketeers, for one (OK, they worked for the King, but still).

Have you ever seen a crowd of people running for a fire exit when things get hairy?

(Irreverent) jokes aside, the bottom line is that there should be sufficient downsides to being in massive groups that it makes gathering in such mobs a non-trivial decision on the player's part. Giving players non-obvious / non-trivial decisions is one of the cornerstones of good gameplay.
> 2 votes

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


title: Rotate a ds_grid 90 degrees in GMS2

text:
# Question
Title: Rotate a ds_grid 90 degrees in GMS2
I need a function that allows me to rotate a grid data structure an arbitrary number of times 90 degrees clockwise. Currently it doesn't appear as though the function has any effect on the `ds_grid`.

Below is the code I'm currently using, the function that calls it looks like: `ds_grid_rotate_alt(global.grid, irandom(3), 10);`.

```
/// @description rotate grid clockwise 90 degrees x times

var grid = argument0;
var turns = argument1;
var width = argument2;

var gx = 0;
var gy = 0;

if turns > 0
{
    var grid_copy = ds_grid_create(width, width);

    for (gy = 0; gx < width; gy++)
    {
        for (gx = 0; gx < width; gx++)
        {
            //grid copy
            var data = ds_grid_get(grid,gx,gy);
            ds_grid_set(grid_copy,width-gy,width-gx,data);
        }
    }
    //copy results back to origional grid
    ds_grid_copy(grid_copy,grid);
    ds_grid_destroy(grid_copy);

    turns -= 1;
    ds_grid_rotate_alt(grid,turns,width);
}

```

# Answer
As commented, you must change the arguments of the `ds_grid_copy()` function, for it isn't saving your calculations.

Taking a look at your code, I came up with a function that does exactly what you want, and that works linearly without the need of being (needlessly) recursive.

Since `ds_grid`s are basically matrices, we can use maths to work with them. Your function uses `width` as matrix size, so it's safe to suppose it's a square matrix. Let *A* be a 4x4 square matrix, and we want to rotate it 90 degrees clockwise; it comes that such a rotation is the same as *first* transposing *then* horizontally flipping the matrix:

You can try it with a squared paperboard, the result is the same. There's a formal explanation for that, but we are interested in the implementation.

Also, every four rotations we get to the starting configuration (rotating 360 degrees equals not rotating at all), so we can consider the modulo of the variable `turns` and *4* instead of performing unnecessary rotations leading to the same result over and over, saving this way useful CPU time.

So, now we are at the point of considering only three different rotations: 90, 180, and 270 degrees clockwise. We can do another consideration: why rotate clockwise three times if we can do just one rotation clockwise? Math helps us, because if we flip horizontally **before** transposing, the result is we are rotating 90 degrees counter-clockwise, thus 270 degrees clockwise:

Finally, 180 degrees rotations are the same be them CW or CCW. We may say we rotate 90 degrees twice, actually rotating by 180 degrees equals to flip both horizontally and vertically, irrespective of the order of transforms:

The only operations involved are transposition, horizontal and vertical flip, and we just combine them to get our desired rotations. We may create three separate functions and execute them as needed, but we can still do some work offline and create a single function that executes two of these transforms at once.

Transposition moves value in a given cell to the target cell by swapping starting coordinates.

> **Trasposition**
> *A\[u,v\] → A\[v,u\]*

Flipping involves reversing the coordinates from the end of the row or column (*W* is max width, *H* is max height).

> **Horizontal flip**
> *A\[u,v\] → A\[W-(u+1),v\]*
>
> **Vertical flip**
> *A\[u,v\] → A\[u,H-(v+1)\]*

We combine transposition and flipping to get 90 degrees rotations (mind I removed parentheses and changed signs accordingly):

> **Transposition, then hor. flip (90° CW)**
> *A\[u,v\] → A\[W-v-1,u\]*
>
> **Hor. flip, then transposition (270° CW - 90° CCW)**
> *A\[u,v\] → A\[v,W-u-1\]*

Finally, the 180 degrees rotation:

> **Hor. flip, then vert. flip or viceversa (180° CW/CCW)**
> A\[u,v\] → A\[W-u-1,H-v-1\]

You can now use these pseudocode assignments to create your rotated matrix in a single step, without any unnecessary iteration or recursion.
> 2 votes

---
Tags: game-maker, data-structure
---


# Question
Title: How can I encourage population balance between two factions?
I'm making a game in which **players must choose between two factions** after reaching a certain level.

PvP and PvE are not influenced by this choice as it's **mostly for role play and the sense of belonging to a community** (and perhaps seasonal events).

The two factions can communicate. Preferably, guild members must be in the same faction and it should be impossible or not easy to change factions.

I fear that if a faction starts to have the majority of players, new players will want to join it to play with their friends or have more guild choices.

How could I mitigate or prevent that? Are there alternatives?

# Answer
A few thoughts:

* An economy can help keep balance. If one faction has more access to an item than another, and if that faction is underrepresented, then those items will be more rare in trade. This will motivate more players to join that faction to get the more rare items.
* Since the factions are mostly for role-playing and story, the choice should be based on what "represents" them (personality test?). A good, simple example of this is Pokemon Go. People got passionate about their team based on just a couple words describing the ideals. There was little difference in the factions themselves. With this kind of personality-based classification, people will often contrast themselves from their friends to pick the opposite faction.
* As long as there is plenty of communication between factions, the problem of friends grouping up should not matter much. In fact, you might see the opposite, where someone chooses the faction opposite his friend to see what else the game has to offer. This is what I would do, because then between the two of us, we could do everything. This might be more tricky if those factions are actively warring against each other, but since you said they are not, I'd recommend allowing teams to form built of people of both factions (Not necessarily a guild, but maybe a team for missions).
> 5 votes

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


title: Circle colliders dont work

text:
# Question
Title: Circle colliders dont work
I have a destination and 2 players.

I want the players to reach the destination and not overlap in the process.

I attached to each player a circle 2D collider and a rigidbody 2D.

Also this script:

```
using UnityEngine;
using System.Collections;

public class Agent : MonoBehaviour {

    public Transform destination;
    private Vector2 destPostion;
    private Vector2 playerPosition;

    public float rotation = 0;

    Vector2 velocity = Vector2.zero;

    public int maxForce = 5; //rate of acceleration
    public int maxSpeed = 4; //grid squares / second

    //private Rigidbody2D rb;

    void Start () {
        //rb = gameObject.GetComponent<Rigidbody2D>();
        destPostion.x = destination.position.x;
        destPostion.y = destination.position.y;
    }

    // Update is called once per frame
    void FixedUpdate () {
        Vector3 temp = transform.position;
        destPostion.x = destination.position.x;
        destPostion.y = destination.position.y;

        playerPosition.x = transform.position.x;
        playerPosition.y = transform.position.y;
        //Work out the force for our behaviour
        var seek = steeringBehaviourSeek();

        //Apply the force
        velocity = velocity + (seek * Time.deltaTime);

        //Cap speed as required
        var speed = velocity.magnitude;
        if (speed > maxSpeed) {
            velocity = velocity * (4 / speed);
        }

        //Calculate our new movement angle
        rotation = Mathf.Atan2(velocity.x, -velocity.y) * 180 / Mathf.PI;
        transform.rotation = Quaternion.Euler(0, 0, rotation);

        playerPosition = playerPosition + (velocity * (Time.deltaTime));

        temp.x = playerPosition.x;
        temp.y = playerPosition.y;
        transform.position = temp;
        //rb.MovePosition(temp);
    }

    private Vector2 steeringBehaviourSeek() {

        //Desired change of location
        Vector2 desired = destPostion - playerPosition;

        //Desired velocity (move there at maximum speed)
        desired = desired * (maxSpeed / desired.magnitude);

        //The velocity change we want
        var velocityChange = desired - velocity;

        //Convert to a force
        return velocityChange * (maxForce / maxSpeed);
    }
}

```

The problem is they start moving for a bit and they stop.

Also in the scene when I move them with the mouse they overlap. Any ideas?

# Answer
> 1 votes
Circle colliders aren't magic. They just let the physics engine detect and respond to collisions with appropriate impulses to change the trajectory of objects in the physics update step.

When you position an object with `transform.position = ...` you're saying "I do not care what the physics engine thinks, put the object EXACTLY HERE" - and the engine listens, and does exactly what you told it to do, even if that breaks the rules of physics collisions, because you told it you wanted to override whatever the result of the last physics step was. A circle collider won't intercept your transform commands and change them into something else.

If you care about physics behaviour like avoiding collisions, then you need to do one of two things:

1. Move your objects with physics, by using the `Rigidbody2D`'s forces, velocity, angular velocity, etc. That puts control back into the physics engine's hands to stop or deflect objects if a particular motion would cause them to penetrate.
2. Do your own checking for collisions using raycasts or shapecasts, and back off if a planned position change would take you into a collision.

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


# Question
Title: LibGDX: How to use AssetManager with Texture Atlases?
A similar question was asked before, but I never saw an answer.

How does one load individual texture regions that derive from a texture atlas using assetManager? I know that assetManager relies on a file name. (the file name could be the .pack file, for instance).

How would this work for individual texture regions? What would go in the file handle?

How would I do this:

manager.load("sprite\_sheet.txt", TextureAtlas.class);

but with a textureRegion from that atlas?

# Answer
> 1 votes
You don't, the asset is the `TextureAtlas`, not the individual `TextureRegions`.

This means that you let the `AssetManager` load the `TextureAtlas` and you manage getting the regions out of it yourself.

One way of doing this is the way Andreas Ohelke does it in Learning libGDX Development where a `Assets` class load the `TextureAtlas` and then simple wrapper classes are responsible for getting the regions in an easy to access format:

```
public class Assets {
    private static final AssetDescriptor<TextureAtlas> SPRITE_ATLAS = new AssetDescriptor<TextureAtlas>("graphics/sprites.atlas", TextureAtlas.class);

    public SpriteAssets sprites;

    public void init(AssetManager assetManager) {
        TextureAtlas spriteAtlas = assetManager.load(SPRITE_ATLAS, TextureAtlas.class);

        assetManager.finishLoading();

        sprites = new SpriteAssets(assetManager.get(SPRITE_ATLAS));

    }

    public class SpriteAssets {

        public final TextureRegion ship;
        public final TextureRegion player;
        public final TextureRegion enemy;

        public SpriteAssets(TextureAtlas atlas) {
            ship = atlas.findRegion("ship");
            player = atlas.findRegion("player");
            enemy = atlas.findRegion("enemy");
        }
    }
}

```

(full example)

---
Tags: java, libgdx, textures, assets, asset-management
---


# Question
Title: Why does this implementation of aabb-sphere collision ghost collide and how can I fix it
I am trying to make a collision detection system and the aabb-sphere collision isn't working. Here is my code.

This method checks to see which whether I should collide with AABB-AABB, Sphere-Sphere, or AABB-Sphere.

```
    public static boolean collides(BoundingBox box,BoundingBox other) {
    if(box instanceof AABB && other instanceof AABB) {
        return collides((AABB) box,(AABB) other);
    }
    if(box instanceof Sphere && other instanceof Sphere) {
        return collides((Sphere) box,(Sphere) other);
    }
    if(box instanceof AABB && other instanceof Sphere) {
        return collides((AABB) box,(Sphere) other);
    }
    if(box instanceof Sphere && other instanceof AABB) {
        return collides((Sphere) box,(AABB) other);
    }
    return false;

```

This method does the actual colliding.

```
public static boolean collides(AABB other,Sphere sphere) {
    Vector3f p = closestPointToAabb(other, sphere.getPos());
    Vector3f v = Vector3f.sub(p, sphere.getPos(), null);
    float dist = Vector3f.dot(v, v);
    boolean collision = dist <= sphere.getRadius() * sphere.getRadius();
    return collision;

};

```

This method calculates the point closest to aabb.

```
public static Vector3f closestPointToAabb(AABB aabb,final Vector3f point) {
    if(point.x > aabb.getMax().x ||  point.y > aabb.getMax().y ||point.z > aabb.getMax().z ) {
        return aabb.getMax();
    }else if(point.x < aabb.getMin().x ||  point.y < aabb.getMin().y ||point.z < aabb.getMin().z ) {
        return aabb.getMin();
    }
    return point;
}

```

This method does all the logic.

```
     public static void updateObjects() {
     for(int collider = 1; collider < axisList.size(); collider++) {
            BoundingBox colliderBox = axisList.get(collider);

            for(int collidee = 0; collidee < collider; collidee++) {

                BoundingBox collideeBox = axisList.get(collidee);

                if((colliderBox.getStatic() && collideeBox.getStatic()) && !(colliderBox instanceof Player || collideeBox instanceof Player)) {
                    continue;
                }
                if(BoundingBox.collides(colliderBox, collideeBox)) {

                    System.out.println("Collision with " + colliderBox.getName() +  " and " + collideeBox.getName());
                    collisionList.add(new Collision(colliderBox,collideeBox));

                }

            }
        }
      }
}

```

Could anyone please help me. Also How should I specify my min and max and the sphere's centre and radius.

**Edit:**

It seems that the collision is working but the Bounding Boxes collide in random places. I think it is a problem in how I am specifying my min and max and the sphere's centre and radius.

Here is how I specify it.

```
 public static void addObject(Entity entity) {
     if(entity instanceof Player) {
         Sphere sphere = new Sphere(entity.getModel().getMin(),entity.getModel().getMax(),entity.getPosition(),false,entity.getName());
         axisList.add(sphere);
         entity.setBox(sphere);
         return;
     }
     axisList.add(entity.getBox());
 }

```

And here is three methods(The code is pretty bad but I will fix it).

```
removeUnusedVertices(vertices);
    float[] verticesArray = new float[vertices.size() * 3];
    float[] texturesArray = new float[vertices.size() * 2];
    float[] normalsArray = new float[vertices.size() * 3];
    float furthest = convertDataToArrays(vertices, textures, normals, verticesArray,
            texturesArray, normalsArray);
    int[] indicesArray = convertIndicesListToArray(indices);
    Vector3f min = min(vertices);
    Vector3f max = max(vertices);
    TexturedModel model = new TexturedModel(Loader.loadToVao(verticesArray, texturesArray, normalsArray, indicesArray),min,max,vertices,furthest, textureLoc);
    return model;

    private static Vector3f min(List<Vertex> vertices) {
    List<Float>  xArray= new ArrayList<>();
    List<Float> yArray = new ArrayList<>();
    List<Float> zArray = new ArrayList<>();
    for(Vertex vertex : vertices) {
        xArray.add(vertex.getPosition().x);
        yArray.add(vertex.getPosition().y);
        zArray.add(vertex.getPosition().z);
    }
    return new Vector3f(Collections.min(xArray),Collections.min(yArray),Collections.min(zArray));
}

private static Vector3f max(List<Vertex> vertices) {
    List<Float>  xArray= new ArrayList<>();
    List<Float> yArray = new ArrayList<>();
    List<Float> zArray = new ArrayList<>();
    for(Vertex vertex : vertices) {
        xArray.add(vertex.getPosition().x);
        yArray.add(vertex.getPosition().y);
        zArray.add(vertex.getPosition().z);
    }
    return new Vector3f(Collections.max(xArray),Collections.max(yArray),Collections.max(zArray));
}

```

My entity intiialization

```
box = new AABB(getModel().getMin(),getModel().getMax(),position,name,staticObject);

```

AABB and sphere:

```
    public AABB(Vector3f min,Vector3f max,Vector3f pos,String name,boolean staticObject) {
    this.min = min;
    this.max = max;
    this.name = name;
    this.staticObject = staticObject;
    this.pos = pos;
}

 public Sphere(Vector3f min,Vector3f max,Vector3f pos,boolean staticObject,String name) {
    radius = Vector3f.dot(max, min);
    center = Vector3f.sub(max, min,null);
    this.pos = pos;
    this.staticObject = staticObject;
    this.name = name;
}

```

**Edit Again:**

I debugged my code again and found that when I make contact with an aabb it reports that I'm colliding with all the aabb's in the scene.

I have no idea what could be causing this.

# Answer
Without knowing more of what error conditions your running into I only have one guess at what is going wrong. It's your "closestPointToAabb()". It looks like your using ||(or) to find your max and min boundaries, instead of checking them each individually. The psuedocode for what you're doing now looks like this:

```
closestPointToAabb(aabb, point)
{
     // max
     if( point.x > aabb.x ) return aabb.max();
     if( point.y > aabb.y ) return aabb.max();
     if( point.z > aabb.z ) return aabb.max();
     // min
     if( point.x < aabb.x ) return aabb.min();
     if( point.y < aabb.y ) return aabb.min();
     if( point.z < aabb.z ) return aabb.min();
}

```

By using ||(or) you're effectively returning the max if any of those conditions are true. Meaning that you were either returning 1 of 3 things:

```
1) A point inside the aabb
2) The max corner of the aabb
3) The min corner of the aabb

```

What I think you want to be doing is building a new point based on each spacial component individually. The psuedocode for that would be:

```
closestPointToAabb(aabb, point)
{
     Point p;
     // for each coordinate axis clamp it to the bounds of the aabb
     for( axis a in xyz ){
         float v = point[a]
         if( v < aabb.min[a] ) v = aabb.min[a];
         if( v > aabb.max[a] ) v = aabb.max[a];
         p[a] = v;
     }
     return p;
}

```

This will be able to return to you any of the corners of your aabb, as well as a point inside of your aabb, **AND** a point along any of the faces of your aabb.

This is the best answer I could come up with using the information you've given us, but hopefully its a good starting point. For some more information on AABB -\> Sphere collision you can check out another of my answers here.

**= EDIT =**

I think your right about issues in building your bounding volumes. The extra code is helpful but it's still a little hard to tell without knowing how your using them, and what issues your running into. Additionally I still think that "closestPointToAabb()" needs to be addressed, but since that's covered above here is some help with building the volumes.

**AABB**

I'm not sure how these variables are being updated in the AABB code, so these are not recommended fixes, just some things to check for:

1) Are 'min' and 'max' the worldspace positions of those corners? Because if so you'll need to update them along with the position whenever it moves.

2) Are 'min' and 'max' a distance away from the center to those corners? If so then they shouldn't change, and instead just get added/subtracted from the position when you need to check against them. Otherwise your box will be centered at the origin(0,0,0). Additionally if they're a distance from center, then you really only need to store one of them as a "radius" and you can add/sub that from the position when you use it.

**SPHERE**

It looks like this setup has a few issues:

1) What is the difference between 'center' and 'pos'? Do they do different things? From an outsider perspective it seems like only one of them is necessary.

2) I'm not sure what values you're passing in as 'min' and 'max' but when you dot two non-normalized vectors you get some large numbers. I think you may want to change your radius calculation to:

```
// psuedocode
Vector3f diameterVector = max - min;
Vector3f radiusVector   = diameterVector / 2;
float    radius         = magnatude(radiusVector);

```

This gets the distance from min to max which is the diameter. And then half the diameter is the radius. (r=d/2)

3) If I misread it and the 'center' and 'pos' do actually have different functionality then you can calculate your center by adding the 'radiusVector' to the min.

```
// same radius psuedocode as above
Vector3f diameterVector = max - min;
Vector3f radiusVector   = diameterVector / 2;
float    radius         = magnatude(radiusVector);
// add radius to the min to find the worldspace
// midpoint between min and max
Vector3f center_worldspace = min + radiusVector;

```

I'm not very fluent in java so I'm sticking to psuedocode for now. I hope the meaning still comes across, and this is even a little bit helpful. Let me know if you have any further questions. Good luck!
> 0 votes

---
Tags: java, collision-detection, physics, logic
---


# Question
Title: Calculating the difference between two numbers using exponential growth
I think this is a very basic game programming question, but I am bad with math and new to programming & game programming so I'm looking for some advice. I'm making a 2D sprite game for iOS. Every frame in my game loop I check to see if player moves past a boundary in the game; if so, I scroll the camera's view:

```
    if playerPosition.x > rightBound {
        let amt = playerPosition.x - rightBound
        camera.position = CGPoint(x: camera.position.x + (amt * 0.1), y: camera.position.y)
    }

```

This works OK; the camera scrolls slowly when the player exceeds the boundary by a small amount and scrolls more quickly when they exceed the boundary by a larger amount. So the scrolling speed scales up linearly. However, I would like the scrolling speed to scale up faster, perhaps in at a more "exponential" rate. (Enter my terrible understanding of math...)

I don't know the best way to express this mathematically. I know that exponential growth is an actual thing in math, but I actually had to look it up on Wikipedia. And I don't know the best way to implement that in game programming.

To clarify with a simple hypothetical, say that the boundary x position is at 0. When the player moves past it in the first frame his position is 1, so the difference between the two positions is 1. Then next frame his position is 2 so the difference increases to 2, and so on. So the difference between the positions grows like 1, 2, 3, 4, 5, 6, etc. However, I want to calculate the difference between these positions so that my result grows more like 1, 2.1, 3.3, 4.5, 6.1, 7.8, etc.

This graph suggests that I might want to use cubic growth or exponential growth:

But I'm not sure how to express such a formula programmatically. Perhaps more importantly, I don't know if that is the best way to approach this sort of calculation from a game programming perspective. This calculation will run four times every frame, and performance is a concern so I'm trying to find an efficient solution rather than some crufty version I arrive at by myself.

Can anyone provide some advice? I'm working in Swift but I think this is a language-agnostic problem. If you express the answer in another language I can probably figure out how to implement that in Swift.

**UPDATE:**

Thanks to tom10, I ended up going with this formula for exponentially increasing my camera scrolling speed based on how far the player has passed beyond a boundary:

```
if playerPosition.x > rightBound {
    let dx = playerPosition.x - rightBound
    let baseAmt = dx * 0.033
    let amt = baseAmt + pow(2, baseAmt * 0.25)
    camera.position = CGPoint(x: camera.position.x + amt, y: camera.position.y)
}

```

`0.033` and `0.25` are "magic numbers" that work well for my game; I arrived at them by trial & error.

# Answer
To put these into a formula, it seems that you want something that varies with the distance from the boundary, so first calculate that parameter (I'll call it `dx` below), and then put that into whatever formula you want.

Note that some terms will preserve the sign of the distance and some won't (`exp(x)` and `x*x` won't but `x*x*x` will) so excursions to the left vs right of the boundary need to be thought through differently in two cases.

```
if playerPosition.x > rightBound {
    let dx = playerPosition.x - rightBound
    let amt = 0.1*dx*dx*dx  // or pow(dx, 3), or exp(abs(x))
    camera.position = CGPoint(x: camera.position.x + amt, y: camera.position.y)
}

```

I'd skip the exponential if I were you. For example, exp(0) = 1, which can be dealt with, but it's a hassle, and for small `dx` it won't make much difference anyway.

If you want to fine tune things, I think you'd be better off using something like `a*dx + b*dx*dx*dx`, where you tune the parameters `a` and `b` to your liking. Here the linear term will be most relevant at small `dx` and the cubic for larger `dx`.
> 3 votes

---
Tags: mathematics, movement, ios, performance, swift
---


title: LookAt only in Z axis

text:
# Question
Title: LookAt only in Z axis
I'm fairly new to game development, like many of us asking questions here

Currently, I'm trying my luck working on a simple space shooter.

I'm trying to add some enemy ships with movement, they will only move forwards, but, at all time, will be facing the player ship´

I have that figured out, after playing with many options, LookAt was my saviour, but now, I'm having an issue, they do rate to face the player, but they also rotate on the Y axis

This is how they are in the editor looking

This is the position setting

Their properties

Their code

```
using UnityEngine;

public class AlienMovement : MonoBehaviour {

    public GameObject PlayerShip;
    public float speed;

    // Use this for initialization
    void Start () {
        GetComponent<Rigidbody> ().velocity = transform.up * speed * -1;
    }

    // Update is called once per frame
    void Update () {
        transform.LookAt (PlayerShip.transform, Vector3.up);
    }
}

```

And how they look once the game is running (frame still)

Transform properties for the one on the right

Any idea what I'm doing wrong?

# Answer
> 3 votes
First, I notice you seem to be working in the XZ plane. This is a slightly unusual choice for a 2D game, and often requires extra rotation like the 90 degree pitch on your enemy ship sprite. If you choose to switch to the 2D physics system later on, it will expect all your gameplay to be in the XY plane.

Next up, LookAt is designed to point the object's local forward vector at the target — that's the blue Z+ arrow. But that axis Unity calls forward isn't the direction your sprite is facing in the visible art, so LookAt is going to spin us the wrong way.

Instead I'd recommend using its cousin, `Quaternion.LookRotation`. It takes (up to) two parameters:

* first, a direction to point the local Z+ axis
* second, a direction to point the local Y+ axis

So we can use this to steer our local Y in a particular direction while keeping our Z facing us flat into the gameplay plane.

```
// Since you're looking down on the XZ plane,
// the Y- axis AKA Vector3.Down is your viewing direction.
// You can change this if you decide to change planes later.
Vector3 intoPlane = Vector3.Down;

// Calculate a vector pointing to the target.
Vector3 toTarget = playerShip.transform.position - transform.positition;

// Point our Z+ into the gameplay plane,
// and our Y+ away from the target.
// (Since our "front" is at the bottom/Y- extreme)
transform.rotation = Quaternion.LookRotation(intoPlane, -toTarget);

```

# Answer
> 1 votes
`transform.LookAt(Transform target, Vector3 worldUp)` makes your transform look towards the target while aligning the transform's up vector with the world up vector. It doesn't care about the forward vector. So even though the transform's up and world up vectors are aligned, the forward vectors aren't since your ship positions seem to have different z-coordinate values.

You can fix this by creating a temporary position variable with the same z-coordinate

```
void Update () {
  Vector3 pos = PlayerShip.transform.position;
  pos.z = transform.position.z;
  transform.LookAt (pos, Vector3.up);
}

```

---
Tags: unity, rotation
---


title: Specular light for DirectX11

text:
# Question
Title: Specular light for DirectX11
I illumine model through model illumine of Phong. Ambient and diffuse light’s constituent work well, but specular works wrong. Under this message I sent screenshoots: 1) ambient and diffuse

2) ambinet + diffuse + specular.

Code shader's. Vertex's:

```
    cbuffer ConstantBufferVS
    {
    matrix World;
    matrix View;
    matrix Perspective;
    }

    struct VS_INPUT
    {
    float4 Pos: POSITION;
    float3 Normal: NORMAL;
    float4 Color: COLOR;
    };

    struct VS_OUTPUT
    {
    float4 Pos: SV_POSITION;
    float3 Normal: TEXCOORD0;
    float4 Color: COLOR0;
    float3 WorldPos: TEXCOORD1;
    };

    VS_OUTPUT main(VS_INPUT input)
    {
    VS_OUTPUT _out = (VS_OUTPUT)0;
    _out.Pos = mul(input.Pos, World);
    _out.Pos = mul(_out.Pos, View);
    _out.Pos = mul(_out.Pos, Perspective);
    _out.Normal = (float3)mul(float4(input.Normal, 1), World);
    _out.Color = input.Color;
    _out.WorldPos = (float3)mul(input.Pos, World); // position vertex in world
    return _out;
    }

```

Pixel's:

```
    cbuffer ConstantBufferPS
    {
    float4 Direction;
    float4 Color;
    float4 factors;
    float4 View; // position camera, 0, 2, -3
    }

    struct VS_INPUT
    {
    float4 Pos: SV_POSITION;
    float3 Normal: TEXCOORD0;
    float4 Color: COLOR0;
    float3 WorldPos: TEXCOORD1;
    };

    float4 main(VS_INPUT input): SV_Target
    {
    // ambient
    float4 ambient = (Color * factors.x) * input.Color;

    // diffuse
    float4 diffuse = saturate(dot((float3)Direction, input.Normal) * Color);

    // TODO
    // specular
    float4 specular = 0.0;
    float3 vView = normalize((float3)View - input.WorldPos); // vector from pixel towards eye
    float3 vReflect = reflect((float3)normalize(Direction), normalize(input.Normal)); // merror vector direction light
    // нормалью
    float spec = pow(dot(vReflect, vView), 64); // calculate spec
    specular = spec * factors.y * Color; // calculate specular light

    // multiply light's component's
    float4 out_color = (ambient + diffuse + specular) * input.Color;
    out_color.a = 1;

    return out_color;
    }

```

All the moments are commented on.

# Answer
A few things come to mind, and I will be making an assumption or 2. Firstly, your out\_colour obviously produces the top image without adding specular? That just adding specular in causes it to be overly dark. The other thing you should also do is call saturate on your out\_colour also. Could you confirm that just removing specular from the link

```
float4 out_color = (ambient + diffuse + specular) * input.Color;

```

renders as per top image.

I've added my specular calculation in below.

```
    float3 reflection = reflect(diffuseLightDirection, input.normal.xyz);

    // Calculate the specular light based on the reflection and the camera position.
    //Increase the specular light by the shininess value.

    // Calculate the specular light based on the reflection and the camera position.
    float specular = dot(normalize(reflection), normalize(input.cameradirection.xyz));

    // Check to make sure the specular was positive so we aren't adding black spots to the water.
    if (specular > 0.0f)
    {

            //  // Increase the specular light by the shininess value.
        specular = pow(specular, specularShininess);

        // Add the specular to the final color.
        pixelColourBlend = saturate(pixelColourBlend + specular);
    }

```

What you will notice is that specular is done as a float and is added uniformly to the pixel.
> 1 votes

---
Tags: c++, directx, directx11, hlsl, specular
---


# Question
Title: Instantiate prefab as a type that inherits from MonoBehaviour
I have a `CeilingTile` class. In this class, I have an `InstantiateCeilingLamp()` method, which instantiates from a `CeilingLamp` prefab.

Here is the code:

```
protected void InstantiateCeilingLamp()
{
    Object ceilingLampPrefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));

    CeilingLamp ceilingLamp =
        Instantiate(ceilingLampPrefab, this.transform.position, Quaternion.identity)
            as CeilingLamp;

    if (ceilingLamp == null)
    {
        Debug.Log("Failed to instantiate the ceiling lamp.");
        return;
    }

    ceilingLamp.transform.SetParent(this.transform);
}

```

`prefabPath` is a `const string` defined within the class.

Stepping through my code using the debugger, I can see that `ceilingLampPrefab` is non-null after executing `AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));`.

However, `Instantiate(...) as CeilingLamp;` returns `null`, because the instantiated prefab cannot be cast to the type `CeilingLamp`, which inherits from `MonoBehaviour`.

How should I modify my code in order to instantiate a prefab as a type that inherits from `MonoBehaviour`?

# Answer
> 1 votes
The `CeilingLamp` prefab has the `CeilingLamp.cs` script (which inherits from `MonoBehaviour`) attached to it, so by modifying the code as follows, I am able to do what I want:

```
protected void InstantiateCeilingLamp()
{
    Object ceilingLampPrefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));

    GameObject lampObject =
        Instantiate(ceilingLampPrefab, this.transform.position, Quaternion.identity)
            as GameObject;

    CeilingLamp ceilingLamp = lampObject.GetComponent<CeilingLamp>();

    if (CeilingLamp == null)
    {
        Debug.Log("Failed to instantiate the ceiling lamp.");
        return;
    }

    ceilingLamp.transform.SetParent(this.transform);
}

```

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


# Question
Title: Redistributing sprites in procedural generation according to player movement
I am making space arcade with procedurally generated background consisted of nebulas and stars sprites, which spawn on Awake() in certain borders around player.

Mobile phones have limited capacity so I want to redistribute sprites along the player's movement. E.G. if player reaches an empty area where is no sprites, I want sprites which farthest relatively to player to move in front of player. So player couldn't ever see an empty area. Notice that player can move in any direction in 2D space, not only up.

# Answer
> 1 votes
1. Add a BoxCollider2D to your nebula sprites which is as large as the sprite.
2. Add a Rigidbody2D with the Body Type "Kinematic" to your nebula sprites.
3. Create an invisible game object centered on the camera.
4. Add a BoxCollider2D to the invisible object which is as large as the screen and has the "Is Trigger?" property activated.
5. Add a new script to the invisible game object which implements the `OnTriggerExit(Collider other)` event. In that script, check if `other` is a background sprite, and if so move it to the opposite side of the screen by assigning a new vector to its `transform.position`. When your world origin (world-space coordinates 0:0:0) is always in the center of the screen, then you can simply flip it on all axis' with `transform.position = -transform.position;`. When your camera is moving, the math gets a bit more complicated. How complicated depends on your actual scene setup.

---
Tags: unity, algorithm, procedural-generation, scripting, procedural
---


# Question
Title: I found out how to rotate both Sphere and Cube (1) like a Turret facing a target but why is it so hard?
I just added 3 objects to my scene to a new project. To be sure where the problem is I created a new project.

Then added to the scene: 2 Cubes and 1 Sphere 1 empty GameObject.

Cube is the target.

Sphere and Cube (1) are the Turret and both are childs of the empty GameObject. The script is attached to the empty GameObject.

The logic say if I will rotate the empty GameObject both Sphere and Cube (1) will rotate at the same time. But I found that if I'm not setting both Sphere and Cube (1) same direction before running the game they will never face to the target only the Sphere.

I had to figure out where is the Sphere facing direction before running the game and change the Cube (1) to face the same direction of the Sphere on the Z Blue axis.

I can't figure out yet and understand why is it so hard to rotate two objects at the same time to be facing the same direction (target).

Now it's working once the sphere and the cube (1) are facing same direction before running the game. It didn't work if I made them childs or parents or changed the Cube (1) position to 0,0,0 nothing.

They were both rotating but never faced the target only the Sphere faced the target.

So now each time I want to rotate two objects at the same time to face another gameobject like a turret, or cannon or anything that is built of two parts I need first to make them facing same direction ?

I guess I did something wrong but not sure what.

The script:

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

public class Rotateturret : MonoBehaviour
{
    public float speed = 3.0f;
    public GameObject m_target = null;
    Vector3 m_lastKnownPosition = Vector3.zero;
    Quaternion m_lookAtRotation;

    private void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (m_target)
        {
            if (m_lastKnownPosition != m_target.transform.position)
            {
                m_lastKnownPosition = m_target.transform.position;
                m_lookAtRotation = Quaternion.LookRotation(m_lastKnownPosition - transform.position);
            }

            if (transform.rotation != m_lookAtRotation)
            {
                transform.rotation = Quaternion.RotateTowards(transform.rotation, m_lookAtRotation, speed * Time.deltaTime);
            }
        }
    }

    bool SetTarget(GameObject target)
    {
        if (!target)
        {
            return false;
        }

        m_target = target;

        return true;
    }
}

```

Here is a link for a short video clip I recorded showing what I mean:

Video clip of the problem

# Answer
> 1 votes
Set the scale of your child cube to `(0.2, 0.2, 1)` instead of `(1, 0.2, 0.2)` so that it looks like it's facing the forward/z-axis. The rotation you are getting is correct. Visually it looks like it isn't because you incorrectly scaled the turret.

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


# Question
Title: OnTriggerExit() called when game object with collider component gets re-parented
I have an object `Hand`, with a rigid body attached to it. In every `Update()` call, the user's hand controller rotation and position are tracked.

In my scene, there is an object `Pin`, with a mesh collider attached to it.

In `OnTriggerEnter()` (inside the `Hand` class), `Pin` becomes re-parented to `Hand`. (`Pin`'s original parent is something else.)

My scene also contains other objects with colliders. However, these other objects do not get re-parented -- only `Pin` does.

Once this re-parenting takes place, `OnTriggerExit()` (in the `Hand` class) is called immediately. This is surprising to me -- I had expected `OnTriggerStay()` (in the `Hand` class) to be invoked instead, since `Hand` is still in contact with `Pin`.

Is such behaviour by design? Is there an elegant way of working around such behaviour?

**UPDATE:**

In response to this comment:

> Does the pin object have a parent before it becomes a part of the hand?

Yes. As mentioned in my post, `Pin`'s original parent is something else.

> Or is it placed inside another collider? And does the pin leave any of these collider areas when the parenting takes place?

As mentioned in my post, `Pin` **itself** has a mesh collider component attached to it. Perhaps I am not understanding the question correctly...

> You can prevent the hand's script from getting this OnTriggerExit by adding a seperate rigidbody to the pin.

I added a separate rigid body to the pin (setting `isKinematic` to `true`), but `OnTriggerExit()` inside the `Hand` class is still called immediately after `Pin` gets re-parented.

**MORE INFORMATION:**

* `Pin`'s original parent (before it gets re-parented to `Hand`) does not itself have a collider component.
* When `OnTriggerExit(Collider collider)` gets called immediately after the re-parenting takes place, the `collider` argument passed to the method is the `Pin` itself.

# Answer
> 1 votes
Re-parenting is a somewhat complicated operation in the physics world. In older versions of Unity it was recommended to disable colliders before changing parents, then re-enable them afterward, because it was a noticeably slow operation.

The physics system more or less has to remove the object from the whole world (triggering OnTriggerExits), then re-insert it into a new place. Even if that place ends up being equivalent, the physics engine either can't or just doesn't guarantee that up-front, so it conservatively handles all collision exit/enter events along the way to make absolutely sure no collision changes get missed.

So, it's generally a good idea not to reparent objects as a means to change their physics behaviour at runtime. Instead, you may want to consider using Joints to attach physics objects when you want them to move together.

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


# Question
Title: Stuttering movement when approaching boundary
I'm trying to limit my movement in the y-axis by checking if the position will be within the boundaries after the `Translate`. If it is, only then do I translate the `Player`.

```
public class Player : MonoBehaviour {

    private float speed = 5.0f;
    private float bottomY = -4.37f;

    void Start () {
        transform.position = new Vector3(0, -4, 0);
    }

    void Update () {
        Movement();
    }

    void Movement () {
        // vertical movement
        Vector3 yTranslateVector = Vector3.up * Input.GetAxis("Vertical") * speed * Time.deltaTime;
        float newYPos = (transform.position + yTranslateVector).y;
        if (newYPos > bottomY && newYPos < 0) {
            transform.Translate(yTranslateVector);
        }

        // horizontal movement
        Vector3 xTranslateVector = Vector3.right * Input.GetAxis("Horizontal") * speed * Time.deltaTime;
        transform.Translate(xTranslateVector);
    }
}

```

However, when I do this, the `Player` kind of pauses when approaching the boundary and then stutters forward towards the absolute limit upon releasing the key. I tried putting the `Movement` function in the `Update` and `FixedUpdate` method, but neither made any difference. Can anyone give me any insight into this?

# Answer
> 3 votes
Instead of cancelling the movement outright when we near the boundary, we can instead shorten our movement to reach the boundary without overshooting.

```
Vector2 input = new Vector2(
       Input.GetAxis("Horizontal"),
       Input.GetAxis("Vertical"));

// Optionally, clamp input to a disc so you don't move faster diagonally.
if(input.sqrMagnitude > 1f)
    Vector2.Normalize(input);

// Compute where we want to be after we take or full movement.
Vector3 step = input * speed * Time.deltaTime;
Vector3 destination = transform.position + step;

// Clamp the y so we don't go lower than min or higher than max.
destination.y = Mathf.Clamp(destination.y, minY, maxY);

// Move to the clamped position.
transform.position = destination;

```

Note that in this form, if we approach the boundary diagonally, our y movement will get cut short but we'll still take our full x movement - like we hit the wall and then slid along it. Sometimes this can feel less abrupt than hitting the wall and stopping, but it does change the net direction of movement to a shallower angle than the player had input. If you prefer to stop at the first intersection with the boundary, we can do it like this:

```
// Compute how far we've exceeded our bounds vertically.
float outOfBounds = Mathf.Max(destination.y - maxY, minY - destination.Y);

if(outOfBounds > 0f) {
    // Calculate the fraction of our move that was in-bounds.
    float absY = Mathf.Abs(step.y);
    float inBoundsFraction = (absY - outOfBounds)/absY;

    // Shorten our step to just that in-bounds fraction,
    // scaling evenly on both axes.
    destination = transform.position + step * inBoundsFraction;
}

```

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


title: Limit PvP dogpiling

text:
# Question
Title: Limit PvP dogpiling
Browser-based strategy game where you play an empire vs other player empires. The main PvP element is battles between empires where outcome results in gaining or losing rank. Troops are also damaged/lost in battles.

You can only declare war (enables battles) against empires of a similar rank. War then remains active until one side surrenders, lost too many battles or there was no battles for x amount of time. This works fine as far as making any single war reasonably balanced at the time it starts. Wars are 1 on 1 but you can be involved in several simultaneously effectively making 1 vs many possible.

I would like diplomacy and alliances to be a part of the game, but I also want to prevent excessive dogpiling. The difficulty here is finding a working middle road between:

**A.** No simultaneous wars (if someone is already at war you cannot attack). This results in "phony wars" as players go to war just to prevent anyone else from attacking them while building up for a real one.

**B.** No attack restrictions which easily results in everyone within rank range jumping some poor guy and wrecking him.

Some mechanics I already have related to this are:

* For each war you have a stance for your troops ranging between Defensive-Offensive. Offensives will tax your economy more but is needed to push for a conclusive victory.
* Defenders advantage applies when fighting defensively inside your own territory.
* Less gains from winning against lower ranks which comes into play for many vs 1 wars when the 1 starts losing rank from surrenders/lost battles.

This makes dogpiling less profitable, could even be a net economic loss for most winners. Doesn't matter though, players still do it.

I'm fine with many vs 1 wars sometimes happening, the challenge is to have it be the exception rather than the norm. My current line of thought is to not limit the option of doing it but to keep tacking on more penalties until it gets to an acceptable level. What I'm looking for with this question is examples of rank-based systems which achieved this already and/or suggestions of new mechanics that would take my game in this direction.

# Answer
When you don't want players to do something, don't give them an incentive to do it. When it is neither damaging for the victim nor an advantage for the attackers, then there is no point in doing it at all and players won't bother to organize it.

Consider to not have any penalty at all for losing a defensive war (including not losing any units or other resources). So only the attacker is at risk of losing their score and resources when they start a war. That way dogpiling will be a victimless crime.

You could also make it a pointless crime. Limit the amount of resources which can be won by attacking a given player in a given timeframe. So when 10 players gang up on one target at the same time, each one only gets 10% of the usual reward at most (score and resources). This, however, opens up a new exploit: starting phony wars to reduce the reward of the "real" attackers.
> 1 votes

# Answer
One way to limit the phony war exploit of Philipp's answer would be to have a rule of transitive agression.

A is at war with B

A is not an ally of C

C attacks B

C is now at war with both A and B

Effectively if someone decides to dogpile, they have to fight everyone, not just their intended target.

Coupling that with Philipp's suggestion of "divide the spoils among the allies" your player choice is to either fight everyone by yourself, and keep all the reward for yourself; or pick a side and split the reward with your allies.
> 1 votes

---
Tags: game-design, mmo, ranking, matchmaking
---


title: Unity Destroy Unused GameObjects

text:
# Question
Title: Unity Destroy Unused GameObjects
I'm trying to access a method in another script without using the keyword "static";

```
public void CreateFarm()
{
    new Farm().NewResourceBuilding(gameObject);
}

```

My question is; will Unity automatically delete this object once it's done calling the method? Or will I need to manually destroy it? If the latter, how will I go about that?

I've searched on Google and been on this problem for a few days until I've finally come to this solution lol. So annoying to reference a static yet want to add a gameobject via the inspector.

---

**Edit** (Left the previous content untouched as some of answers already provided for the above might be useful to others). I have since revised my code and the flow.

I have a scene with a number of "empty lots" which I use images as placeholders childed to a Canvas.

**The following steps occur:**

Clicking on any of these images calls Unity's event system to open a panel, from the onclick options of the inspector. This panel will allow me to select from a number of different buildings to construct.

**ChangePanels.CS**

```
public void RuralBuildingSelected()
{
    empirePanel.SetActive(false);
    characterPanel.SetActive(false);
    ruralBuildingPanel.SetActive(true);
}

```

*Why I wanted to avoid "static" was because no static method is callable from the inspector (AFAIK). I could have created my own script and called a public onclick, but perhaps one of you might be able to advise which option of these is more efficient.*

Whichever "emptylot" I clicked on, I wanted them to send through their data into a manager script so whatever building I built, could replace the emptylot.

**EmptyLot.CS**

```
public void CreateFarm()
{
    new GameManager().GetEmpty(gameObject);
}

```

The following follow gives you an option of a number of buildings to construct. If I click on the farm, I need to;

* Instantiate a new Farm
* Parent it to the emptyLot's parent
* To replace the emptylot with the new farm, I set them to have the same positions
* Destroy the emptylot that called the new farm into existence
* Bring back the main panel

**Farm.CS**

```
new public void NewResourceBuilding(ResourceBuildings resource)
    {
        Farm newFarm = Instantiate(resource) as Farm;
        newFarm.transform.SetParent(GameManager.emptyLot.transform.parent);
        newFarm.transform.position = GameManager.emptyLot.transform.position;
        newFarm.levelText = newFarm.GetComponentInChildren<Text>();
        newFarm.name = resource.name;
        Destroy(GameManager.emptyLot);
        GameObject main = GameObject.Find("Main Canvas");
        main.GetComponent<ChangePanels>().MainScene();
    }

```

**My Questions:**

1. The "EmptyLot.CS" script creates a new GameManager to call a public method. I don't reference the object. Will this automatically be added to the garbage collector or should I just destroy it after using it? If I need to destroy it manually, how would I go about that?
2. I note that if I went ahead with the static methods and implement my own OnClick() method I can condense this to just two scripts instead of the three. So should I do that? Or based on the above code, is it just as efficient to keep it the way it is? I'm not a pro at this, but inline with Wondra's comment (to Almo's answer) it does seem like the approach of creating objects to delete instantly is a performance issue?

Thank you for taking the time to read/help/advice

# Answer
I'm going to take a step back here because I think there's some confusion about fundamentals of the C# language and how it works in Unity.

Firstly, what happens when I say `new Foo()` in this method...

```
void DoSomeFooStuff() {
    new Foo().DoSomeStuff();
}

```

...depends on how the `Foo` type is defined.

* If `Foo` is the Unity type `GameObject` then it creates a `GameObject` and adds it to the current active scene. That's an object you can see & select in the hierarchy, move in the scene view, has a name, layer, tag, a Transform component, and can have other components attached to it in the Inspector or with `AddComponent<>()`.

Because the scene now holds a reference to this `GameObject`, it will not be automatically be cleaned up. Other scripts can obtain a reference to it by walking the scene hierarchy or using various `Find` methods. It will stay persistent until you manually `Destroy()` it, or until you unload the scene it's in.

Not every object you work with in a Unity game is a `GameObject`. Most objects you create this way will not be `GameObject`s, so I think your title "Destroy unused GameObjects" might be misleading. It doesn't look to me like Farm or GameManager are `GameObject`s (though since you haven't shown us their definitions or constructors, it's hard to know exactly what they are or do)
* If `Foo` is a `struct`, then this puts a `Foo` instance straight onto the stack with a default initializer (eg. all numeric members default to 0), works with it in place, then pops it back off the stack when the function returns. No further cleanup is needed.
* If `Foo` is a `class`, then this allocates space for a new `Foo` instance on the managed heap (a new garbage collector allocation), initializes its fields, and constructs it using its parameterless constructor if it has one.

After that line has executed, there are no more references pointing to this `Foo` instance and it is now effectively garbage. It's still taking up space in memory, but nobody can call on it to do anything useful because nobody has a reference to it.

The next time you ask the memory management system for more memory than it can immediately serve, it will invoke the garbage collector, which will mark everything that's still referenced and delete what's not. At that point this garbage goes away and you get the memory back. (This is a slight simplification ignoring generational garbage collection and compaction. But for a small & short-lived allocation like this those details don't change the conclusion)

+ A caveat to this is if `Foo`'s constructor method `Foo()` stores a reference to itself somewhere, like in a master list of `Foo` instances (similar to how `new GameObject()` stores a reference to the new `GameObject` instance in the scene hierarchy). If it does, then it's not garbage as far as the GC is concerned, and it won't be reclaimed until after all references to it are gone.

---

Okay, with all that out of the way, I'd recommend a substantial refactor here.

You already have an empty lot that can accept clicks. Instead of thinking of it as an "Empty" lot that needs to be destroyed when built upon, or possibly recreated when the building is removed (more object creation & deletion, allocation & garbage collection), why not just think of it as a "Lot" that can hold multiple building types?

```
public class BuildingLot : MonoBehaviour {

    public IBuildingComponent currentBuilding;
    public GameObject emptyVisual;

    // This slot instance can handle the job of receiving clicks
    // & managing building selection state.
    public void Select() {
        // If we have a building,
        // delegate our selection behaviour
        // to that building's unique functionality
        if(currentBuilding != null) {
            currentBuilding.Select();
            return;
        }

        // Otherwise, tell the building manager an empty slot
        // has been selected, so it knows to display the right
        // building UI, and knows which slot to build on next.
        BuildingManager.GetInstance().SetSelectedLot(this);
    }

    // Your building manager can call this on the currently selected slot
    // when a particular building type button is pressed.
    public void Build(IBuildingComponent buildingPrefab) {
        // Alternatively, we can recycle an existing building
        // instance from an object pool, rather than allocate a new one.
        currentBuilding = Instantiate(buildingPrefab);
        currentBuilding.transform.SetParent(transform, false);

        // Hide any "blank/buildable slot" graphics or effects.
        emptyVisual.SetActive(false);

        // The new building instance can figure out what setup is
        // appropriate for the new lot it finds itself in.
        currentBuilding.Initialize(this);
    }

    // If you have a clear / destroy method, you can restore the slot to empty.
    public void Clear() {
        if(currentBuilding == null)
             return;

        // Clear our building (or recyclce it back to an object pool)
        Destroy(currentBuilding.gameObject);
        currentBuilding = null;

        // Restore normal empty appearance.
        emptyVisual.SetActive(true);
    }
}

```

Your build method then just needs to select the right prefab based on which button was clicked, and pass it to the currently selected `BuildingLot` to construct. The configuration logic can live in the building component's `Initialize(BuildingLot lot)` instance method, so you're working with the instance of eg. `Farm` you actually want to keep, rather than constructing a throwaway first.
> 2 votes

# Answer
C# has a garbage collector, and will automatically get rid of unused objects.

However, do not use that as an excuse to allocate and forget about objects a lot. Over time it will fragment memory and cause problems.
> 0 votes

# Answer
From the code you posted it is not possible to tell whether the `Farm` object that will be created will be destroyed or not by garbage collection. It is true that C# has garbage collection and if no references exist to the `Farm` object then it would be deleted, but when an object is instantiated it could run a constructor method that could create a reference to itself in some other part of your program. The Singleton Pattern mentioned in the comments is actually an example of a time when you might set a reference from a constructor. In a case like this you should manually destroy it to be sure. It could save you time debugging issues in the future.
> 0 votes

# Answer
You can use the code:

```
 Destroy(gameobject);

```

at the end of the process in the gameobject you want to dispose.
> 0 votes

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


# Question
Title: Why the transform never rotate between the range angle of 70 and -70?
When running the game the rotationRange is always 0.

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

public class Rotateturret : MonoBehaviour
{
    public enum RotateOnAxis { rotateOnX, rotateOnY, rotateOnZ };
    public bool randomRotation = false;
    [Range(0, 360)]
    public int rotationRange = 70;

    private void Start()
    {

    }

    private void Update()
    {
        if (randomRotation == true)
        {
            rotationRange = Random.Range(rotationRange, -rotationRange);
            transform.Rotate(Vector3.right, rotationRange);
        }
    }
}

```

I want it to rotate on the x axis between 70 and -70

# Answer
> 3 votes
You need to flip the parameters, `Random.Range` wants the min value first, max second.

So `rotationRange = Random.Range(-rotationRange, rotationRange);`.

Also, are you sure that you want to reassign to `rotationRange`? That way negative numbers (or zero) will mess up your system on future iterations.

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


# Question
Title: How to delay jump to syncronize with an animation ?
I'm using Unity and First Person Controller. If i press the jump button, my charachter jump immediately. I want,instead, that jump movement starts after (for instance) 1 second, to be syncronized with a jumping animation I trigger.

How to do that ?

Thanks

# Answer
You can add delays with Coroutines.

```
IEnumerator Jump() {

    //code for starting the animation, however you are doing it
    anim.SetTrigger("Jump");

    //leave code and come back after a second
    yield return new WaitForSeconds(1);

    //your code for jumping
    rigidbody.AddForce(Vector3.up * jumpPower);
}

```

You then call this with `StartCoroutine(Jump());`. While the coroutine is waiting, the game will continue to do other things, like updating animations.
> 1 votes

---
Tags: unity
---


# Question
Title: Removing selectable elements from a 2 dimensional array
I am using a 2 dimensional array to set up the game board of an arkanoid-like game I'm making. I haven't really used 2d arrays before, but someone suggested this would work better for me than the list I was originally using. My problem is that when a brick spawns, I need to remove that element from the list of options for the random brick spawn location. My brick spawns are random, but with conditions. Other than the first one, they need to spawn touching another brick. For now, I am just trying to remove the locations that have already been spawned at. I thought maybe I could put an if statement around the brick spawning code that checks if the location is null. My problem with this method is that it has to choose a location, check if it is null, if it is then it has to check if it is touching another brick, and then finally place a brick if it passes both parameters. Once we get down to only a couple of locations left to pick though, it could go around for a very long time checking non-null locations before it finally finds the right locations, potentially bogging down the game significantly. I have posted my code below. I'm hoping someone has a good suggestion on how to do this because I can't seem to come up with anything solid. I'm open to completely revamping if need be, but I really feel like the 2 dimensional method is the best path. Thank you!

```
private int columns = 20;                //Number of columns in our game board.
    private int rows = 30;                  //Number of rows in our game board.

    public int brickCount;               //Number of bricks to spawn.

    //Define brick types to assign sprites to in editor
    public GameObject oneHitBrick;
    public GameObject twoHitBrick;
    public GameObject threeHitBrick;
    public GameObject explodingBarrel;  //temporarily represented by the unbreakable brick

    private Transform boardHolder;                                  //A variable to store a reference to the transform of our Board object.
    //private List <Vector3> gridPositions = new List <Vector3> ();   //A list of possible locations to place tiles.
    private Vector3[,] gridPositions;
    //Clears our list gridPositions and prepares it to generate a new board.
    void InitialiseList ()
    {
        //Clear our list gridPositions.
        Array.Clear(gridPositions, 0, gridPositions.Length);
        //gridPositions.Clear ();

        //Loop through x axis (columns).
        for(int x = 1; x < columns-1; x++)
        {
            //Within each column, loop through y axis (rows).
            for(int y = 22; y < rows-1; y++) //start at 22 so no bricks can be spawned below this line.
            {
                //At each index add a new Vector3 to our list with the x and y coordinates of that position.
                gridPositions[x,y] = new Vector3();
            }
        }
    }

    //RandomPosition returns a random position from our list gridPositions.
    Vector3 RandomPosition ()
{
    //Create 2 random ints to choose the grid position for a brick
    int randomIndex1 = Random.Range (1, gridPositions.Length);
    int randomIndex2 = Random.Range (1, gridPositions.Length);

    //Declare a variable of type Vector3 called randomPosition, set it's value to the entry at randomIndex from our List gridPositions.
    Vector3 randomPosition = gridPositions [randomIndex1,randomIndex2];

        //Remove the entry at randomIndex from the array so that it can't be re-used.
        gridPositions[randomIndex1,randomIndex2] = null; //Error: Cannot convert null to 'UnityEngine.Vector3' because it is a non-nullable type

        //Return the randomly selected Vector3 position.
        return randomPosition;
    }

    //LayoutObjectAtRandom accepts an array of game objects to choose from along with a minimum and maximum range for the number of objects to create.
    void LayoutObjectAtRandom (GameObject brick, int brickCount)
    {

        //Instantiate objects until the randomly chosen limit objectCount is reached
        for(int i = 0; i < brickCount; i++)
        {
            //Choose a position for randomPosition by getting a random position from our list of available Vector3s stored in gridPosition
            Vector3 randomPosition = RandomPosition();

            //Instantiate tileChoice at the position returned by RandomPosition with no change in rotation
            Instantiate(brick, randomPosition, Quaternion.identity);
        }
    }

    //SetupScene initializes our level and calls the previous functions to lay out the game board
    public void SetupScene (int level)
    {
        //Reset our list of gridpositions.
        InitialiseList ();

        brickCount = (int)Mathf.Log(level, 2f); //set the number of bricks based on the current level

        //Instantiate a random number of wall tiles based on minimum and maximum, at randomized positions.
        LayoutObjectAtRandom (oneHitBrick, brickCount);

        //Instantiate a random number of food tiles based on minimum and maximum, at randomized positions.
        LayoutObjectAtRandom (twoHitBrick, brickCount);

        LayoutObjectAtRandom (threeHitBrick, brickCount);
    }

```

# Answer
The challenge here is that you actually want to track a couple of related but different things: occupied positions & candidate positions. One solution is to use one to derive the other as needed. That would work & might save some memory, but it comes at the expense of speed, and in my opinion, solution clarity.

Instead, what I would suggest is to track both separately. Furthermore, I would use a combination of both arrays & lists as I think it makes for a bit more solution clarity. The arrays are nice because you can easily check & update any position in the grid of used & candidate positions. However, the dynamically sized lists are handy for things like randomly selecting a valid candidate & reporting all the spawn locations without iterating over the whole works.

Finally, the `Point` class is useful because it bundles up the notion of an X,Y coord in a single object. So instead of having to track the coordinate parts separately, we can just keep a list of points.

The solution overview is:

* Place your first brick, either manually or randomly.
* Each time a brick is placed check its neighboring positions.
* If a given neighboring position hasn't already been spotted before, add it to a list of candidates.
* There after, you can easily select a random candidate position from the list built in the previous step.

C# isn't my primary language, but I took a shot at some demo code (also available here):

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Drawing;

namespace Rextester {
    public class Program {
        bool[,] hasBrick;
        bool[,] alreadyOpen;
        List<Point> openPositions;
        List<Point> brickPositions;
        int width;
        int height;

        public void Init() {
            width = 20;
            height = 10;
            hasBrick = new bool[width,height];
            alreadyOpen = new bool[width,height];
            openPositions = new List<Point>();
            brickPositions = new List<Point>();
        }

        public void AddBrick(int x, int y) {
            // if there's already a brick here, bail out
            if (hasBrick[x,y]) {
                return;
            }
            // add the brick
            hasBrick[x,y] = true;
            brickPositions.Add(new Point(x,y));
            // add legal neighboring candidate locations
            if (x+1 < width && !alreadyOpen[x+1,y]) {
                openPositions.Add(new Point(x+1,y));
                alreadyOpen[x+1,y] = true;
            }
            if (x-1 >= 0 && !alreadyOpen[x-1,y]) {
                openPositions.Add(new Point(x-1,y));
                alreadyOpen[x-1,y] = true;
            }
            if (y+1 < height && !alreadyOpen[x,y+1]) {
                openPositions.Add(new Point(x,y+1));
                alreadyOpen[x,y+1] = true;
            }
            if (y-1 >=0 && !alreadyOpen[x,y-1]) {
                openPositions.Add(new Point(x,y-1));
                alreadyOpen[x,y-1] = true;
            }
        }
        public Point GetRandomOpenPosition(Random rng){
            int index = rng.Next(openPositions.Count());
            Point result = openPositions[index];
            openPositions.RemoveAt(index);
            return result;
        }
        public void Display() {
            for(int a=0; a<height; a++) {
                for(int b=0; b<width; b++) {
                    if(hasBrick[b,a]){
                        Console.Write("#");
                    }
                    else if(alreadyOpen[b,a]) {
                        Console.Write("O");
                    }
                    else {
                        Console.Write(".");
                    }
                }
                Console.WriteLine();
            }
        }
        public static void Main(string[] args){

            Random rng = new Random();
            Program app = new Program();
            app.Init();
            app.AddBrick(4,7);

            for(int a=0; a<25; a++){
                Point p = app.GetRandomOpenPosition(rng);
                app.AddBrick(p.X, p.Y);
            }

            app.Display();
        }
    }
}

```

Note: I wasn't able to infer exactly how you are defining neighbors, so I assumed north, south, east, west. If you want diagonals, you'll need to add the corresponding four additional candidate position checks (NE, NW, SE, SW) in the `AddBrick(..)` method.
> 1 votes

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


# Question
Title: Changing the hit box position in melonjs
I'm trying to follow the platformer tutorial from the melonJS website, but using assets from kenney.nl instead of the tutorial assets. My problem is that the hit box is always centered at the center of the entity, and I need to move it. I've looked through the docs, and I can not figure out how to do it.

# Answer
if your on an unity based tutorial, you should be able to change how far the collider's center is from the objects center in the inspector, but it would be easier to answer if I knew what engine your using.
> 0 votes

# Answer
You can simply change the anchor point to fix this. Inside the entity constructor, modify the anchor point to match the correct placement using,

```
this.anchorPoint.set(x, y);

```

x and y can be the offsets.

If you are experiencing irregular sprite flipping, simply modify the offsets accordingly in the update function.

https://melonjs.github.io/melonJS/docs/me.Renderable.html#anchorPoint
> 0 votes

---
Tags: javascript
---


# Question
Title: Unity use image to load prefabs along a line
Say I have an image of PNG or a bitmap with a line zigzagging through it. I have done quite a bit of research in the answer still eludes me to how to use an image in unity and have it generate Primitives IE cubes along a black line in the bitmap. If anyone could just point me in the right direction as far as the tutorial or information that will get me started that will be great.

Ok so take the image below. What I am attempting to do is where the black line is instantiate a cube. I pretty much have the code written but the 4 issues I am having is 1. Identifying if black is found in my Color\[\] variable 2. Getting the blocks to render on the black lines without overlapping 3. Not freeze when generating the blocks.

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

using UnityEngine;

public class MazeGeneratorV1 : MonoBehaviour {
public Texture2D img;
public GameObject wall;
public int unitWidth = 10;
public int unitHeight = 10;

// Use this for initialization
void Start () {
    Pixelreader();
}

private void Pixelreader()
{
    //img = (Texture2D)Resources.Load("test2.png");
    for(int w=0; w < img.width; w++)
    {
        for(int h=0; h < img.height; h++)
        {
            Color[] colors = img.GetPixels(w, h, 10, 10);
            print(colors);
            if (colors == Color.black)
            {
                print("wall");
                Instantiate(wall, new Vector3(w,0,h), Quaternion.Euler(0, 0, 0));

            }
        }
    }
  }
}

```

# Answer
> 1 votes
You are honestly almost there I gather from the source code you have in your question. What it appears to me that may account for things not showing up right is you are not including the size of the `wall` (prefab? Sorry I am not well versed in Unity). So when you set the position you will want it to be the h and w times the size of the prefab, otherwise you are just offsetting their position by the value of 1 for every given row/column.

For example, if you have 11 blocks in a row starting at 0,0 your second block is going to be at 1,0, then 2,0 and so on.. if your blocks are 10 units wide then it will not be until the 11th block that it would actually be outside of the first block placed down in the line and you actually want them to be placed down at 0,0 then 10,0 and 20,0 and so on so the blocks do not overlap.

You will also want to read this one pixel at a time I believe, right now the code looks like you are reading a 10x10 block instead of one at a time (assuming your image is 1x1 instead of 10x10 for the size of a block).

The code changes would be

```
Color[] colors = img.GetPixels(w, h, 1, 1);
if (colors[0] == Color.black)
{
    Instantiate(wall, new Vector3(w * wall.width, 0 ,h * wall.height), Quaternion.Euler(0, 0, 0));
}

```

This offsets the positions by the coordinates of the pixels in the image multiplied by the width and height of the `wall` object.

This should handle issues 1 and 2... 3 is going to be a bit harder because you are doing rather slow processing and creating -alot- of objects in this manner. For example if its a 128x128 image then you are doing a color check of 16384 pixels and generating possibly that many wall objects as a worst case scenario.

There are a few things you could try but Ill not be able to write the code for them or run them to see if they improve the situation. I will however explain how they can help.

1) Expand the size of the wall when you instantiate it to the size of all of the black pixels you read consecutively or until you reach the end of the row. You can calculate the size you would need by the default wall size and the number of pixels you read so you create one object that would take you from the top left corner to the opening near the middle and then the other side of the opening all the way to the top right corner. This could potentially reduce the number of `wall` objects you have to `Instantiate()`. You could also make this logic a bit more complicated and try to handle vertical lines as well.

2) Your maze seems to have a set size between two walls. You could read only the first pixel and see if its black then assume the next X amount must also be solid because it should either be a passable edge or a solid wall. This would then let you lower the amount of times you have to check the image and just increment your `h` and `w` by the amount of pixels that have to be set in order to give you a wall for that section or an opening. Of note, this optimization could also be done with suggestion 1.

3) You could break apart the creation of the blocks so you only do a certain number of them at a time. I believe a coroutine would be of use here as you can yield after reading a certain number of pixels or more likely after creating a certain number of `wall` objects. This will let other systems run for a frame or so and then return to generate more objects for you.

4) You could find a better format than using the image for laying out your maze. Right now the image is -mostly- empty space which means you are going to spend a lot of the time processing it to do nothing. You could do some pre-processing to take an image and just generate the coordinates that contain a block in them so you are only processing the black lines and use that data to `Intantiate()` the `wall` instances.

5) You can actually do all of the above suggestions at the same time. They are of all different levels of difficulty depending on your development situation and your time requirements but you could get a better data format to only contain the objects you need to create (update the new format to be the coordinates AND the height and width of the wall to create). You could scan from a solid point Horizontal OR Vertically until you reach the end of a row or column respectively to reduce the number of blocks you have to create.. And you can also do this in a coroutine to 'time slice' the processing across multiple update loops so as to not freeze your application, for too long in any case.

EDIT: 6) You could make specific prefabs for each 'section' of the maze. Each section has a combination of four walls, you could use that to your advantage and create your prefabs to have just the four corners but no blocking walls (a four way intersection), another one with a wall across the top and bottom (a horizontal hallway), another one with a wall on the left and right (a vertical hallway) and then ones for a left turn or a right turn (wall across the top and to the right but the bottom and left side open for example) and finally a set of dead ends coming in from one side (opening on the top but a wall on the left, right and bottom sides). The hard part here is identifying which of the prefab shapes you would need from the image. This is not overly difficult but does require checking I think at a minimum of four values per 'grid' such as (1,0) to see if the top wall is there (assuming each prefab will always have a column in each corner at the least). (0,1) would then get you the left wall. (GridSize, 1) would get you the left wall and (1,GridSize) would get you the bottom wall. As 5 states, this could also be incorporated with the other 4 options as needed to further optimize.

I hope this helps, you seem to be on the right track for the first two issues. I hope the 6 examples of how to speed it up/not lock up the application give some assistance in that area as well. I will admit it is a bit harder with out knowing more details, those are just general things you can try of increasing difficulty (in my opinion).

Note: I do not see a fourth issue actually listed in the question as of the writing of this answer.

---
Tags: unity, image, gameobject
---


title: LWJGL Thin Matrix tutorials GUI

text:
# Question
Title: LWJGL Thin Matrix tutorials GUI
I have a question about the GUI implemented by Thinmatrix. For positions we have to use values between \[-1, 1\]. This is probably because the origin of the screen is the center and then we have a 1 by 1 grid. Is there a possibility to change this up, and reposition the origin to for example the top left corner, and make the screen a lot bigger to use absolute coordinates instead of values between \[-1, 1\]

Thanks,

# Answer
> 0 votes
The coordinates are in normalized device coordinate range, because no further transformation is applied.

You can set up an orthographic projection matrix with appropriate values to get the desired behavior. I would suggest using a math library, contrary to what he does in the tutorials, because you really don't need to write everything yourself. JOML is a good one for this.

In your shader, just multiply your `gl_Position` by it. That's it.

---
Tags: gui, lwjgl
---


# Question
Title: How to make a property visible in the inspector window if another property is true
How can I make one condition visible in the inspector window if another is true and hidden if false? For example, if `isLightON = true` then `isLightBright` should be visible else if `isLightON = false` then `isLightBright` should be hidden. I know this is suppose to be done using editor coding but not sure exactly how it is to be done.

# Answer
> 4 votes
The links Hellium shared seem to all go about this by defining a custom editor to draw the whole inspector view for the object. This certainly works, but it can get a bit laborious for more complicated components. If you want to use these hidden attributes on a bunch of different types, then you end up re-writing and maintaining a lot of boilerplate.

I wanted to find something I could just slap on when I wanted something hidden. Something like...

```
public bool isLightOn = false;

[ConditionalProperty("isLightOn")]
public float brightness;

```

The idea is we'll pass to `ConditionalPropertyAttribute` the name of the bool that should control this property's visibility, then use that to decide whether to draw the control. (If you wanted to get really fancy, we could extend this to support expressions, like "myIntValue \> 5" or "valueA != valueB")

Here I've defined a custom property attribute to mark the sometimes-drawn fields and store the criteria we'll use to decide whether to draw them:

```
public class ConditionalPropertyAttribute : PropertyAttribute {

    public string condition;

    public ConditionalPropertyAttribute(string condition) {
        this.condition = condition;
    }
}

```

And then, in an `Editor\` folder, created a custom property drawer to control how fields with this attribute are dawn (or not):

```
using UnityEditor;

[CustomPropertyDrawer(typeof(ConditionalPropertyAttribute))]
public class ConditionalPropertyDrawer : PropertyDrawer {

    // Determine whether this field should be visible.
    // (We could probably do some caching here...)
    bool ShouldShow(SerializedProperty property) {
        var conditionAttribute = (ConditionalPropertyAttribute)attribute;
        string conditionPath = conditionAttribute.condition;

        // If this property is defined inside a nested type
        // (like a struct inside a MonoBehaviour), look for
        // our condition field inside the same nested instance.
        string thisPropertyPath = property.propertyPath;
        int last = thisPropertyPath.LastIndexOf('.');
        if (last > 0) {
            string containerPath = thisPropertyPath.Substring(0, last + 1);
            conditionPath = containerPath + conditionPath;
        }

        // Get the SerializedProperty representing the field that is our criterion.
        var conditionProperty = property.serializedObject.FindProperty(conditionPath);

        // For now, we'll only support bool criteria, and default to visible if there's a problem.
        if (conditionProperty == null || conditionProperty.type != "bool")
            return true;

        // Use the condition property's boolean value to drive visibility.
        return conditionProperty.boolValue;
    }

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
        if(ShouldShow(property))
            EditorGUI.PropertyField(position, property, label, true);
    }

    public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
        if (ShouldShow(property)) {
            // Provision the normal vertical spacing for this control.
            return EditorGUI.GetPropertyHeight(property, label, true);
        } else {
            // Collapse the unseen derived property.
            return -EditorGUIUtility.standardVerticalSpacing;
        }
    }
}

```

What I like about this approach is I only need to write the above attribute & drawer once, and they work for any number of hidden fields in any number of types, and the fields I'm hiding can be of any type the Inspector knows how to draw, including elements of arrays. So the maintenance for adding/changing scripts is much lower than writing custom editors for every type that wants to hide some things.

---
Tags: unity
---


title: How to use base.Function() in Unity

text:
# Question
Title: How to use base.Function() in Unity
I am using 3 classes:

1. EnemyBullet : MonoBehavior
2. EnemyBulletType1 : EnemyBullet

EnemyBullet Class:

```
void FixedUpdate(){
    this.gameObject.transform.rotation = Quaternion.Euler (new Vector3 (0,0,90));
}

```

EnemyBulletType1 Class:

```
override void FixedUpdate() {
    base.FixedUpdate ();
    //Do something else here
}

```

The reason is I'll have many EnemyBulletType classes and I want them all to do a common thing and then do something on their own.

Question: This code isn't working: Error: virtual or abstract members cannot be private How is FixedUpdate() defined in the MonoBehviour and how to change it to help my usecase?

# Answer
> 1 votes
As indicated by the compiler, the function can't be private.

In C#, the default visibility is `private`. When you want to create virtual functions which can be overriden in sub-classes, you have to explicitely set the visibility to `public` (not advised here, because it's a MonoBehaviour function that should not be called by anything but Unity itself) or `protected`:

See MSDN documentation : https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual

> You cannot use the virtual modifier with the static, abstract, private, or override modifiers.

Indeed, if you want your subclass to know the function to override, the latter must be visible by your subclass (which is not possible if the function is private)

---

EnemyBullet Class:

```
protected virtual void FixedUpdate(){
    this.gameObject.transform.rotation = Quaternion.Euler (new Vector3 (0,0,90));
}

```

EnemyBulletType1 Class:

```
protected override void FixedUpdate() {
    base.FixedUpdate ();
    //Do something else here
}

```

---
Tags: unity, inheritance
---


# Question
Title: Do I need real socket connections to create AI Bot players in a multiplayer web game?
I have built a realtime multiplayer web game using WebSocket protocol.

In my game I create about 100 AI bot players to simulate playing the game with the real players. Every time a bot is dead the server will create a new one. I wonder if I need to simulate the Websocket connection and implement Websocket listeners like what I am doing at the moment.

I understand that creating new Websocket connections will use a lot of resources and maintaining the connections eat up resources on the server too. As I don't need to send anything to bot players I probably don't need to create real connections on the server.

The game is working fine. But I am looking for ways to improve. Let me know what you think.

# Answer
Hm... You shouldn't open those for AI characters, at least not for all of them, all the time. But this depends on your game.

Some assumptions: 1) There are more than one real player in the game. 2) They have to interact with AI players 3) There is some graphical user interface for the interaction.

What you have here is human players, AI players and "state of the world". If this was classical client-server game, it would have worked like this: Human player sends command to the server, server does the simulation of AI player, sends response. AI players literally "live" on a server and open connections towards player(s) only when they have to interact with them, either by touching them or by being seen by them.

Example: I'll take the example of the simplest socket 2D game there is: Agar.io . You have players, they eat each other. You have state of the world (which is, who ate how much, where is the location on the grid of each player etc). In this example, we have 1 human player. Thing is, the human player only needs to know the part of the world state which effects him/her. Let's say a human player is in position 0 and can see everything in a square of -10,-10 up to 10, 10 on x,y axes.

Basically, what happens, AI character opens a connection towards a player only if its location is such that is in that camera visible square or about to enter it. If it is not seen, it is being simulated on a server. Once it enters the camera, it starts to really exist and has to interface with the open connection to interact with the player. Now, the fun part: you only need one server connection with the single human player to simulate any number of AI players interacting with the human one! Why? Because AI opponents are on a server and what the player doesn't see, (s)he has to take on trust.

I could tell you that I am answering this question to you from the beach bar in Hawaii, there is no way for you to check. And that is true until you actually look (move the camera where I can actually be seen) in which case I have to prove it to you by opening socket connection to you and actually sending you a "picture". Basically, you could make AI character be in the first place and say it had eaten 100 other players and grown 10 times and it will be true until player actually comes to the location where the virtual AI player can be seen. Then your game would have to open a socket and show that monstrous, extremely good AI player to Human player. And then it turns from invisible simulation of 100 players to visible simulation of 10 visible AI players + human player.
> 1 votes

---
Tags: websocket
---


# Question
Title: Can a Component.gameObject be null in Unity?
Can a `Component.gameObject` be null in Unity? If it can what can cause it to be null?

The context for the question is a `NullReferenceException` I got from the users, which specifies only method, but not line in which it occurred.

So, I suspect that there may were conditions which cause `Component.gameObject` to be null.

# Answer
> 3 votes
It depends. Component.gameObject refers to the gameObject that the component (most likely your script) is from.

Therefore if you are referencing the 'gameObject' that the script is attached to it cannot be null (as the gameObject would have to exist for the script to exist and be running).

However, if you are referencing a component from a different GameObject and then using Component.gameObject to find its gameObject, but the gameObject has been deleted/removed before this, the Coponent.gameObject will be null. To test this, you could try to reference the component itself. If the gameObject is null, the component itself should be null too (as it cannot exist without its gameObject.

(EDIT: As pointed out in the comments I made a mistake here. This would in fact throw a null reference exception, or one of Unity's errors. This is because, although the value is practically null, there is no 'null' value assigned to the gameObject reference, as the gameObject doesn't exist anymore. So, as you are trying to reference something that doesn't exist, it will actually be an error. Sorry for not thinking this through. This means that this second scenario is actually impossible).

Most likely you are in the first scenario (where it cannot be null) and another factor is causing the exception. But without a more detailed description of the situation, this is the best I can do.

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


# Question
Title: How to make a prefab of a blood effect using provided shader/materials in 2D?
I want to create a blood splat effect as shown in this link: https://gfycat.com/CharmingThickFlies

The developer was nice enough to leave the source explain how to apply this. But I cant seem to follow the provided instructions. Instructions and code are here: https://www.reddit.com/r/Unity3D/comments/4108d1/new\_splatter\_shader\_effect\_im\_working\_on\_perfect/cyyj988/

I want to get this effect to a prefab level which I can then instantiate in my code.

I have followed link on youtube and read up on how to use shaders but I can't seem to apply this in unity and get a prefab. I have tried applying this to a particle level system but that also did not help.

Some guidance would be appreciated. Thanks

# Answer
The 'instructions' in the reddit comment are really desgined for people who know how shaders work. I'll try to break it down for you.

1. Make a new material (like you would make any other game object), and store it anywhere in your assets folder that makes sense for you
2. Download the shader file and attatch it to the material.
3. Download the other two texture files, and attatch them to the fields on the shader stated in the reddit comment (MainTexture in Main and NoiseTexture on Noise).
4. This is your completed material. All you need to do now is drag it to your Prefab folder and it'll make the material a prefab for you.

That's all there is to it. I think you mistook the comment for a tutorial when instead it was more a link to the files and how to put them together for anyone comfortable with shaders.
> 1 votes

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