# Question
Title: How can I store and load large 3D environments (terrains or cities)?
I am interested in how a large area 3D environment in games like Grand Theft Auto V or Far Cry can be stored (on disk, in what file format) and how that data can be retrieved when it is used in a game. By "the environment" I mean only static objects like terrain with vegetation, city areas with buildings, et cetera. I'm not referring to temporary or moving objects like people or cars. I am not interested in scene rendering.

I guess it may be convenient to shard (horizontally partition) the data by location creating something like "tiles" because it is usually accessed by location and such tiling will help to keep data that is related together (and reads will be faster). Also I guess the data for sure is stored in some (compressed?) 3D format with the respect to tiling. There probably have to be mechanisms that will split one object to two (or more) parts if it does not fit into a single tile.

I have found a somewhat related question (How a 3D game map is stored and handled) but it only briefly answers small part of my question.

# Answer
Large levels are usually stored, as you guessed, broken up into small levels that can be streamed in and out of memory as they are needed. Generally all of the information needed for each chunk of the world is stored with that chunk (terrain, buildings and props, vegetation, LOD information, et cetera) although in some cases there will also be an overall umbrella or container level, always loaded, which may impart some data to the individual streamed chunks as they are loaded.

The file format for this varies, generally every engine or framework will use something that is specific to that engine, usually optimized for getting that data off the disk and into memory in the format needed by the code as quickly as possible.

Objects generally are not sliced along the tile boundaries like you surmise. That's expensive and difficult to deal with. Usually an object will simply exist in one of the levels on the boundary, and not the others. Sometimes the object might be placed in *all* levels, but that also requires some management to handle correctly.
> 2 votes

---
Tags: terrain
---


title: Younger audiences and chat

text:
# Question
Title: Younger audiences and chat
Most multiplayer games have some sort of way to communicate. It is usually verbal, written, or emotive gestures.

If I were to allow young children, from 11 to 13, access to a game I'm creating where anyone can type anything, what would I need to do?

The things I can think of are; hide all chat, only allow other young players to talk to each other with a list of censored words, or just allow predetermined sentences and actions to be used.

# Answer
> 2 votes
Legally, you "just" need to comply with the appropriate child protection laws in your jurisdictions (you probably want to discuss this aspect of the issue with a lawyer). Although I put "just" in quotes because that might be a lot of work.

In the United States, for example, you have COPPA (among potentially other things), which basically means you can't collect personal information about a child without permission from a guardian. The bookkeeping involved there is so tedious that most organizations simply put a clause in their EULA to deny the service to under-13-year-olds (including StackExchange).

From another standpoint, you probably want to protect yourself from potentially-bad PR that might result from a story about a child being verbally harassed or otherwise exposed to something unsavory via interaction with other users of your game - regardless of whether or not you agree with that position on moral or ethical or whatever grounds.

A typical way to do this is to design you game to simply limit the range of expressible interaction that's possible with other players. Not just for young players, for *all* players (otherwise players are incentivized to lie about their age once they realize they are "missing" features of the game). Reducing interactions to a set of predetermined emotes or icon bubbles is a great way to handle this, and as a bonus may make it easier to port your game to consoles or other platforms where a keyboard is not a common input device.

Parental control options, as noted in the comments of your question, are another good idea, although not something particularly common. For young kids in the age range you're talking about, however, it's still likely that the parents are the ones actually purchasing and setting up the game and so it might be an avenue worth investigating if the "icon emotes" approach isn't what you're after. You can implement a range of options. Offhand, the ones I think might be useful are:

* disabling chat entirely
* disabling private messaging
* disabling or requiring confirmation of friendship requests
* a mode where customizations of other avatars (if possible in your game) isn't rendered; everybody appears in generic or default outfits
* two-factor-ish login approaches, where the parent must confirm a child's attempt to start the game

---
Tags: community-management
---


title: Semi-procedural mission generation

text:
# Question
Title: Semi-procedural mission generation
I want to generate missions out of more or less predefined smaller chunks. Example mission structure:

Mission type: Rescue

1. Travel through forest
2. Gather intel
3. Choice:
    * Sneak into castle (if it fails, switch to fight)
    * Fight your way into castle
    * Use clever disguise (if entry method available for castle and it was discovered in 2)
4. Rescue princess

The travel block is generic and could be applied to a number of different landscapes, giving different random encounters or events. Same goes for other types of blocks, the castle could be replaced with another building/location, the princess could be someone else etc.

As the example hints I want to do some more advanced things than just randomly link up a few mission chunks:

* Show expected mission layout to the player before accepting it
* Have optional blocks or choice between different blocks
* Change mission layout during the mission: "the princess is in another castle" = add one more travel block and one enter + rescue block
* Be able to increase variety later by adding additional objects like more location types
* Be able to inject special story blocks into the dynamic missions that will always happen eventually

Part of the strategy element in the game is choosing which missions you accept so a lot of them will be discarded and there must be enough variation to make this choice meaningful. You might be badly equipped for forest encounters, but well equipped for sneaking into castles. And rescuing a princess is high-reward so the mission could be worth taking - this is the kind of decision I want the player to make.

I could probably just code this together in a way that works for now, randomizing a mission type, starting with the end block and work backwards from there to the start block. There will be some dependencies, like available location types depending on terrain type or available block types depending on the overall mission type. This seems like the hard part, figuring out what needs to depend on what and where to start from.

Other dependencies that come into play are:

* Some missions types not becoming available until later in the story, easy to handle
* Overworld location does not have much effect on the abstract "map" generated by a mission, except that some terrain types will be more common depending on where you are
* Player may have access to various means of transport that will impact mainly the travel blocks
* Factions exist and are somewhat tied to terrain, like elves in forest
* If game world has a war between two faction I may want to spawn more combat missions against one or both of them depending on player allegiance

So do I generate elven enemies because I generated forest terrain first or do I change around my mission generation logic to look at target factions before terrain? (just an example of the kind of compromise I need to deal with).

Another model I considered but is not very keen on is having predefined fixed templates of missions to fill with blocks of appropriate types. I feel this could have me doing too much work the RNG could do for me instead and I might also have to consider template to mission type relationships.

My question is basically: Is there a strategy that would help me achieve this kind of mission generation in a relatively clean and maintainable way? A similar situation from your game that you can share lessons learned from?

Maybe there is not a perfect solution, but there are likely more or less good ways the problem can be approached in.

Game is a turn-based RPG/strategy game with OO design, but I don't think the details have a major impact for the concept I ask about. My object relationships are not set in stone yet. I think the dynamic mission-generation is a key factor in the game and if I find a good way to deal with that I may very well adapt other parts to work well with that model.

# Answer
> 3 votes
I assume that your game world is already fixed and now you are generating missions which work in that game world.

First of all, you need to know which mission types are actually possible in the location you have. For example, your "Rescue" mission type template requires:

* A location to gather intel
* A location to infiltrate (the terrain to traverse is implied: It's whatever lies between quest hub and location)
* An NPC to rescue
* An enemy faction which opposes the mission

These are localized features which would be created when you design/generate the game world and then be more or less persistent. If you generate these features ad-hoc when generating missions, your game world will feel awfully inconsistent. It will be obvious that you create people, locations and factions out of nowhere which the player really should have noticed before just to never mention them again after the mission is over. The world will feel much more immersive if the player hears about the evil elves with their menacing castle and meets the beautiful princess *before* getting the mission to rescue her.

So when the player is in a location in the game world where not at least one of each of these components is nearby, then this particular type of mission is impossible to generate here.

So I would recommend you to implement each mission type as a Factory for Missions: a `MissionFactory`.

Each `MissionFactory` would have a method `bool availableIn(worldLocation)`. That method would check the surrounding of that location to see if everything is present that's needed to generate a mission of that type. This is also the method where you check if certain *political* conditions are met (like your war mission example which would require two nearby factions which are currently at war with each other).

So if the player is in a quest hub and you want to generate a bunch of missions to pick from, you first need to filter your list of mission factories to those which are available in this quest hub by calling `availableIn(player.location)` and append those which return `true` to a list of available mission factories. Then when you want to create 10 missions, you take 10 random picks from that list (duplicates permitted) and call `missionFactory.generateMissionAt(worldLocation)` on each of it.

Optionally, you could use weighted randomness. `availableIn` could return not just a bool but a number which says how *probable* that mission is in this location. For example, "exterminate dangerous monster" might happen more often in rural areas while "assassinate political opponent" happens more often in urban areas, but each can still appear in the less likely location from time to time.

The `generateFrom` method of each mission factory would then generate a random mission consisting of random features in that world location.

---
Tags: game-design, architecture, quests, mission-design
---


# Question
Title: Component oriented programming for rich RPG world
I've asked this question on several forums but didn't get the proper answer yet.

So, in my opinion, it is a really theoritical and deep, but I really can't deal with it by myself.

**What is my goal?**

I want to create a TES-inspired (The Elder Scrolls series) RPG with a really behaviour-complex world, when as a player you can, for example, not only play on *guitar* as a *Musical Instrument*, but use it as a *Weapon* or, what is perhaps more unobvious, *throw it* right to the *furnace* to get some heat in a cold winter night.

**What did I get so far?**

I started with upper-level ontology, because such world must have really deep complex hierarchies. There were an `Entity`, then `MaterialEntity` (with time and space extensions) and `AbstractEntity` (`Notions`, `Relationships` and so on). `MaterialEntity` was divided to `Event`, `PhysicalObject` (with mass and temperature). The last ones consisted of `Creatures`, `Things`, `Substances` (like water which is uncountable in the same sense as apples) and so on.

Then there was a *big* problem with tree-like inheritance: in the previous example a guitar was a `MusicalInstrument`, `Weapon` and `Fuel` at one time, furthermore there are a lot of another ways to *interpret* the thing and interact with it.

I decided that OOP with it's 2D Types (2D because every entity can be placed in a simple table with rows and columns) paradigm just not fit well in such complex case (like Newton's force formula for Mercury) and I need something better.

**What did I tried?**

1. **Interfaces**. *Pros*: Simple and obvious. *Cons*: A lot of code duplications and hard *SRP*-violation. Just imagine how many `IOpeneable` things you will have in code (door, bottle, box, chest, window and so on).
2. **Strategy Design Pattern**. *Pros*: More reusability that interfaces. *Cons*: old remain with *DI* handling added.
3. **Components or Entity Systems**. Pros: A lot of reusability, no duplication at all. Seems like this is a good choice for me, but...

**The cons of COP (or just my misunderstanding)**

I think that *COP* seems great for my task (and for other games) because it makes all the static compile-time coupling more runtime and dynamic, but it sacrifies **a lot** for it: the intelligibility of code, because now you see

```
entity.GetComponent<Openeable>.Open()

```

or

```
entity.GetComponent<Inventory>.AddItem( anotherEntity.GetComponent<Item>() )

```

instead of

```
box.Open();

```

or

```
inventory.AddItem( weapon );

```

As a developer I want my code to reflect the domain as much as possible, so the whole `Component-Entity` paradigm looks strange because there are nothing like *components* or *systems* in real (or game) world. In another words: I want more that just shift compile-time to run-time as COP does sacrificing the clarity of code.

Sorry for such long introduction, I just wanted to clarify the problem as much as possible.

**The main question**

Are there modern extensions of `COP` so far or should I just use another paradigm for my problem?

Thanks for your attention!

# Answer
Taking the example of the guitar:

> (...) a player you can, for example, not only play on guitar as a Musical Instrument, but use it as a Weapon or, what is perhaps more unobvious, throw it right to the furnace to get some heat in a cold winter night.

First off, move away from using object inheritance to model this. Although, I want to note that using OOP is not wrong, but this kind of OOD (Object Oriented Design) doesn't yield well to what you want.

You should prefer Composition over Inheritance. If you can model `The Guitar has Musical Behaviour` instead of `The Guitar is a Musical Instrument` then do that.

---

Next up, you need to be able to plug in those behaviours. The reason is because you will not be able to develop systems for playing musical instruments, armed combat and item forge all at once. In fact, you don't want bugs of one of those systems to ruin the others... what you need is to "be open for extension, but closed for modification".

So, you need a way to extend composition.

This rasoning leads you stright to this option:

> *Components or Entity Systems*. Pros: A lot of reusability, no duplication at all. Seems like this is a good choice for me (...)

---

> but...
>
> (...)
>
> the whole Component-Entity paradigm looks strange because there are nothing like components or systems in real (or game) world

But there are! At least in the game world there would be. For example, you could create a game where there is no way to craft items, instead you need to get them from drops or buy them from NPCs... and then at a later date you can add a *forge system*... as part of this update you would add "meterial attributes" to the objects (or reuse some existing ones) to become crafting materials. So you see, the game world has systems.

Notice I say that the *forge system* is not a component of the objects. Instead I say that the object has "material attributes". This is because you don't need to add extra behaviour to the objects, just the relevant attributes that the new systems will manipulate or interact with.

---

About the "the intelligibility" and the "pretentiousness of code" (Is that measurable?)... you have options:

**1. Combine interfaces with components**

For example if you write a `IHasInventory` interface... instead of writing:

```
entity.GetComponent<Inventory>.AddItem( anotherEntity.GetComponent<Item>() )

```

You could write:

```
entity.Inventory.AddItem(anotherEntity);

```

Given that the variable `entity` is of type `IHasInventory` and `Inventory` is a property of that interface.

Of course, this approach means that you will not be adding components dynamically (unless this is a dynamic language). But, do you really need to add components in runtime?

Also, you will not be writing the logic for inventory a lot of times, because there would be a single `Inventory` class. So, no SRP concerns here.

**2. Use a more dynamic language**: For instance, with a dynamic type, in the line:

```
entity.Inventory.AddItem(anotherEntity);

```

Inventory could have been added in runtime:

```
entity.Inventory = new Inventory();

```

even if `Inventory` is not a property of `entity`. For example in JavaScript you can add attributes to an already created object.

**3. Embrace it**: You can be pretentious, I give you my blessing.

---

**Addendum: On dealing with damage**

> It looks more natural to see sentence "I attacked him" instead of "I get my weapon component to deal with it's armor component" or "The system check my input and calculated attack damage on guy"

It wouldn't be the "weapon component" and the "armor component". The first reasons being that the the target needs to be able to take damage, not just it's armor. The second reason...

You have a character that have weapons that have attributes. Usually some weapon will be equiped and the character attacks with that. You may also want to consider attacking without weapon. So you can think of the attack as being modified by the equiped weapon.

So, I suggest to think about it in terms of "cause damage" instead of attack. This will ease to implement things like buff/debuff mechanics or status effects that do damage over time (eg: poison).

In terms of "cause damage" you want to say something along the lines of "my character causes damage to the enemy"

```
myCharacter.Damage(enemy);

```

But that sounds like you need to implement `damage` multiple times... which is what leads you to write something like this:

```
myCharacter.Combat.Damage(enemy.Combat);

```

Or perhaps

```
myCharacter.Combat.Damage(enemy);

```

If you consider that there could be effects on various components. In my opinion that looks good enough... yet, what about wrapping that? You don't need to write like that each time, instead:

```
Combat.Damage(myCharacter, enemy);

```

Where `Combat` is a class that handles attacks, so you only would worry to populate in the entities the attributes you need to compute the damage.

About damage over time and other damage sources, you could consider the `Combat.Damage` method to be adding a damage source & damage target pair... then have a `Combat.Update` compute the actual damage and have it run as part of the game loop / tick / wolrd update method... this way `Combat.Update` will be able to compute damage over time, remove damage sources once they are done, or even add new ones for damage status.

**Addendum: "openable"**

There is no need to implement it as anything more than `IOpenable` interface with a `IsOpen` property. To open you could then write:

```
entity.IsOpen = true;

```

Or

```
entity.SetOpen(true); // for those languages >.>

```

So, this can be implemented just as attributes. Of course, you may choose to have `Open` and `Close` methods... although there is no need to.

Besides. You shouldn't implement an "Openable" as a class, because bein "Open" means something different for doors, chests, etc... So, I'm saying that "Inventory" class makes sense, but "Openable" class does not. In fact, I would question whatever or not having an abstraction for "openable" makes sense... but that depends on the game.

---

I want to note that I'm saying to use interfaces to access the components, intead of whatever component library you are using (with which you are clearly not happy about the syntax you need to use).
> 6 votes

# Answer
The whole idea of components is to break the code out into thier own domains. The side effect of doing that is you end up with nice small totally contained components.

I look at components as individual libraries. They should know nothing about the outside world. Because of this interfaces are a bad way to go in my view. Interfaces create coupling between components and said interface. Why would you need that? Instead components should have functions that work on thier internal state and events to tell the outside world what's going on inside the component. Those become your input and output for the component and it makes them 100% decoupled from everything so they can just do thier one specific domain and do it well. This also helps with performance because you can test each domain independently to see how it performs and make changes to just that component.

The question then becomes how do the components within a given game object communicate? They do so by having a unique script per unique game object. I call this the same name as the game object and append CommHub to it. This is the communication hub for all those components that make up this game object. In here is where you hook up all the components events to other components functions. You now have a central place to easily see how that game object works at a glance. This high level view of a game object is so valuable! The way ppl normally do things in Unity by accessing components from within components doesn't show you in one place how the game object works. It's messy, don't do that.

The question then becomes how game objects interact with other game objects and again while keeping them unaware of each other and thier components. This is where systems come in. Each interaction that has to happen gets a singleton systems class. This is the communication bridge between game objects components talking to each other. A system functions and a matching events. Again your game object comm hub script is where you hook components to systems. One game object component will raise and event which will call a system function. That system function in turn raises its matching event, which a different game object component in its comm hub subscribed to so it's function gets called.

This gives you two game objects who are oblivious of each other and isolated a way to communicate when an interaction needs to happen. Not to mention it makes the comm hub script the command central for all communication for each game object which is invaluable to see all in one place.

For ideas:

PlayerInput component fires events like onMoveForwardHit, onJumpHit. The Controller component has functions like MoveForward, Jump, Stop. It has events like onLanded. The Sound component has functions like PlayFootsteps, PlayLand.

Inside your PlayerCommHub script you hook all these events to functions. Next thing you know when you press the 'w' key your guy moves forward and is making walking sounds!

Extend this idea to everything in your game and you'll have a very decoupled, easy to maintain and change, and unit testable codebase!

Also don't use SendMessage because again it puts how your object works from a high level inside each component. Do you want to go through 20 source files flipping back and forth trying to follow flow of messages or do you want to see all component interactions in one source file (comm hub). This file as no is statement or loops. It simply has events being tied to functions. So easy to visualize what that game object is doing and how it interacts with other game objects and components.
> 1 votes

---
Tags: architecture, component-based, oop
---


# Question
Title: How do I set the Tag of joints[] to what I want in this script?
Hello I got this big script for building a Rope from position a to position b. The joints are getting instantiated but the tag is default, what I have to change in the script to set the Tag of the joints ?

"I didnt wrote this script!"

Here is the RopeScript:

```
public class RopeScript : MonoBehaviour {

public Transform target;
public float resolution = 0.5F;                           //  Sets the amount of joints there are in the rope (1 = 1 joint for every 1 unit)
public float ropeDrag = 0.1F;                                //  Sets each joints Drag
public float ropeMass = 0.1F;                           //  Sets each joints Mass
public float ropeColRadius = 0.5F;                  //  Sets the radius of the collider in the SphereCollider component
//public float ropeBreakForce = 25.0F;                   //-------------- TODO (Hopefully will break the rope in half...
private Vector3[] segmentPos;           //  DONT MESS!  This is for the Line Renderer's Reference and to set up the positions of the gameObjects
private GameObject[] joints;            //  DONT MESS!  This is the actual joint objects that will be automatically created
private LineRenderer line;                          //  DONT MESS!   The line renderer variable is set up when its assigned as a new component
private int segments = 0;                   //  DONT MESS!  The number of segments is calculated based off of your distance * resolution
private bool rope = false;                       //  DONT MESS! This is to keep errors out of your debug window! Keeps the rope from rendering when it doesnt exist...

//Joint Settings
public Vector3 swingAxis = new Vector3(1,1,1);               //  Sets which axis the character joint will swing on (1 axis is best for 2D, 2-3 axis is best for 3D (Default= 3 axis))
public float lowTwistLimit = -100.0F;                   //  The lower limit around the primary axis of the character joint.
public float highTwistLimit = 100.0F;                   //  The upper limit around the primary axis of the character joint.
public float swing1Limit  = 20.0F;                  //  The limit around the primary axis of the character joint starting at the initialization point.

void Awake()
{
    BuildRope();
}

void Update()
{
    // Put rope control here!

    //Destroy Rope Test (Example of how you can use the rope dynamically)
    if(rope && Input.GetKeyDown("p"))
    {
        DestroyRope();
    }
    if(!rope && Input.GetKeyDown("r"))
    {
        BuildRope();
    }
}
void LateUpdate()
{
    // Does rope exist? If so, update its position
    if(rope) {
        for(int i=0;i<segments;i++) {
            if(i == 0) {
                line.SetPosition(i,transform.position);
            } else
            if(i == segments-1) {
                line.SetPosition(i,target.transform.position);
            } else {
                line.SetPosition(i,joints[i].transform.position);
            }
        }
        line.enabled = true;
    } else {
        line.enabled = false;
    }
}

void BuildRope()
{
    line = gameObject.GetComponent<LineRenderer>();

    // Find the amount of segments based on the distance and resolution
    // Example: [resolution of 1.0 = 1 joint per unit of distance]
    segments = (int)(Vector3.Distance(transform.position,target.position)*resolution);
    line.SetVertexCount(segments);
    segmentPos = new Vector3[segments];
    joints = new GameObject[segments];
    segmentPos[0] = transform.position;
    segmentPos[segments-1] = target.position;

    // Find the distance between each segment
    var segs = segments-1;
    var seperation = ((target.position - transform.position)/segs);

    for(int s=1;s < segments;s++)
    {
        // Find the each segments position using the slope from above
        Vector3 vector = (seperation*s) + transform.position;
        segmentPos[s] = vector;

        //Add Physics to the segments
        AddJointPhysics(s);
    }

    // Attach the joints to the target object and parent it to this object
    CharacterJoint end = target.gameObject.AddComponent<CharacterJoint>();
    end.connectedBody = joints[joints.Length-1].transform.GetComponent<Rigidbody>();
    end.swingAxis = swingAxis;
    SoftJointLimit limit_setter = end.lowTwistLimit;
    limit_setter.limit = lowTwistLimit;
    end.lowTwistLimit = limit_setter;
    limit_setter = end.highTwistLimit;
    limit_setter.limit = highTwistLimit;
    end.highTwistLimit = limit_setter;
    limit_setter = end.swing1Limit;
    limit_setter.limit = swing1Limit;
    end.swing1Limit = limit_setter;
    target.parent = transform;

    // Rope = true, The rope now exists in the scene!
    rope = true;
}

void AddJointPhysics(int n)
{
    joints[n] = new GameObject("Joint_" + n);
    joints[n].transform.parent = transform;
    Rigidbody rigid = joints[n].AddComponent<Rigidbody>();
    SphereCollider col = joints[n].AddComponent<SphereCollider>();
    CharacterJoint ph = joints[n].AddComponent<CharacterJoint>();
    ph.swingAxis = swingAxis;
    SoftJointLimit limit_setter = ph.lowTwistLimit;
    limit_setter.limit = lowTwistLimit;
    ph.lowTwistLimit = limit_setter;
    limit_setter = ph.highTwistLimit;
    limit_setter.limit = highTwistLimit;
    ph.highTwistLimit = limit_setter;
    limit_setter = ph.swing1Limit;
    limit_setter.limit = swing1Limit;
    ph.swing1Limit = limit_setter;
    //ph.breakForce = ropeBreakForce; <--------------- TODO

    joints[n].transform.position = segmentPos[n];

    rigid.drag = ropeDrag;
    rigid.mass = ropeMass;
    col.radius = ropeColRadius;

    if(n==1){
        ph.connectedBody = transform.GetComponent<Rigidbody>();
    } else
    {
        ph.connectedBody = joints[n-1].GetComponent<Rigidbody>();
    }

}

void DestroyRope()
{
    // Stop Rendering Rope then Destroy all of its components
    rope = false;
    for(int dj=0;dj<joints.Length-1;dj++)
    {
        Destroy(joints[dj]);
    }

    segmentPos = new Vector3[0];
    joints = new GameObject[0];
    segments = 0;
}
}

```

# Answer
It looks like you instantiate each joint in `AddJointPhysics`, here:

```
joints[n] = new GameObject("Joint_" + n);

```

At this point, `joints[n]` contains the new joint game object, and you should just be able to do `joints[n].tag = ...` to assign whatever you want (in place of `...`) to the object's tag property.
> 2 votes

---
Tags: unity, c#, rope-physics, joints
---


# Question
Title: Solvable mazes that have contained cells
Is it possible to create a random maze that is solvable and uses a group of cells or single cells that do not depend on the cells around them?

I am using a visual language that uses self contained objects so it’s difficult to tell the other cells/objects what is next to them. I tried using a group of four cells that can only have walls on the right or bottom of the group but it can create areas that are not accessible. The example below has + for the outside border X for walls and 0 for the paths:

Valid groups:

```
0 X
0 X

```

and

```
0 0
X X

```

A small maze that has paths that are inaccessible

```
+ + + + + +
+ 0 X 0 0 +
+ 0 X X X +
+ 0 0 0 X +
+ X X 0 X +
+ + + + + +

```

# Answer
# You're going to have trouble

And you're going to have to suck it up and deal with it. There is no possibility of ensuring that no areas are inaccessible without knowing what's around each cell. If a cell *can* block access in a given direction, then *inaccessible areas must exist* unless cells can talk to each other.

Heck, at the moment you aren't even guaranteed a *solvable* maze:

```
+ S + + + +
+ 0 X 0 0 +
+ 0 X X X +
+ X X 0 X +
+ 0 0 0 X +
+ + + E + +

```

The best I was able to do under similar circumstances (the Source engine) was for each cell to have two states:

* Block South
* Block East

Then starting from the North-West corner randomly pick between those two states. It would create inaccessible areas in the NE and SW corners, but that was an acceptable loss because the start was always NW corner1 and the exit was always in the SE corner.

This method will always generate a generally South-Eastern solve path, but it is guaranteed to *have* a path. There will be the occasional inaccessible area, but they're specifically only in the corners.

For example (with S and E tiles completely open):

```
+ S + + + + + + + +
+ 0 0 0 0 0 X 0 0 +
+ 0 0 X X 0 X X X +
+ 0 X 0 X 0 0 0 X +
+ 0 X 0 X X X 0 X +
+ 0 0 0 X 0 0 0 X +
+ X X 0 X X X 0 X +
+ 0 X 0 0 0 X 0 0 +
+ 0 X X X 0 X 0 0 +
+ + + + + + + + E +

```

This can still generate unsolvable mazes if you require a *specific* end square, otherwise you are guaranteed to terminate *somewhere* along the South or Eastern edge. You said you had the ability (albeit difficult) to perform checks against neighboring cells. This would be where you do it: insuring that not *every* cell along the N and W walls are all identically aligned (very boring maze) and insuring that the SE corner is connected. The interior though is free to be perfectly random.

Try flipping any 2x2 cell in my example that isn't along an edge: it will always result in a new path.

1Actually it wasn't, it was in the north-center, but I flipped the E-W direction of the NW corner cells so that it was always connected to the start position. Similarly the goal was "anywhere on the South edge"
> 1 votes

---
Tags: algorithm, random, puzzle, maze
---


# Question
Title: Multiplayer networking and understanding snapshots between client and server
**Please note:** Although this question involves a link to the Source Engine, its really a generic question about client-server interactions in multi-player games, and I think can be answered by anyone with such experience.

---

So I just *started* reading this article on multiplayer networking and only got through the first paragraph before I already had a slew of questions. Most of these questions can all be addressed if I simply could get help understanding the diagram at the top of the page:

Here is my *understanding* of the first paragraph, regarding snapshots:

A **snapshot** is something sampled on the server and broadcasted out to all connected clients. Ideally, in a perfect world with zero latency, clients could send updates to the server, and the server could broadcast each and every update back out to all the other clients. *However* this is not a perfect world, latency *does* exist and is both chaotic and unpredictable; and so by servers sending these snapshot "heartbeats" out at regular frequencies, all clients can receive updates at the same rate, consistently. **Yes? No? Kinda/sorta?**

Assuming I'm more or less correct about the underlying *purpose* of snapshots, then I'm trying to understand what is happening in that diagram above:

* The client is currently at `Tick=115`, but the server is at `Tick=130`, but why?! Why is the client behind?
* Why does the client "buffer snapshots for 100ms"? What's going on there? Is that just the time it takes (roughly) to process a snapshot from the server?
* Why is the server simulating the world (and what does that even mean?!) at 33Hz but only sending out snapshots at 20 Hz?

I know these are a lot of tiny/small questions but think they can be addressed with a single answer explaining what is happening in the diagram. Thanks in advance!

# Answer
> The client is currently at Tick=115, but the server is at Tick=130, but why?! Why is the client behind?

Because the client has to wait until it has information from the server in order to process it. So in this case you can assume that the client has a ping of 15ms because that is the difference between the two. The client can't process past tick 115 because that's the last snapshot it got from the server.

IE: the client will always be behind the server according to the amount of latency.

> Why does the client "buffer snapshots for 100ms"? What's going on there? Is that just the time it takes (roughly) to process a snapshot from the server?

It's not necessarily the time it takes to process a snapshot, it's more like how an audio streaming service like Pandora works. What would happen if your computer could only play audio as it received it and didn't buffer? The moment your connection had any kind of lag the music would cut out. What do you think happens to an online game if you don't buffer? The same thing.

It's to make sure you have a smooth and responsive gameplay experience and it's invisible to the user because EVERYONE has it and it's planned for. The reason network latency (ping) is bad is because not everyone has it and you can't completely account for it due to how much it varies.

> Why is the server simulating the world (and what does that even mean?!) at 33Hz but only sending out snapshots at 20 Hz?

The server is simulating the world because all "decision-making" has to happen server side for integrity reasons. If you let the client have any influence on the outcome of events then it makes it trivial for players to cheat.

It's sending them out at a lower rate because sending every single "tick" is both too much data and would result in the same problem as with no buffer. The client doesn't need 33hz, it processes at that rate because it wants to process them as fast as the server generates them.

Think of it like the refresh rate of a monitor, you have a 144hz monitor but your game is only running at 90fps. Your GPU is sending less but your monitor is still refreshing 144 times per second, because you want each frame to display as quickly as possible. You don't need 144 frames to be smooth, same idea.
> 1 votes

---
Tags: networking, multiplayer, timestep, latency, source-engine
---


# Question
Title: ScreenToWorldPoint problems in otherwise awesome Unity demo
I am using this neat Unity demo I found on Stack Overflow, which demonstrates texture masking via RenderTexture:

Can you erase a texture in real time in Unity

But the mapping from mouse position to world space is wrong. This is the script that does the mapping:

```
using UnityEngine;
using System.Collections;

public class MaskCamera : MonoBehaviour
{
    public Material EraserMaterial;
    private bool firstFrame;
    private Vector2? newHolePosition;

    private void CutHole(Vector2 imageSize, Vector2 imageLocalPosition)
    {
        Rect textureRect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
        Rect positionRect = new Rect(
            (imageLocalPosition.x - 0.5f * EraserMaterial.mainTexture.width) / imageSize.x,
            (imageLocalPosition.y - 0.5f * EraserMaterial.mainTexture.height) / imageSize.y,
            EraserMaterial.mainTexture.width / imageSize.x,
            EraserMaterial.mainTexture.height / imageSize.y
        );
        GL.PushMatrix();
        GL.LoadOrtho();
        for (int i = 0; i < EraserMaterial.passCount; i++)
        {
            EraserMaterial.SetPass(i);
            GL.Begin(GL.QUADS);
            GL.Color(Color.white);
            GL.TexCoord2(textureRect.xMin, textureRect.yMax);
            GL.Vertex3(positionRect.xMin, positionRect.yMax, 0.0f);
            GL.TexCoord2(textureRect.xMax, textureRect.yMax);
            GL.Vertex3(positionRect.xMax, positionRect.yMax, 0.0f);
            GL.TexCoord2(textureRect.xMax, textureRect.yMin);
            GL.Vertex3(positionRect.xMax, positionRect.yMin, 0.0f);
            GL.TexCoord2(textureRect.xMin, textureRect.yMin);
            GL.Vertex3(positionRect.xMin, positionRect.yMin, 0.0f);
            GL.End();
        }
        GL.PopMatrix();
    }

    public void Start()
    {
        firstFrame = true;
    }

    public void Update()
    {
        newHolePosition = null;
        if (Input.GetMouseButton(0))
        {
            Vector2 v = camera.ScreenToWorldPoint(Input.mousePosition);
            Rect worldRect = new Rect(-8.0f, -6.0f, 16.0f, 12.0f);
            if (worldRect.Contains(v))
                newHolePosition = new Vector2(1600 * (v.x - worldRect.xMin) / worldRect.width, 1200 * (v.y - worldRect.yMin) / worldRect.height);
        }
    }

    public void OnPostRender()
    {
        if (firstFrame)
        {
            firstFrame = false;
            GL.Clear(false, true, new Color(0.0f, 0.0f, 0.0f, 0.0f));
        }
        if (newHolePosition != null)
            CutHole(new Vector2(1600.0f, 1200.0f), newHolePosition.Value);
    }
}

```

I fixed line 49 and 50 like so:

```
Vector2 v = GetComponent<Camera>().ScreenToWorldPoint(Input.mousePosition);
Rect worldRect = new Rect(0.0f, 0.0f, 16.0f, 12.0f);

```

So the script compiles and the worldRect is in the right place now. Through debugging I found that the world coordinates returned on line 49 are off. I also tried setting the z value of mousePosition to 10, even though the cameras are orthographic, like so:

```
Vector3 mousePos = Input.mousePosition;
mousePos.z = 10;
Vector2 v = GetComponent<Camera>().ScreenToWorldPoint(mousePos);

```

The mapping from the mouse to worldspace is still wrong though. Mouse coordinates within a small rectangle near the center are mapping to the full width and height of the image in world space.

# Answer
> 1 votes
Ack! Okay, so the camera in the original script is referring to the Main Camera, not the camera with the script attached. Line 49 should read as follows:

```
Vector2 v = Camera.main.ScreenToWorldPoint(Input.mousePosition);

```

No other changes were necessary.

---
Tags: unity, shaders, masking, rendertexture
---


title: Image effect console error

text:
# Question
Title: Image effect console error
I have imported image effects from asset store in my project. When imported, I've got 5 error messages :

```
Assets/Standard Assets/Effects/TonemappingColorGrading/Editor/TonemappingColorGradingEditor.cs(370,134): warning CS0618: `UnityEditor.TextureImporterFormat.AutomaticTruecolor' is obsolete: `Use textureCompression property instead'

```

What to do ?

# Answer
Go to the TonemappingColorGradingEditor.cs script. And on line number 370, Replace TextureImporterFormat.AutomaticTruecolor with TextureImporterCompression.Uncompressed.
> 1 votes

---
Tags: unity, image-effects
---


title: What am I supposed to pass shaders to?

text:
# Question
Title: What am I supposed to pass shaders to?
I don't think I fully understand how rendering shaders work. I get that you give a shader to an object/sprite when drawing it, and it applies the shader to it. But I don't think I'm doing it right.

For example, I wrote a shader for when the player is underwater. It makes the player sway side to side, but the problem is I'm not sure how to tell when I can use it. Do I loop through all the water blocks, and If the player intersects, run the shader on the player? This brings up the problem where all of the player would wave instead of just the part of him below the water.

I'm not sure what else I could do, and I apologize if this sounds confusing, I'm very confused myself and am not sure how to explain it. Do I run the shader on the water and somehow get it to run on all the pixels intersecting the water? What do I do? Also, just to make sure, **I am using 2D.**

# Answer
> 1 votes
You generally don't use a special shader for the player to create an underwater effect, nor do you do any sort of crazy collision detection between the player and the water.

Underwater effects generally activate when the *camera* is under the water. And underwater effects are often accomplished by way of full-screen post-process passes rather than swapping everything to a special underwater shader.

In other words you render your player and everything else normally all the time. If the camera happens to be underwater, you render a fullscreen quad when a special shader that samples the regular frame and applies the underwater "wave" effect, along with whatever other fancy effects you may want to add (maybe a color shift, for example).

The other side of the coin is when the camera is above the water, but looking down into it. In this case, the responsibility of doing any refractive waving and whatever would normally be the job of the water geometry's shader; it will generally *also* sample the regular frame and apply a similar kind of distortion (as well as a reflection and refraction effect).

In both case, the player doesn't get a special underwater shader. A post-process effect is used when the camera's below the water plane, and a special effect is used for the water plane itself for when the camera sees it from above.

---

Since you've edited the question to specify that you're using 2D, I'll note that that doesn't change a whole lot. You no longer have to worry about a water shader for when you're above the water, looking down into it. That makes things easier.

You also don't have a camera that can ever really be under the water. Instead, you know which regions of your world are underwater via some other mechanism (maybe the world is tile based, maybe you can identify the water with a rectangle or spline region, et cetera). You can use that mechanism to build a mask for the fullscreen underwater effect, using a texture containing alpha values as I describe in my answer to this other question. That mask can be used as a blend factor to ensure the wavy postprocess effect is only applied to the regions of the scene that are under water.

---
Tags: opengl, graphics, glsl, shading
---


# Question
Title: How can I create borders in an open-world game that don't feel artificial?
When creating open-world maps, a big issue to take into consideration is how "borders" of sorts are implemented. Obviously, in an open-world game, there shouldn't be invisible-wall borders, as it ruins immersion, and makes the game feel more "artificial".

I've done a little bit of research online and I've found the following methods:

* Have the map be an island, surrounded by water that will kill you if you venture out too far.
* Have the map be surrounded by mountains that are much too steep to climb over.
* A combination of the above; mountains plus a body of water. The Elder Scrolls V: Skyrim does something like this but does have places where paths lead out of the world. *(Thanks @Pharap)*

These seem like the best methods but I'm wondering if there are any other methods that can be used to create borders in an open world without ruining immersion.

# Answer
Just some quick additional suggestions, that sometimes complement what others have already said.

1) **water solution**: I never understood why killing the player with a shark or something. Just let him/her swim infinitely (like with a proceduraly generated infinite ocean). That alone would closer resemble the idea of how distant it would be in real life to cross an ocean by swimming. The player would just get tired at some point of going forward and then would decide to reload (because going back all over again would be just as tedious).

Of course, if you have modern boats, ships, jet-skis, etc, and the concept of gas as resource, that works well too and then it becomes part of the item number 4 below, since the player can just sail until running out of gas. Then, if he/she can swim, it becomes again a problem of just letting him/her swim forever.

2) **scene barrier**: it does not have to be mountains. A dense forest, as someone else told here. A canyon with a beautiful view. A part of a city with too many buildings in the way and the only possible streets blocked. A huge fire destroying parts of a city, or a gas leak, or a radiation accident in part of a city that blocks the way. If the city was invaded by aliens, maybe the gigantic spaceship is itself blocking the path to other parts of the city as it crushed when arriving. Or, why not, you can have flying islands like in Zelda Skyward Sword, where the boundary is given by not-falling-to-death.

3) **challenging who tries**: you can always increase the challenge exponentially as far as the player goes. Imagine an open-world in the country fields. The player crosses farms in the direction of the inner-lands of your world. More and more enemies show up with no power-up, health kits or something in the way. If you make these field camps procedural and increase the challenge, the player will eventually get killed without having the feeling that he/she was cheated by an artificial border. I like this approach because it even creates in the mind of the players the impression that there might be something hidden ahead (of course, you have to take care and don't abuse on this illusion, to avoid the players becoming mad at you!).

4) **lack of resources**: if a player has to eat/take medicine/whatever, and/or if vehicles have gas, you don't need boundaries. Let the player and/or its vehicles die. That is particularly useful in a space game, where creating a non-artificial barrier is quite difficult. In other words, if that suits your gameplay framework, make the open world finite by not being accessible due to being impossible to accumulate resources to go beyond a give distance.

---

I won't keep going with a ton of suggestions based on storyline and gameplay. My reasons: first I don't know which type of game we are talking about. Second: frankly, as nice as it can be to have a story-line or gameplay related solution such as failing missions because some hostage has died when you tried to get out of the borders, I don't think that is exactly what you meant and, on the contrary, I found those to be usually harmful for immersion. But if you happen to be interested in these types too, let me know and I can drop some ideas that I have either seen or thought.

Also, as a general point, notice that more than once I touched procedural generation. Really, I think procedural generation is your friend here. You don't need to use it only for having infinite worlds. I always say we should start using it much more often to make the finite open-games more realistic and diverse. Using it for a fake endless border would be a neat use.
> 136 votes

# Answer
Different games have different requirements in how realistic they are to their genre, e.g. FPS games can constrain to a building, whereas RPG games like **Rust** / **DayZ** / **Skyrim** have larger and more open world maps to suit their style.

Some common ones across games (and examples) include:

* Constrain to an Island and:
    + Ruin the only bridge out (**GTA 3, Vice City, Unturned, etc**)
    + The ferry only comes sometimes
    + You're trapped (**Dead Island, Just Cause, Crysis**)
* Forest/Open World games with large continents (parent maps):
    + Blocked by trees except for a few areas (**Pokemon**, **Legend of Zelda**)
    + Blocked mountains (**Skyrim**, as you pointed out)
* Out-of-bounds areas (A higher governing force controls where you can and can't go, meaning you are killed when exiting):
    + Turrets shoot you down (**Borderlands**, **Batman: Arkham City**)
    + You fail the mission (**CoD**, probably **Battlefield** too)
* Objectives unlock continuation (Literal, not the metaphoric idea embodied by gaming):
    + More enemies spawn until you do and you die eventually (**CoD: Zombies**, **Left 4 Dead**)
* You get moved by a higher power:
    + Picked up / teleported back (Imagine AM from Harlan Ellison's **I have no mouth and I must scream** (the story, not the game adaption))
* Don't have borders, increase map size until your program cannot handle it
    + Walking and discovering increasing size of world (**Minecraft** and the concept of program failure at a certain distance from the centre of the map).
* In a city:
    + Barricades / cars block you from moving (**Left 4 Dead**)
    + Buildings blocking your path (Pretty much every urban level of **FPS** games)
* On a cliff / high place:
    + If you traverse past the edge, you fall off and die (A few **Borderlands** levels)
* Your character physically cannot handle the outside environment:
    + Other planets & the moon with an artificial environment (**WORLD END ECONOMiCA**)
> 69 votes

# Answer
I am a bit hesitant to add this option, but it could work.

## Torus.

When seen in 2D (neglect height for a moment) the inside AND the outside of a torus are endless. They simply wrap around on both axes.

Placing your characters on a shape like that could be tricky. You could always go easy on yourself and get a less exact torus.

(source)

Now we're talking 3D objects, how about a plain old sphere? They don't necessarily have to be as big as Earth. Make them the size of a small moon, like Dactyl, the moon of 243 Ida. I can imagine writing a story for such a setting can be quite the challenge (same goes for the torus).

Mario Galaxy makes use of this by making very small planetoids. If it works for Nintendo there's probably some merit to the concept.
> 56 votes

# Answer
Basically, you just need to put something at the edge of the world that the player can't move past for some reason. Anything will work, as long as it stops the player from going any further in a particular direction while using the actions allowed by your game.

You seem to be looking for a comprehensive list, so here you go; I think this covers all the viable possibilities:

* A mountain.
* A pond (if the player can't swim)
* A river or canal or sea (if the player can swim, but is a vampire)
* An extremely long train.
* A fence (if the player cannot destroy or clamber over fences)
* An infinitely-long cylinder (as all players intuitively know that games don't ever let you clamber over cylindrical objects)
* An angry poodle which moves around the world boundary to block the player's path.
* Lasers.
* An insoluble maze.
* A water-resistant cornfield (if the player is afraid of insoluble maize).
* Inexplicable but conveniently placed mines.
* An unexpectedly large dachshund.
* Quicksand.
* A densely packed Thanksgiving-day parade which the player cannot move past.
* A bridge which is closed off due to zombie outbreak.
* zombies (who presumably got across the bridge before it was closed).
* Giant zombies.
* Mutant zombies.
* Fast zombies.
* Extremely slow zombies.
* Thanksgiving-day zombie parade which the player cannot move past.
* A line of women all named Helen.
* A line of men all named Steve.
* A force field (N.B.: Not an invisible wall)
* An invisible wall (N.B.: Not a force field)
* Choking jungle.
* Giant space piranhas.
* A "do not cross - police line" tape facing inward (if the player is a law-abiding citizen).
* A "do not cross - police line" tape facing outward (if the player is not a law-abiding citizen).
* A large building.
* A small building (if the player cannot climb over small buildings).
* A kitten (if the player cannot climb over kittens).
* A sachet of Cup-o-Soup powdered soup, Chicken Noodle flavour. (If the player cannot climb over sachets of Cup-o-Soup powdered soup, Chicken Noodle flavour.)
* Poison fog.
* Noby Noby Girl (see above comment re: infinitely-long cylinders)
* Poison frogs.
* The trailer for the upcoming Star Wars film. (Or at least this seems to work on the majority of my friends, even though they must have already watched it a dozen times. Your mileage may vary. May need to issue patches to the game as new Star Wars films are released. Possible Copyright issues, too.)
* God.
* Infinite hinterland.
* A mountain of bones.
* Giant magnets.
* Outside the playable area there is only Pong.
* Chain-link fence.
* Make game online-only, and pretend there was a connection error if the player gets too close to the edge of the world. Teleport them back to the start, and tell them they need to reboot their router.
* A link to TVTropes.
* Impenetrable fire.
* Crushing despair.
* Meticulously planted gardens, upon which the player does not wish to tread.
* An infinite list.
* Have EULA restrict player from traveling too far.
* A manned border crossing, and the player doesn't have the necessary paperwork.
* A fake loading screen.
* Grey squares (if your game is Chess).
* Have protagonist's mother call on their mobile if the player starts wandering off.
* Have player's actual mother call on their mobile if the player starts wandering off. (Requires a lot more micromanagement, but very effective)
* Spawn easy-to-defeat but wealthy enemies for the player to kill and loot, breadcrumbing the player back into the main game area.
* The bridge of death.
* Any incline steeper than 30 degrees either up or down, with a visible crack in the mesh between it and the playable area.
* Electroconvulsive therapy.
* Extreme homeopathy (see pond, river, canal, and sea, above)
* Nesting birds. (Seriously. You do *not* want to mess with these.)
* @JoshPetrie. Just saying; nothing seems to get past him! :)
* A pit so wide that the player cannot jump over it (this is basically the 'canal' solution, above, but without needing the potentially expensive water shader)
* Cliffs.
* Progressive SAN loss.
* The infinite blackness of space.
* The inarticulate raving of a lunatic.
* The ineffable beauty of a daffodil.
* The interminable loneliness of the soul.
* A wall.

...hope that helps!
> 47 votes

# Answer
## Flat Earth

The Earth is flat, so why not border the world realistically; A cliff that falls into space.
> 31 votes

# Answer
## Caves.

No start, no end, no invisible walls. There will be no obvious 'walls designed to keep the player from leaving the playing area', since you're in a cave. All walls are the same.
> 28 votes

# Answer
A very interesting example is in the first scene of Fallout 4 :

You are in your normal house during a normal day and suddenly there are news reports and alerts of nuclear bombs (the beginning of the nuclear war of 2077). You are then tasked to go to the nearby vault as soon as possible. But you can take a long time to do so if you wish. The relevant part is that when you try to leave the map, the bomb actually explodes nearby (it normally explodes only when you reached the vault), killing everyone, setting a hidden limit to the map. You can see this in action here.

This is the same kind of border as the turrets in Borderlands (as noted in Quill's answer), but kind of hidden as it then feels like it is time-related while it is not.

In the same vein I've seen in Hitman Absolution's *Streets of Hope* level a border implemented in a similar fashion with a train. In a town, as long as the player stays far from the railroad there is no train, but as soon as the player approaches, the train comes, preventing the player from crossing. The train is actually an infinite train and doesn't end as long as the player stays close. As soon as the player goes far enough, the train ends.
> 21 votes

# Answer
**Include leaving the game area in your story.**

Perhaps those pesky guards wont let you leave the city. Perhaps the front door or gate is blocked/locked. It might not all be impossible, but still hard to leave the game area.

What happens when the player does leave? You win the game! (but perhaps there is another better ending?)

The point is the player need to have a incentive to stay in the game area. This does not have to be by force, as long as it's clear that leaving will have a bad outcome to the story. The player might not be able to rescue his friend, might never be able to unravel the secret story, might not be able to find the holy grail.

In an open world the player might go further out of bound than in a completely railroaded game. However, when the player does not return in time, objectives might run out of time, enemies might replenish or puzzles reset.

Now, when the player does reach the edge of the map, based on the story we can do different things.

* The game can end in a win or lose condition.
* The hero can refuse to abandon his quest.
* The hero can get tired of travelling in the wrong direction, and return to known ground.
* The hero can get in trouble (tired at sea, dehydrated in the dessert), be rescued, and wake up in the play area.
> 14 votes

# Answer
A neat trick I've seen in a game from the past (Ultima 7): make the entire world map seamless, namely once the player has reached an edge, (s)he gets teleported to the opposite side.

This technique could work pretty well also if your map is surrounded by water, without the need of blocking the player o killing him/her.
> 11 votes

# Answer
Your question is very general to being with, so a specific answer (like mountains, water, or caves) can't really be given as we don't know what specific setting you are talking about.

A general answer would be to incorporate things from the environment into the border. Some examples would be:

* A city. Construction can block exits.
* The wilderness. As you said, water, mountains, etc.
* Space. An asteroid belt.

The key is to think of normal situations you would find in the environment that is in the game, and to strategically place these situations around your borders so everything looks natural to the user.
> 9 votes

# Answer
# Make the whole game's art style feel artificial

This was the solution adopted by Valve for Team Fortress 2. From the Hydro developer commentary (2:29):

> Maps require impassable boundaries, but unless we restrict the environments to either interior spaces or steep canyons, these boundaries can't always block the player's view of the outlying, unreachable area. In our more realistic titles, like HL2, these boundaries often require fictional and visual explanations. In the heavily stylized Team Fortress world, however, conspicuous artificiality is a core design principle and so we can simplify or altogether ignore these explanations without compromising the player experience. Playtesting showed, for instance, that these low fences leading to an empty expanse successfully conveyed the message that the area beyond the fence is uninteresting and out-of-bounds.
> 2 votes

---
Tags: level-design, levels, open-world
---


# Question
Title: Give a message box where yes no question should be answered
Message boxes, had some time put in creating some for my program, now it all were informative message boxes where an OK button was available and then it closed.

I worked with a canvas that would be enabled when needed and gets disabled on clicking OK.

But now I'm in need of a messagebox that gives an output. I've tried to do the same and test some stuff with public variables, but my code kept going and didn't wait for the response of the "dialogue box" which results in the changes going through and an unused canvas that opened behind my active screen. (Another canvas is loaded when running the code while the current canvas gets disabled).

Code example:

```
 cnvCleanup.enabled = true;
 //Here it should wait till i have "answered" on cnvCleanup
 if (CleanUpDone == true)
 {
 usages = 0;
 }
 else
 {
 usages++;

```

The cnvCleanup will get disabled on the script I wrote for clicking on the OK button. In case the Not OK button is clicked the bool CleanUpDone should remain false so there the cnv gets disabled.

EDIT: More code. The CleanUpDoneis `public bool CleanUpDone;` that gets changed in the cnvCleanup.

```
int usages;
usages = System.Int32.Parse(AssetList[2]);
if (usages < 10)
 {
 usages++;
 AssetList[2] = usages.ToString();
 }
 else
 {
 cnvCleanup.enabled = true;
 //Here it should wait till i have "answered" on the cnvCleanup
  if (CleanUpDone == true)
  {
  usages = 0;
  AssetList[2] = usages.ToString();
  }
  else
  {
  usages++;
  }
}

```

# Answer
> 0 votes
I have changed the code like this: in the update he checks if he is on one of the needed buttons. so the mousepointer is on the object and the canvas is active. when one of the buttons is clicked, he does the code, if none of the buttons are clicked, nothing happens.

```
RectTransform rt = btnCleanupOK.GetComponent<RectTransform>();
    if (Input.mousePosition.x > btnCleanupOK.transform.position.x - rt.rect.width /2 && Input.mousePosition.x < btnCleanupOK.transform.position.x + rt.rect.width / 2 && Input.mousePosition.y > btnCleanupOK.transform.position.y - rt.rect.height / 2 && Input.mousePosition.y < btnCleanupOK.transform.position.y + rt.rect.height / 2 && cnvCleanup.enabled == true)
    {
        isOverOK = true;
    }
    else
    {
        isOverOK = false;
    }

```

How to check the button is clicked:

```
 if (Input.GetMouseButtonDown(0) && isOverOK)
    {
        clickedOKButton();
    }

```

In the `clickedOkButton();` is the rest of the code that needed to be run when clicking on OK.

I've done the same for clicking on the later button. I know this isn't optimal, but it works.

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


# Question
Title: Unity Ads. Is the Ad.show placementId parameter used anymore?
I started a project a long time ago with the Unity ad api v1, now that they have moved onto Advert api v2 i'm wondering if they still use the placementId parameter.

I'm only wondering this because they used to support video and image based Ads. As far as I know they only do video now. They used to have examples similar to this:

```
Advertisement.Show("rewardedVideo", options);

```

Which specified which of the supported advert types you want, `rewardedVideo` for video and `rewardedImage` (or something similar) for images.

With the loss of images and the integration guide (behind the login screen) having been changed **does the palcementId parameter still matter since I noticed that you can pass in only the callback stuff?**

# Answer
Yes it does matter. if you pass placementId "video" then ad is skippable if you pass "rewardedVideo" then ad is not skippable. Tested this in unity ads 2.0.8
> 0 votes

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


title: How to optimize classes

text:
# Question
Title: How to optimize classes
I am currently working on a game based on SFML and written in C++. For the HUD of the game I have a HUD class with a lot of different variables and methods. Basically most of the variables have a set and get method. We are talking about 14 variables currently and I am sure this will increase.

Example excerpts:

```
sf::Text m_AmmoText;
sf::Text m_ScoreText;

sf::Text getAmmoText();
sf::Text getScoreText();

void setAmmoText(sf::String text);
void setScore(sf::String text);

```

### Questions

Optimize context is performance vs. code mantainability

### 1. Prototyp or Inheritance?

I searched the web and found the prototype pattern or the inheritance of classes as the most useful ones to apply. Since I never use both I am quite unsure which solution will have a positive impact on the code and performance. I am aware that with these few classes the performance impact is hardly measurable. It is more for practice and to get it right from the beginning. I started to re-write the code to apply inheritance but thought it might be better to ask the experts first.

Here is an example of the classes. Implementation of methods accordingly to read or write the variable (skipped here).

```
class HUD{
    protected:
        sf::Text m_Text;
    public:
        getText();
        setText();
}

class HudAmmo : public Hud {};
class HudScore : public Hud {};

```

So instead of hud.getAmmoText() I could use hudammo.getText(). I did not code the prototyping yet. But read a lot about its pros and cons on the internet. Suprisingly I could not find a clear direction since most examples I found were abstract. I tend to apply the prototyping pattern from what I understood so far mainly because of this post:

### 2. Alternative

Re-write the class and have only 1 set and get method which passes the context, e.g. hiscore or other solutions?

# Answer
Don't overthink your problems. Keep your designs straightforward and simple until you have proven (by profiling) that you need to complicated them. Then focus on new designs that address the specific problems you found while profiling.

I see nothing in your problem description that suggests you should change your current HUD design *at all*.

---

> I searched the web and found the prototype pattern or the inheritance of classes as the most useful ones to apply

"Prototype" versus "inheritance" are *design* choices first and foremost, not performance optimization choices. In general neither will be more or less efficient at runtime than the other. In practice, the specific technique used to implement prototype or inheritance-based object construction may have some minor impact on runtime performance, but generally it will be irrelevant. This brings me to your next concern:

> It is more for practice and to get it right from the beginning.

To "get it right from the beginning," you need to correctly understand when it matters to be overly performance-conscious and when it doesn't. *That* is what is important.

In this case it *almost certainly* doesn't matter, and no amount of "practicing" techniques you think may be more optimal will actual improve your ability to do so, because you are probably lacking the real-world concerns that actually make something a performance issueand because you *definitely* lack the knowledge of where those specific concerns occur in this particular case.

When you want to optimize something, the first thing you generally want to do is profile it to make sure you actually understand what is slow. Often this will be enough to let you know that what you *think* is slow *isn't* and that your actual performance problem is elsewhere. Then you can go find and focus on that, instead of worrying about micro-optimizations that are dwarfed by a larger issue.

> 2. Alternative

What you should do here is probably nothing. Your HUD class, with it's 14 variables, is not a performance concern and it's probably not a particularly serious design concern either. It makes sense, it works, and directly reading and writing variables via accessor methods (that are almost *certainly* inlined by any modern compiler) will be plenty fast.

Your proposal of creating some kind of HUD base class and then HudAmmo, HudScore, et cetera subclasses that just inherit is worse than what you have now:

* from a design perspective (you still need to store instances of each of these HudProperty classes somewhere; where?)
* from a code maintainability perspective (it's a vastly less straightforward design)

And from a performance perspective it's not any different, really; you are still calling inlined accessors to return text variables.
> 4 votes

# Answer
A few rule of thumbs when performance is a major concern:

Virtual inheritance means chasing a pointer and most likely a branch misspredict.

Chasing a pointer usually means a cache miss.

A cache miss is very expensive (about as expensive as calculating a cosine)

Accessing data that's all tightly packed gets prefetched and is much cheaper.

In otherwords a class containing 14 sf::Texts is cheaper than a class containing 14 pointers to what eventually is a sf::Text.

Note I'm talking about pointers, creating a class that is stored by value and holds several related UI component is fine. For example an ammo display, it holds the icon unique to the weapon, total ammo, currently in the clip and max clip size and a progress bar of the current clip.

---

Besides that your getters and setters should return and take their variables by const reference.

```
sf::Text m_AmmoText;
sf::Text m_ScoreText;

const sf::Text& getAmmoText();
const sf::Text& getScoreText();

void setAmmoText(const sf::String& text);
void setScore(const sf::String& text);

```

Because you want to avoid needing to copy the fields if you don't need to.

Consider defining the simple getters and setter inline inside the class. This will allow the compiler to inline the functions and remove the overhead of the call.
> 0 votes

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


title: My generated texture is flipped

text:
# Question
Title: My generated texture is flipped
I'm learning OpenGL and I don't understand why my texture is flipped if I give as UVs the "matching" vec2 of the mesh's vertex (vec3).

Example:

```
vert -256 -256
uv   0    0

vert 256 256
uv   1    1

```

I've had to try a different order for the UVs to be able to get the correct result...

Can someone explain why is that so? Thanks.

Screenshots:
https://i.stack.imgur.com/R0y1g.jpg

This are the snippets of code I use:

```
// Create texture
GLuint texDebugId;

// RGBA Texture:
// R G
// B A

unsigned char texDebugBuf[] = {
    255, 0, 0, 255,
    0, 255, 0, 255,
    0, 0, 255, 255,
    0, 0, 0, 0,
};
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &texDebugId);
glBindTexture(GL_TEXTURE_2D, texDebugId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, texDebugBuf);
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);

//------------------------------

// Prepare VBOs
static const GLfloat verts[] = {
    -256.0f, -256.0f, 0.0f,
    256.0f, -256.0f, 0.0f,
    -256.0f, 256.0f, 0.0f,
    256.0f, 256.0f, 0.0f
};

/*
// FLIPPED (but why?)
static const GLfloat uvs[] = {
    0.0f, 0.0f,
    1.0f, 0.0f,
    0.0f, 1.0f,
    1.0f, 1.0f,
};
*/

// OK
static const GLfloat uvs[] = {
    0.0f, 1.0f,
    1.0f, 1.0f,
    0.0f, 0.0f,
    1.0f, 0.0f,
};

// Upload vertices
glBindBuffer(GL_ARRAY_BUFFER, vbo_id);
glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

// Upload UVs
glBindBuffer(GL_ARRAY_BUFFER, vbo_tex_id);
glBufferData(GL_ARRAY_BUFFER, sizeof(uvs), uvs, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

//------------------------------

// Render
glBindTexture(GL_TEXTURE_2D, texId);

glEnableVertexAttribArray((GLuint) pd.vertex_a);
glEnableVertexAttribArray((GLuint) pd.uv_a);

// Vertices
glBindBuffer(GL_ARRAY_BUFFER, vbo_id);
glVertexAttribPointer(
    (GLuint) pd.vertex_a,  // attribute id
    3,                     // size
    GL_FLOAT,              // type
    GL_FALSE,              // normalized?
    0,                     // stride
    (void *)0              // array buffer offset
);

// UVs
glBindBuffer(GL_ARRAY_BUFFER, vbo_tex_id);
glVertexAttribPointer(
    (GLuint) pd.uv_a,      // attribute id
    2,                     // size
    GL_FLOAT,              // type
    GL_FALSE,              // normalized?
    0,                     // stride
    (void *)0              // array buffer offset
);

glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

glBindBuffer(GL_ARRAY_BUFFER, 0);
glDisableVertexAttribArray((GLuint) pd.uv_a);
glDisableVertexAttribArray((GLuint) pd.vertex_a);

glBindTexture(GL_TEXTURE_2D, 0);

```

Note:

```
proj matrix:
proj = glm::ortho(-320, 320, -240, 240, -1.0f, 100.0f); // 640x480 with 0,0 at center

camera matrix:
cam_target = glm::vec3();
cam_up = glm::vec3(0.0, 1.0f, 0.0f);
cam_pos = glm::vec3(0.0f, 0.0f, 5.0f);
camera = glm::lookAt(cam_pos, cam_target, cam_up);

MVP matrix:
glm::mat4 mvp = proj * camera;

```

# Answer
> 2 votes
This is because OpenGL actually expect the pixels ordered from the bottom-left.

So, when you give `(0, 0)` then what you meant is not the upper-left but bottom-left instead. In your case, you want it to be blue, but it shows you red instead.

Take a look at this, scroll down to number 12.

> **12. OpenGL's Lower Left Origin**
>
> Given a sheet of paper, people write from the top of the page to the bottom. The origin for writing text is at the upper left-hand margin of the page (at least in European languages). However, if you were to ask any decent math student to plot a few points on an X-Y graph, the origin would certainly be at the lower left-hand corner of the graph. Most 2D rendering APIs mimic writers and use a 2D coordinate system where the origin is in the upper left-hand corner of the screen or window (at least by default). On the other hand, 3D rendering APIs adopt the mathematically minded convention and assume a **lower left-hand origin** for their 3D coordinate systems.
>
> **. . .**
>
> Another common pitfall related to 2D rendering APIs having an upper left-hand coordinate system is that 2D image file formats start the image at the top scan line, not the bottom scan line. OpenGL assumes images start at the **bottom scan line by default**.

---
Tags: opengl, textures
---


# Question
Title: Facebook Scores API Global and Daily Rank on Unity
I need to implement 4 types of leaderboards on my Unity game:

* All Time/Daily
* Global/Friends

I'm using Scores API from Facebook and I achieved All Time Friends Leaderboards. I'm taking a look at the Scores API documentation and I'm not seeing Daily nor Global rank anywhere.

Is it possible? If yes, how?

# Answer
After some research and thinking a little, it is not reasonable facebook connect you with someone who's not on your social circle so it does not make any sense if Facebook made a global rank.

TL;DR Facebook don't have Global Rank
> 0 votes

---
Tags: unity, facebook, leaderboards
---


# Question
Title: How can I move and rotate an object in an “infinity” or “figure 8” trajectory?
I know that the easiest way to move an object with the figure 8 trajectory is:

```
x = cos(t);
y = sin(2*t) / 2;

```

but I just don't know how to rotate it, lets says with a new variable r as rotation, how do I merge it into the above formula ? can anyone please advise me on what is the simplest and cheapest way/formula to move and rotate the figure 8 trajectory ?

ref:How can I move an object in an "infinity" or "figure 8" trajectory?

# Answer
> 4 votes
The object should point in the direction of the derivative, which is `[-sin(t), cos(2t)]`. Its angle is `atan2(cos(2t), -sin(t))`.

Edit: OP is apparently asking how to rotate the "trajectory," not the object itself.

To rotate the figure, choose an angle, `θ`, in radians, that you'd like the trajectory to be rotated. The position along this rotated figure is:

```
x = cos(θ) * cos(t) - sin(θ) * sin(2t)/2
y = sin(θ) * cos(t) + cos(θ) * sin(2t)/2

```

---
Tags: mathematics, graphics, software-engineering, trajectory
---


title: GTA style camera - Unity

text:
# Question
Title: GTA style camera - Unity
I am wanting to make a 3d RPG with unity, and I'm in the planning phase. For the camera I decided to make it GTA style. I want the camera to be rotated around the player *without* effecting the movement of the player. If anyone can give any pointers on this, I would be very grateful.

# Answer
> 1 votes
This snippet of code should help you.

1.) Attach your main camera to your main character and position it wherever you want it relative to said character.

2.) Attach a script to your camera with the following code somewhere in it, where x, y, and z are the angles you want to rotate the camera:

```
Camera.main.transform.eulerAngles = new Vector3(x,y,z);

```

Note: I haven't (and won't be able to until the weekend arrives) tested this personally, this is just from scavenging the docs.

I am not sure what exactly you want you input method to be, but to get input from the keys you call `if(Input.GetKeyDown(char key)) DoSomethingWithInput()`, so something like this (but again, untested; you'll probably have to tinker with values and such to get it to behave how you want.);

```
if(Input.GetKeyDown('d'))
{
    Camera main = Camera.main;
    main.transform.eulerAngles += new Vector3(1 * xWalkingVelocity, 0, 5 * zWalkingVelocity); //Where xWalkingVelocity is either the xVelocity of the character OR 1 if the character is not moving. Same for zWalkingVelocity.
}

```

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


# Question
Title: Cube that turns every for example 5 seconds 90 degrees
I want a cube to rotate 90 degrees every \[Second/Counter should be setable\]

Like in this video at 3.47 the spiky cube that turns 90 degrees https://www.youtube.com/watch?v=bxWpsT4lKXU

I have tried to do it but it will not turn 90 degrees smoothly or even 90 degrees, it just turns kind of 90 degrees but I need help I guess.

Here is my script:

---

public class TurnCubeScript : MonoBehaviour {

```
public Transform turnCube;

public float turnSpeed;
//SETTING THE COUNTER FOR OBJECT TO TURN
public float setCounter;
public float counter;
//SETTING THE COUNTER TO SETCOUNTER AFTER COUNTER1 = 0
public float setCounter1;
public float counter1;

void Start ()
{
    setCounter = counter + setCounter;
    setCounter1 = counter1 + setCounter1;
}

void Update ()
{
    TurnTheCube();
}

void TurnTheCube()
{

    counter -= 1 * Time.deltaTime;
    if (counter < 1)
    {
        //SOME TRIES...
        //turnCube.transform.eulerAngles += new Vector3 (0, 0, 90 * Time.deltaTime * turnSpeed);
        //turnCube.Rotate(0, 0, 90 * Time.deltaTime * turnSpeed);
        //turnCube.rotation = Quaternion.Euler(0, 0, rotation);

        counter1 -= 1 * Time.deltaTime;

        //GIVES THE CUBE SOME TIME TO TURN
        if(counter1 < 1)
        {
            counter = setCounter;
            counter1 = setCounter1;
        }
    }
}

```

}

# Answer
If you are looking for a stationary rotating box, you should try using the built in script "auto rotate and translate" and set it to your box. Then, type in the values of how you want it to rotate it.
> 1 votes

---
Tags: unity, rotation
---


# Question
Title: How can I make an object move in a certain direction depending on its spawning point?
I'm currently developing a 2D game and I couldn't find a way to figure this out. In the game, I have 4 different balls and 4 different spawning points. Every 2 seconds, a random ball spawns at a random spawning point.  What I want to achieve is, as I tried to describe above, lets say a ball spawns on right side, I want it to move towards left, if it spawns upside, I want it to go downwards etc.

Here is my spawner code:

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

public class Game : MonoBehaviour {

    public Transform[] spawnPoints;
    public GameObject[] balls;

    public float timer = 2.0f;

    void Update()
    {
        timer -= Time.deltaTime;
        SpawnBalls ();
    }
    void SpawnBalls()
    {
        int spawnPoints_num = Random.Range (0, 4);
        int balls_num = Random.Range (0, 4);

        if (timer <= 0)
        {
        Instantiate (balls [balls_num], spawnPoints [spawnPoints_num].position, spawnPoints [spawnPoints_num].rotation);
        timer = 2.0f;
        }
    }
}

```

And here is my ball movement code:

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

public class Balls : MonoBehaviour {

    public Game game;
    public float speed = 0.25f;

    void Start ()
    {
        game = FindObjectOfType<Game> ();
    }

    void Update ()
    {
    //Some if statement
    //transform.Translate (Vector3.left * Time.deltaTime * speed);
    //else if
    //transform.Translate (Vector3.up * Time.deltaTime * speed);
    //else if
    //transform.Translate (Vector3.right * Time.deltaTime * speed);
    //else if
    //transform.Translate (Vector3.down * Time.deltaTime * speed);
    }
}

```

I've tried giving spawnpoints tags and creating if statements with gameObject.tag and stuff but couldn't find a way to work it. How can I make it check which spawnpoint the ball spawned at so I can make it move accordingly?

Thanks for help.

# Answer
> 0 votes
Ok, even though I couldn't manage to learn what I wanted, I figured a way out.

```
Instantiate (balls [balls_num], spawnPoints [spawnPoints_num].position,spawnPoints [spawnPoints_num].rotation, spawnPoints [spawnPoints_num]);

```

I added spawnPoints \[spawnPoints\_num\] at the end of instantiate which makes the ball, children of the spawnpoint it got spawned at. After that I just gave spawnpoints tags and did a simple transform.parent.tag check, and go from there. Thanks everyone for their input.

# Answer
> 1 votes
Get a reference to the spawn point. Orient its forward axis(the blue one) in the direction you want your spawned object to move and use this :

```
 transform.Translate(spawnPoint.transform.forward * Time.deltaTime * speed);

```

# Answer
> -1 votes
What you're looking for is the Vector3.MoveTowards method. try the following

```
    public Transform target;
    public float speed;
    void Update()
    {
        float step = speed * Time.deltaTime;
        transform.position = Vector3.MoveTowards(transform.position, target.position, step);
    }

```

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


# Question
Title: Why doesn't my jump script stop my player from jumping mid air?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Jump : MonoBehaviour {

public float jumpSpeed;

private Rigidbody2D _rigidbody;

private bool _isGrounded = false;

// Use this for initialization
void Start () {
    _rigidbody = GetComponent<Rigidbody2D> ();
}

// Update is called once per frame
void Update () {
    //if the jump button was pressed
    if (Input.GetButtonDown ("Jump") && _isGrounded) {
        _rigidbody.velocity = new Vector2 (
            _rigidbody.velocity.x,
            jumpSpeed
        );
    }
}

void OnCollisionEnter2D(Collision2D collision) {
    if (collision.gameObject.tag == "Ground") {
        _isGrounded = true;
    }
}

void OnCollisionLeave2D(Collision2D collision) {
    if (collision.gameObject.tag == "Ground") {
        _isGrounded = false;
    }
}

```

}

Its supposed to check if the player is on the ground, but it still lets my character jump unlimited times in the game.

# Answer
> 0 votes
Because you're not setting your bool `_isGrounded` to false anywhere. As @DMGregory said, there is no such method as `OnCollisionLeave2D` defined in Unity API, thus it won't be executed unless called explicitly, which means, the bool `_isGrounded` will remain true and your player will continue to recieve jump input. You need to change it to OnCollisionExit2D.

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


title: How to cache tile map?

text:
# Question
Title: How to cache tile map?
I am trying to write a strategy game with PHP, and basically I have a 1d based tile map (grass, dirt, sand, castles, etc.) stored in a database. Now where is 40k records, from x1y1 to x200y200 and I might increase it in future. Where is few column in this map table, it's id,x,y,occupied,terrain,city\_type My question is, what should be a working caching strategy for something like this? Should game cache it by request, i.e. when player requests x189y15 with radius 5, it will cache the resulting array of tiles and when display it to anyone who requests map with the same x,y and display radius. But what is not efficient because of radius. I thought of storing the whole map in array, but I run into two problems, firstly, how would game select data from array within needed radius? Second, if it can is there a point then? Wouldn't this array be as slow or slower than db access? What is a (best) perfomant caching strategy for this case? Does this need caching at all?

# Answer
> 1 votes
PHP, without the use of dedicated extensions, is bad for this task.

The main problem is that in PHP the execution of requests is compartmentalized. It serves each request in an isolated thread, and clears all resources after the request has finished. With the exception of session variables, database and permanent storage, there is not a real cache solution in PHP (at least not by default).

Note: the only way to spawn another thread (without extensions) is to make another request.

*This is good for IT admins because it means no leaks and no deadlocks. With the appropriate configuration, it means no huge CPU loads running in the background indefinitely. In addition, the resources needed for the server are directly proportional to the number of requests, so it is possible to find a maximum number of requests that will not deteriorate the performance of the server. Easy IT administration means cheap IT administration, which means cheap servers (and that is without saying that PHP is free).*

If your map does not change, you can have the client cache the information. Otherwise, look into cache extensions of PHP.

There are two types of caches to look into: for code such as OPCache, and for data such as Memcache. If your data does not change then both may work, otherwise you want a data cache.

---

When it comes to handle large maps, video games will often load this kind of information to RAM and keep it there (but you cannot really do that on PHP). The load time can be optimized using files that contain distinct chunks of the data that can be loaded depending on what region the player is (the database can be considered to be doing a similar optimization).

Since no information is kept from request to request in PHP... if you put all the data on arrays on a PHP files, the server will have to load it into RAM every time one of those PHP file is loaded. For a small arrays this works better. If the data is too big, you are better off loading it from the file system (fopen et.al.), database or a dedicated cache extension (which can keep data in RAM between requests).

Note: the file system will have its own cache solution depending on the operating system.

Code cache will compile the PHP files and keep them in bytecode or binary format between requests (resulting in better response time). If you do this, remember that you have to edit the PHP files to update the arrays, and that you have to invalidate the cache when you do that in order to allow the server to recompile the files... if this happens too often, the benefits of the code cache are minimal.

Therefore, if your data changes too often, you want a data cache. You can push and pull data to the data cache using a key, resourcing to database if the data is not available there. Remember that you pull all the data under that key, there will be an ideal chunk size to store per key (it may be a single tile, but definitively not the whole map), testing advised.

---
Tags: tiles, tilemap, maps, php
---


title: Moving entities above a tile entity

text:
# Question
Title: Moving entities above a tile entity
Sorry if my code looks amateur I just started modding, although I have experience in Java.

I have a tile entity checking every frame if there are entities above it. It works, but then stops after 1 tick. Here is the code I am using.

```
import java.util.List;

import net.minecraft.entity.Entity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.AxisAlignedBB;

public class TileEntityConveyor extends TileEntity implements ITickable {

    public static float speed = 1f;

    @Override
    public void update() {
        if (this.worldObj.isRemote)
            return;
        double x = this.pos.getX();
        double y = this.pos.getY();
        double z = this.pos.getZ();

        AxisAlignedBB collsion = new AxisAlignedBB(x, y, z, x + 1, y + 2, z + 1);

        List<Entity> list = this.worldObj.getEntitiesWithinAABB(Entity.class, collsion);

        for (Entity entity : list) {
            entity.motionX += speed;
            //          this.
        }
    }

}

```

# Answer
There is actually FOUR sides in minecraft, but they are usually just shortened to two. There's a ***physical server***, which is the server in the real world, the ***physical client***, which is the client in the real world, the ***logical server***, the server that you know as the server in game, and the ***logical client***, the client you play.

`World#isRemote` simply checks if the method you are running is in the ***logical server*** (`false`) or the ***logical client*** (`true`).
> 0 votes

---
Tags: java, minecraft-modding, modding
---


# Question
Title: Extract eye/camera position from a view Matrix
I'm trying to improve my Camera. This camera owns a target (vec3 \_at), a position (vec3 \_eye) and a view mat4. When I move the mouse, I perform a rotation to the view matrix, according to 2 angles (\_angleY, \_angleZ), so that it gives the feeling the world is turning and not the cam.

Here is what I have, which works :

```
// Called each frame
void Camera::look(bool rotation)
{
    // Computes view Matrix
    _view.lookAt(_eye.X,_eye.Y,_eye.Z,
                 _at.X, _at.Y, _at.Z,
                 0, 0, 1);

    // Apply rotation to the matrix, according to angles
    if(rotation) {
        _view.rotate(_angleY, 0, 1, 0, _at);
        _view.rotate(_angleZ, 0, 0, 1, _at);
    }
}

```

This perfectly works. I'm able to make my world rotating around a selected target (vec3). My problem is that my eye position is not updated each frame since I update my angles which apply a new rotation. Then my eye position is wrong and I need it to be updated each frame for another calculation.

Then, I'm trying to extract the eye position after the rotation, update it, and set angles to 0 (hoping it's the best solution...)

Therefore, I need to extract the eye position of my camera, from my modelview matrix. Here is what I'm trying to do, according to what I read here , in the last comment :

```
void Camera::look(bool rotation)
{
    // Computes view Matrix
    _view.lookAt(_eye.X,_eye.Y,_eye.Z,
                 _at.X, _at.Y, _at.Z,
                 0, 0, 1);
    if(_angleY != 0 || _angleZ !=0)
    {
        if(rotation) {
            _view.rotate(_angleY, 0, 1, 0, _at);
            _view.rotate(_angleZ, 0, 0, 1, _at);
        }

        Vector3D d;
        d.X = _view[3];
        d.Y = _view[7];
        d.Z = _view[11];
        // This creates a vector by multiplying -d by the mat3 part of the view matrix.
        Vector3D retVec = _view.mul3(-d);
        _eye = retVec;
    }
}

```

few things which might be need :

```
void Matrix4::lookAt(float eyeX, float eyeY, float eyeZ, float targetX, float targetY, float targetZ, float upX, float upY, float upZ)
{
    Vector3D axe (upX, upY, upZ);
    Vector3D forward(targetX - eyeX, targetY - eyeY, targetZ - eyeZ);
    Vector3D normal = Vector3D::crossProduct(forward, axe);   // normal = regard x Axe
    Vector3D newAxe = Vector3D::crossProduct(normal, forward); // newAxe = normal x regard

    // Normalize new vectors
    forward.normalize();
    normal.normalize();
    newAxe.normalize();

    // lookAt matrix
    Matrix4 Matrix4;
    Matrix4.values_[0] = (float)normal[0];
    Matrix4.values_[1] = (float)normal[1];
    Matrix4.values_[2] = (float)normal[2];
    Matrix4.values_[4] = (float)newAxe[0];
    Matrix4.values_[5] = (float)newAxe[1];
    Matrix4.values_[6] = (float)newAxe[2];
    Matrix4.values_[8] = (float)-forward[0];
    Matrix4.values_[9] = (float)-forward[1];
    Matrix4.values_[10] = (float)-forward[2];
    Matrix4.values_[15] = 1.0f;

    *this *= Matrix4;

    // translation is part of the lookAt function
    translate(-eyeX, -eyeY, -eyeZ);
}

```

If someone understands what I'm doing wrong, it might help a lot, I spent a while with this problem... Thanks,

# Answer
> 5 votes
The lookAt matrix is like this:

```
RightX      RightY      RightZ      0
UpX         UpY         UpZ         0
LookX       LookY       LookZ       0
PosX        PosY        PosZ        1

```

Or in your code

```
normal[0]   normal[1]   normal[2]     0
newAxe[0]   newAxe[1]   newAxe[2]     0
-forward[0] -forward[1] -forward[2]   0
eyeX        eyeY       eyeZ           1

```

With the indexes in the matrix as follows:

```
0           1           2             3
4           5           6             7
8           9           10            11
12          13          14            15

```

As you can see, you should be reading the indexes `12`, `13` and `14`:

```
d.X = _view[12];
d.Y = _view[13];
d.Z = _view[14];

```

---

This is quote from the OpenGL FAQ on Transformations:

> For programming purposes, OpenGL matrices are 16-value arrays with base vectors laid out contiguously in memory. The translation components occupy the 13th, 14th, and 15th elements of the 16-element matrix, where indices are numbered from 1 to 16 as described in section 2.11.2 of the OpenGL 2.1 Specification.

Of course, we are using 0 based indexes, so the `13th, 14th, and 15th elements` are the indexes `12`, `13` and `14`.

---
Tags: opengl, c++
---