# Question
Title: simple solution for 3d collision detection and response
I'm having great difficulty trying to implement collision detection and response in a 3d game

What are some simple solutions someone can use to implement smooth collision and response similar to games like Quake? I can see there are a lot of different ways to do collision and response but that makes it even more confusing, Im not sure which method is the best solution to sit down with.

So I was wondering what is the goto solution for the average programmer? All I have found online are very complicated incomplete mathematical explanations which I have a hard time understanding. Is this really a topic that requires an entire textbook to understand??

Perhaps theres a library ? Ive tried looking into bulllet but it seems to require heavy knowledge of physics. The best solution I have found is in a software called darkbasic, where it somehow handled sliding collision automatically and all the user had to do was desginate which object were to be handled. Was wondering maybe theres something similar to that

# Answer
> 1 votes
Usually Simple Collision Detection Libraries are commonly built-in to 3d engines or as feature but here's a few that I know that are widely used that don't have the complexities and added Physics system:

**Coldet** http://sourceforge.net/projects/coldet/

**OZCollide** http://www.tsarevitch.org/ozcollide/

There's also Blitz3D, which is similar to DarkBasic (Language wise). It is Free and Open Source now and has a built-in collision system.

# Answer
> 0 votes
I was working in a project that has near-round characters and cube enviroment (walls, trees, etc...) there we managed collisions by embebing every char object in a sphere and getting the magnitude of the 0,0,0 point of the object (exactly the center of it), then you can easily check if magnitude + radius of item A is inn or out of magnitude + radius of item B and fire a collision if it's in it.

I didn't wrote it so i can't give you exact maths but i could help you to find out some new and efficient ways to detect collisions.

Hope it helps

---
Tags: collision-detection, collision-resolution
---


title: Beginning RTS game student project

text:
# Question
Title: Beginning RTS game student project
I have experience with XNA and Unity3D. I have also built my own engine with Tao and C#. I am in last year of college and I want to make a small RTS game demo, nothing fancy I won't bother much with the art part. I will leave objects untextured, just drop some light.

It is a big decision, which one to choose XNA or Unity3D or maybe else? I definitely won't build my own engine since I will waste lot of time that way. I am looking for an engine/framework that will allow me to concentrate on higher level stuff like AI algorithms rather than do my own texture loading and stuff.

I will try to copy stuff from Starcraft2. My models and environment won't be textured though. I won't bother with sounds either, just some simple explosion and shooting sounds. The player will play against AI. I will go for the Starcraft2 mechanics/logic, not the skin. By skin I mean art stuff. At the end I would make small videos of gameplay showing the AI decision making process by printing text, so that a potential employee can see what is actually going on.

# Answer
How to Choose Between Two Things

Seriously though, it sounds like a personal choice to me. Which one do you have more experience in or are more comfortable with? How might you start making an RTS with XNA vs. making it in Unity3D? Unity3D is higher-level, more engine-like; do you want to deal with matrices and stuff, essentially writing things from scratch, or do you want to work within Unity's environment?

Also from a goal-oriented perspective, it sounds like you're doing this for the end goal of showing an employer your game AI. It seems like you would want to do the least amount of work to get to the point of implementing AI, therefore you would want to choose Unity. But if you want to impress your employer with what you've written from scratch, XNA is definitely closer to starting from scratch than Unity3D.
> 2 votes

# Answer
XNA is fine. Unity too. Really just choose one.

As a student I coded a turnbased strategy game in C#/XNA to implement an AI.

So here's some free advice:

You need to get the game in a playable state before even thinking about writing the AI. Yes I know this is obvious ;) So you might wanna consider making a mod for an existing RTS instead of writing an RTS from scratch.

Create a dumb AI as soon as possible. Just to test/tweak your RTS (if you build from scratch). This will give you some insights how to design your AI and which problems the AI needs to solve. It can also be used as opponent against the real AI later.

Your RTS rules must be complex enough to even require an AI e.g. a player should not be able to win by simply mass producing one unit type. One way to do this is by having a counter unit for each other unit type. Starcraft achieves this with different weapon/armor types.

The AI Game Programming Wisdom books by Steve Rabin are a good resource on game AI.
> 2 votes

# Answer
There is a FOSS engine specifically for RTS's http://springrts.com/

It uses Lua and C++.

Though it looks like your using the StarCraft2 engine. Which is a really good idea.
> 1 votes

# Answer
Unity has come a long way. Anyone thinking about creating their own game or game demo should now ask themselves, why should I NOT choose Unity.

When it comes down to Real Time Strategy type of games, Unity already has an asset for this in the asset store. It currently has no AI and no multiplayer but should be a great asset to build upon or learn from.

RTS development framework
> -2 votes

---
Tags: rts
---


# Question
Title: Prevent character's animation from causing its mesh to interpenetrate itself
I'm making a game with a pretty large group of people that respond to things the user does. They all have the same animator attached, but the animations that play differ using a script with a randomizer.

Now all Mixamo stuff is free I'm making some new and different models to put in my game, these models differ in size and shape, just like humans do. My previous setup was pretty much two models with the textures changed, so the animations were acting the same on all models.

This is now no longer the case with the new models. Hands of the models are moving through their leg mesh (see attached image). I fear I'd have to make separate animations for each model but I'd first like to know if there's maybe another way. I tried adding colliders to the leg and hand of each model, but the animation totally ignores those.

Does anyone know of a way to make sure body parts of my models don't go trough eachother? Or do I have to face the facts and make seperate animations for each model?

# Answer
Small clipping errors are almost impossible to avoid when developing games, as self collision with large amounts of animated characters are very costly to calculate.

If you need (almost) perfect animations for cutscenes, animate each character on its own. But when you are animating for realtime, you should not worry about minor errors, as these are barely visible most of the time, especially when you have a lot of characters on screen at once.

Even the best, most professional games contain this kind of clipping errors, for example weapons moving through the character's backpack when ducking. The best thing you can do is probably trying to make all characters similar in size.
> 4 votes

---
Tags: animation, unity, skeletal-animation
---


# Question
Title: Why not pre-render story parts in a game?
When playing games nowadays there are often story related cut-scenes, during which you cannot interact with the game, you can only listen to it or watch it while it plays.

However in a lot of games these story scenes are rendered live with the game engine, and not with pre-rendered videos. I can't seem to understand why the story scenes aren't pre-rendered during game development

My question is:

Why not pre-render a story cut-scene during game development as a video with the highest settings so the user doesn't need to render it on his/her end?

My guess is that game developers don't choose to do this because videos and real-time game rendering need a smooth transition a lot.

# Answer
> 93 votes
I can think of a couple of reasons:

* Pre-rendering and recording the video cost a LOT more space on the disk that animating it live with bone animations.
* Visual aspects. If you pre-rendered half of what you see in the game with "better" quality, the transition could make the game lose its flow. I can image following the main character of a game which is rendered with 1000 polygons during normal game play, but suddenly seeing him rendered with 2000 polygons, nice skin smoothing and 25 shader effects, this for two minutes then jump back with the low-res character... this would look odd.
* Internal approbation/modification process. I would guess that the pipeline to simply modify an animation for a cut scene from within a game company is much simpler than modifying the original asset of the animation, render it and make have it approved.
* No need for it (or 'because they can'). Game engines and hardware are getting more and more sophisticated and powerful, so the quality of what they produce is getting closer to cinema quality graphics, so since the end user machine can do it, why bother doing pre-rendering?
* Flow. As you suggested, unless you push your engine to do that, there could be a small loading time before showing a video, whereas a transition to a cut-scene imply loading a smaller amount of data and a small game state transition.

Suggested from the comments:

* Cost. Using a software with its architecture that optimize the pre-rendered scenes (such as Rad Game Tool's "Bink Video") can be costly to licence and implement. (Thanks @Honeybunch)
* Customization. If the player can change their character's appearance, equipment, or party composition, then either these choices are not reflected in the pre-rendered sections (e.g. a canonical character/loadout/party is always shown) or a number of pre-rendered videos are required to cover all possible combinations (which quickly becomes impractical if the player has many choices). (@DMGregory & @Kevin)

# Answer
> 44 votes
A lot of game allows characters to change appearance during play. Rendering cut scenes in the engine can reflect these changes. With videos you don't have that flexibility.

# Answer
> 23 votes
Other advantages of rendering cutscenes in-engine include:

* It scales to the hardware, unlike pre-rendered videos. Some older games have cutscenes rendered in 720p or lower, which simply don't look as nice on a 4k or higher resolution screen.
* It is more mod-friendly. If you choose to install high-res texture mods, or simply wish to replace your Witcher's horse with a cool-looking giant wolf, those modifications would be nowhere to be seen on a pre-rendered video.
* Lip synchronization is much easier to deal with in-engine. Nowadays, lip animations depend on audio tracks. That means the voice actor doesn't need to sync his speech to the character's lips' movements. If you ever need to localize your game from one language to the next, your voice actor only needs to focus on his lines and you don't need to re-render the scene.
* It is more flexible. Whether your character is barely standing upright due to his injuries, or whether he's drunk, his current state can be reflected much more accurately when rendered in-engine, than on a video.
* The environment is reflected more accurately. Maybe you just burned down the entire forest, or you somehow managed to avoid Aerith's death against all odds. Well, a pre-rendered video can't account for every eventuality.

---

In the end it all boils down to the fact that cutscenes rendered in-engine are dynamic, and therefore offer flexibility which a pre-rendered video simply cannot.

# Answer
> 19 votes
Games which got famous for pre-rendered cutscenes looking far better than the actual game are the PlayStation 1 era Final Fantasy games. The protagonist of Final Fantasy VII, for example, looked like this during cutscenes:

And like this during the actual game:

What is the problem with this? The difference between the aesthetics during cutscenes and actual gameplay was so different, that it barely looked like the same game. The break between cutscenes and gameplay was so obvious, it interrupted the immersion and challenged the players suspension of disbelieve.

Nowadays games avoid this by rendering narrative cutscenes with the game engine. That way the cut between interactive and non-interactive portions of the game is far more seamless.

Although it is something which is not 100% abandoned. The Witcher 3, for example, integrates a few pre-rendered CGI sequences. Famous is the intro cutscene, but there is also some subtle use during some key cutscenes in the actual game which can only be noticed by paying attention to video compression artifacts. The consistency problem due to character customization is solved by doing this mostly during scenes where no main characters are on the screen.

# Answer
> 2 votes
Another issue of pre-rendered cutscenes, is covering possibilities, as in today's games, your actions changes the course of in-game story.

Therefore, resulting in countless different combinations of outcomes and so, countless different pre-rendered cutscenes. This has some obvious limitations (Hundreds of GB, possibly TB).

Having the game engine render it in real time, means that you only need to send the relevant parameters containing what actions the gamer took up to that point. The game engine then calculates what the possible outcome is from those parameters.

This way, from only one engine, you can add as many possible outcomes you want.

---
Tags: rendering
---


# Question
Title: White dots artifacts when applying borders to hex tiled geometry
I have a hexagon tiled geometry I created in Blender

Which I then load in WebGL, using THREE.js library. Below is the loading code, I've cut the code of creating scene, lights, etc. I create rendered with antialiasing flag.

```
grassTexture = new THREE.ImageUtils.loadTexture( 'textures/GrassTileModo.png');
grassTexture.wrapS = grassTexture.wrapT = THREE.RepeatWrapping;

var loader = new THREE.JSONLoader();
loader.load("models/hexmap.json", function(geometry)
    {
        var attr = []
        for(var i = 0; i < geometry.faces.length; i++)
        {
            if(i % 4 == 0)
                att = [new THREE.Vector3(1.0, 0.0, 0.0), new THREE.Vector3(0.0, 1.0, 0.0), new THREE.Vector3(0.0, 0.0, 1.0)];
            if(i % 4 == 1 || i % 4 == 2)
                att = [new THREE.Vector3(1.0, 0.0, 0.0), new THREE.Vector3(0.0, 0.0, 1.0), new THREE.Vector3(0.0, 1.0, 0.0)];
            if(i % 4 == 3)
                att = [new THREE.Vector3(1.0, 1.0, 1.0), new THREE.Vector3(1.0, 1.0, 1.0), new THREE.Vector3(1.0, 1.0, 1.0)];

            attr.push(att);
        }

        var material = new THREE.ShaderMaterial( {
            uniforms:
                {
                    diffuse: {type: 'c', value: new THREE.Color(1, 1, 1)},
                    opacity: {type: 'f', value: 1.0},
                    map: {type: 't', value: grassTexture},
                },
            attributes:
                {
                    aBorderMap: {type: 'v3', value: attr, boundTo: 'faceVertices'}
                },
            vertexShader: document.getElementById('shader-vs').firstChild.textContent,
            fragmentShader: document.getElementById('shader-fs').firstChild.textContent
        } );

        plane = new THREE.Mesh(geometry, material);
        scene.add( plane );

    });

```

Basically, the idea is I assign each vertex barycentric coords, and use them to know which edge I need to outline. Since my hexagons are getting tesselated by blender to 4 faces each, I assign different attributes to different faces, the way edges I don't need to outline are not outlined. In my case on the edges I don't want to outline, z barycentric coordinate will be zero.

This is how blender tesselates:

Vertex shader code:

```
precision highp float;
precision highp int;

uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
attribute vec3 position;
attribute vec2 uv;
varying vec2 vUv;
attribute vec3 aBorderMap;
varying vec3 vBorderMap;

void main()
{
    vUv = uv;
    vBorderMap = aBorderMap;
    vec4 mvPosition;
    mvPosition = modelViewMatrix * vec4( position, 1.0 );
    gl_Position = projectionMatrix * mvPosition;
}

```

Fragment shader code:

```
precision highp float;
precision highp int;

uniform vec3 diffuse;
uniform float opacity;
varying vec2 vUv;
uniform sampler2D map;
varying vec3 vBorderMap;

void main()
{
    gl_FragColor = vec4( diffuse, opacity );

    vec4 texelColor;
    if(vBorderMap.x <= 0.05 || vBorderMap.y <= 0.05)
        texelColor = texture2D( map, vUv ) * 0.5  + vec4(0.0, 0.0, 0.0, 1.0) * 0.5;
    else
        texelColor = texture2D( map, vUv );
    gl_FragColor = gl_FragColor * texelColor;
}

```

When I zoom out those artifacts can be clearly seen:

Although zoomed in it looks much better:

At first I thought lack of antialaising was a problem, but when I added it, it didn't help.

EDIT:

js fiddle link ---\> https://jsfiddle.net/denisve/ad74pf77/5/

full screen ---\> https://jsfiddle.net/denisve/ad74pf77/5/embedded/result/

WARNING: Huge embedded image there, so will take some time to load, sorry about that, didn't find a way to use external images on jsfiddle.

# Answer
> 1 votes
You need to use texture linear filtering or nearest filtering.

```
texture.minFilter = THREE.LinearFilter;

```

---
Tags: shaders, webgl, three.js
---


title: Writing my own gravity

text:
# Question
Title: Writing my own gravity
I am writing a little game engine in LWJGL. I want to have a gravity, but I don't know correct equations. Let's assume that I've got a 3D vector marking gravity force in each axis(e.g. Vector3f(0.0, -9.8, 0.0) would be Earth's gravity), object's mass and object's CdA(coefficient of drag multiplied by approximated object area). I wanna know how to correctly calculate object's gravity!

# Answer
If you want to write a fully functional physics engine I'd recommend learning some basic newtonian physics. Wikipedia is a good starting place for those kind of things. That being said I'll try to provide some information about your "problem" and beyond that.

---

**Physical explanation:**

At every point in space you have a *local gravity*, usually named *g*. g is an acceleration with m/s² as unit (you could use other units like km/h² or something like this, but they're usually useless). In 3 dimensional space acceleration is a vector with 3 components (x, y, z).

Accelerations simply represent the increase of velocity per time frame, usually per second. So if you want to calculate your velocity at time t you simply have to do v = a * t + v0, of course assuming a is constant over your time t. v0 is the velocity of your object at t = 0 (If you have a car going 130 km/h and accelerate it by 5 (km/h) / s over the time of 6 seconds you have a final speed of 160 km/h).

---

**Using it in your game**

Long story short: If you want to have your velocity you simply have to add a * dt to your former velocity vector, where dt is the time that passed since the last frame (At fixed 60 fps 0,0166666... s). Keep in mind that your units have to match. If g is in m/s² your dt also has to be in s.

Pseudocode:

```
velocity += g * dt;   //Assuming your math library allows * operator for vectors

```

---

**Further physical explanation for multiple gravitational pulls:** Of course in reality the local gravity is not equal everywhere. The equation for gravity force is:

```
|F| = G * m1 * m2 / r²
where G = 6.67e-11, m1/m2 = the masses of your objects, and r = distance between the center of mass of both objects

```

Important fact about this force: It affects both objects, but usually you only care about one of them, because the effect on the other one is neglegible. The direction of the force is always towards the mass center of the other object.

If you have multiple masses with relevant gravitational pull you have to add you force vectors F together and finally use the following equation to calculate your final acceleration: `a = F/m`

Now, you could want to include air resistance. This makes the matter much more complex as you have multiple factors to consider: Density and pressure of your medium (Maybe it changes depending on your current height). Or your area covered by the falling object, which again decreases acceleration (in this case mass of your falling object also matters again, without air resistance it's not relevant). Covering all possible cases is way to much to do in a simple answer here so I'd recommend starting further research here.

**Disclaimer:** Of course this explanation is based solely on newtonian physics. Einstein's relativity is not taken into account, but it only matters significantly if v is in scale of 0,1c or higher
> 4 votes

# Answer
The figure of 9.8 metres/second/second is only accurate at a distance of approximately 6371 km from the Earth's centre, and only for a planetary mass of approximately 5.972 * 10^24 kg.

However, if you use those calibration figures above, thus measuring distance in *Earth Radii* (Re) and mass in *Earth Masses* (Me), then a general gravitation equation for the magnitude of the gravitational acceleration (Ga) can be obtained as

Ga = - (9.8 * Me / Re / Re)

Note that in a 3D world the direction of the gravitational acceleration (or force) is always exactly opposite to the displacement of the object from the centre of the planet.

As long as you only have one very massive object in your system it will be sufficient to omit the gravitational force between the moving objects of your system, and to keep this single massive object stationary. However as soon as you have a second very massive object, be it moon, planet, or star, this approximation will not be accurate.
> 3 votes

# Answer
I believe you are wanting to simulate a simplified, uniform gravitational field where the following assumptions are true:

* The mass of the object in question is negligible compared to the mass of the object it is being gravitationally attracted to.
* Any *change* in distance between the object in question and the other object is negligible compared to the *total* distance between them.

If this is the case, then these simplifications allow us to simulate gravitation very easily by just using an acceleration equation. At each time step, increment the object's velocity vector by the *acceleration* * duration of time step *dt*:

`velocity += acceleration * dt`

Where, in the Earth surface gravity case, `acceleration` would be the Vector (0, -9.81, 0) where positive y represents the upwards direction.
> 1 votes

---
Tags: java, physics
---


# Question
Title: Screen transition effect like subway surfers
I would like to know how can I achieve this kind of screen transition effect ? The effect is screen independent.

https://www.youtube.com/watch?v=Muh7QFisCfE#t=01m57s

# Answer
Placing an animation on a UI panel that goes under other UI elements should do the work. Because canvases are automatically stretched to fit whole screen.
> 1 votes

---
Tags: unity
---


# Question
Title: Collisions between mesh (bounding-box) and Vertex/Index Buffer
I have a short Question: I'm trying to add Collisions in my 3D DirectX9 game and my World is Stored in a `LPDIRECT3DVERTEXBUFFER9` and `LPDIRECT3DINDEXBUFFER9` and Rendered per `DrawIndexedPrimitive`. My Player is a `LPD3DXMESH` loaded from a .X file. Now I want to detect Collisions between the two! How can I do that? After some research I could only find Collisions between Bounding Boxes and/or Rays!

Apologise my bad English, I'm German! :-) Hope for fast reply!

# Answer
> 1 votes
Fundamentally what you need to find is OBB-Triangle intersection. Some searches yield on answer here:

Moving OBB vs. triangle intersection test

The complexity of your case comes in to play in that your vertex data is stored in a D3D buffer - not an ideal format for collision detection. You will have to lock the vertex buffer each time you test. Depending on whether it is triangle strips or triangle lists you will need to pull out the vertices to test against them. Furthermore, to make collision detection against triangles fast enough you need a spatial data structure to wrap it. I wrote about that here: When would a mesh collider be better than primitive colliders

As for the player, you will need to lock the mesh buffer and find the bounding box. The problem you will have is that, if the player is being posed by animation, simply locking the player buffer may not give you the correct vertices as they are posed on the GPU. You'll need to do something more sophisticated to get a useful AABB.

To be performant, you might want to duplicate the triangle vertices in main ram in a format that is best suited for collision detection.

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


# Question
Title: Reading mesh data back from OpenGL vs storing two copies
I'm wondering if whether it's a good idea or not to keep a copy of vertex data in the main memory or just read it back via `glGetBufferSubData` (or `glMapBuffer`/`glMapBufferRange`).

The reason why I'd do this is so that I can keep only what's needed in the VRAM (and resource which may be needed very soon in the main memory) but not have to go back and load the resource from the disk again.

The concern that I have is that, with the draw optimized flags (`GL_XXXX_DRAW`) is that they aren't optimized for reading back (since there's a seperate flag for that). So if it's not very fast, it kinda defeats the whole purpose.

The other option is storing a second copy and just delete the VBO when I'm done (no reading it back), but I dislike this because it requires more memory usage than might be necessary.

Which option is preferred? Is there another way? Maybe something I'm missing?

# Answer
> 2 votes
VRAM management is between the GPU and the GPU driver. The driver could do a few things, it could throw an error when it doesn't have VRAM to do an operation, or it might just start streaming from the system RAM (avoiding the main issue, and possible game crashes.)

Streaming from the system RAM is the more likely solution, however communication between the GPU and CPU **can be** extremely slow in the context of a game environment.

Because of that communication cost, for performances sake, you should also avoid reading data from the GPU (or wherever else the GPU driver has it) if possible. That would mean keeping a copy of critical data locally, and deleting the GPU side of the data as needed. So, yes, it is a good idea to keep copies of the data locally.

The problem with that, is that you could start running into issues with not having enough system RAM. However, that can be avoided with temporary files. If you create a "raw data dump", type of file, you can parse your game files, and then literally just store little used data straight into a disk file.

As a temporary raw data file, you don't need to parse it again. However, possibly machine specific (I'm thinking specifically of architecture endianness here.)

Disclaimer: All of this is assuming VRAM is an issue. If it's not giving you a problem, don't fix it. If your worried about the consumer market, calculate out how much VRAM your application is using, decide what your "Minimum requirements" are, then fix the issue if present.

# Answer
> 0 votes
the openGL driver will unload stuff from vram on its own as needed (most of the time).

And if you are ready to remove the mesh from vram then you should be sure you are not going to needed it for a minute. When reloading it you might as well read it back from disk.

---
Tags: opengl, c++, resource-management, vertex-buffer
---


# Question
Title: Duplicate a Prefab as a separate asset in Unity 5.2
I have a Asset which is a collectable object \[Pickup\] and I currently have eight in my scene, I'd like to duplicate this asset and use it to harm the player \[Bad Pickup\].

I decided to duplicate the asset because I wanted both assets to have the same components (Animation script, rigid body, mesh colider, etc...). However, when I edit the texture of my new asset \[Bad Pickup\], it changes the texture used for the original asset \[Pickup\] as well.

I've tried GameObject -\> Break Prefab Instance on the object with the new asset but it doesn't appear to make a difference.

Is there a way to break this instance so that I don't have to make a completely new GameObject and add the same components manually?

# Answer
This is because you're editing a material. Prefabs simply reference materials, they don't contain them. That material is used for both prefabs. You can duplicate the prefabs, but make sure you create a new material for any prefabs you want to have a different material.
> 2 votes

---
Tags: unity, assets, gameobject
---


title: Setting resizable to false in LibGDX

text:
# Question
Title: Setting resizable to false in LibGDX
I have a small working game prototype. I want to do something like

```
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.resizable = false;

```

But I get "LwjglApplicationConfiguration cannot be resolved to a type"

What can I do? Or is there a different method? Thanks.

# Answer
This code should work:

```
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.resizable = false;
new LwjglApplication(new YourGame(), config);

```

Are you using the newest source from svn?
If it still doesn't work, there must be another problem..
> 1 votes

---
Tags: libgdx, graphics, window-management
---


title: Move ball based on direction of force?

text:
# Question
Title: Move ball based on direction of force?
I'm trying to make a ball that will move in the direction I push it from, and later pull it to me based on where the player is standing.

```
using UnityEngine;
using System.Collections;

public class BallForce : MonoBehaviour {

    public float thrust;
    public Rigidbody rb;

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

    // Update is called once per frame
    void Update () {

        if (Input.GetMouseButton (0))
            rb.AddForce (transform.forward * thrust);
    }
}

```

This seems to work, but I'm not sure how I get it to move based on the position of the player. How would I do this?

# Answer
To find a vector **from point A to point B**, you do this: **B - A = C**. The **C vector** is the vector that **starts from A** and **ends at B**.

In this case your vector A is the ball's position...
...and the vector B is player position...
...so the resulting vector C will give you a vector from ball to player.

Then you can use `C.normalized * thrust` for your force.
> 2 votes

# Answer
You could use Quaternion.LookRotation( transform.position - PLAYER POSITION ) which can be used to make the ball turn in the direction of the player and then you could add forward force to the ball for it to be pulled.
> 0 votes

# Answer
Instead of adding force based on the ball's direction, add it based of the players forward-vector.

You will have to tag the playerobject in the Inspector as "Player" (without quotations)

Try this:

```
private GameObject player;
void Start() {
    player = GameObject.FindGameObjectWithTag("Player");
}
…
if (Input.GetMouseButton (0))
    rb.AddForce (player.transform.forward * thrust);

```

Since you probably will have more or even **many** balls in the scene, a script for every ball would be an overkill, and would decrease the performance of your game. (except it's a game similar to football)

The better solution would be a BallManager. Tag every ball with the tag "ball" and check when the mouseButton is down, if the clicked object is a "Ball".

```
public class BallManager : MonoBehaviour {
    private GameObject player;

    void Start() {
        player = GameObject.FindGameObjectWithTag("Player");
    }

    void Update() {
        if (Input.GetMouseButton (0)) {
            Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
            Raycast hit;
            if (Physics.Raycast(ray, out hit, 100.0f)) {
                if (hit.gameObject.tag == "Ball") {
                    hit.gameObject.GetComponent<Rigidbody>().AddForce(player.transform.forward * thrust);
                }
            }
        }
    }
}

```
> 0 votes

# Answer
You could create a variable to reference the ball in the player script and just push forward or pull backwards in this script as the direction will be depending on the player, something like this:

```
public GameObject ball;
void Update(){
    if(Input.GetButtonDown("Fire 1")){
       ball.GetComponent<Rigidbody> ().AddForce(Vector3.forward * speed);
    }

    if(Input.GetButtonDown("Fire 2")){
        ball.GetComponent<Rigidbody> ().AddForce(-Vector3.forward * speed);
    }
}

```
> 0 votes

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


# Question
Title: How to animate child from parent in the Animation view?
For some reason I can't change the value of the scale properties.

The scale properties belong to a child object, and I added them with "add Property".

What I'm trying to do is, adding an Animation to an empty parent object, which is going to animate a few of the child components for an menu opening animation. I need the animation on this parent object.

# Answer
It is definitely possible to animate multiple children objects via one animation component on the parent object. First, select your parent object in the object hierarchy. Then open up your animation window (if this is not already within view, it can be opened by clicking `Ctrl + 6`). Create a new animation clip and name it whatever you want. In your animation view shown below, you will see the button "Add Curve". When you click the "Add Curve" button, you will see all the components of the parent object as well as all of the children objects:

Click on the triangle next to the child object's name and you should be able to choose which components of that child you want to animate.
> 0 votes

---
Tags: animation, unity
---


title: Attach to a GameObject after collision?

text:
# Question
Title: Attach to a GameObject after collision?
How can I make a GameObject attach (or "stick") to another GameObject after collision? The problem: ***I want the GameObject to attach after collision even if it changes scale***.

What I have tried:

```
protected Transform stuckTo = null;
protected Vector3 offset = Vector3.zero;

public void LateUpdate()
{
    if (stuckTo != null)
        transform.position = stuckTo.position - offset;
}

void OnCollisionEnter(Collision col)
{
    rb = GetComponent<Rigidbody>();
    rb.isKinematic = true;

    if(stuckTo == null
       || stuckTo != col.gameObject.transform)
        offset = col.gameObject.transform.position - transform.position;

    stuckTo = col.gameObject.transform;
}

```

This code makes a GameObject attach perfectly after collision. But when that GameObject changes scale (while it's attached), it visually no longer looks attached to whatever it collided with. Basically, this code makes the GameObject stick with **only** the original scale at the moment of the collision. **How can I make the GameObject *always* stick to whatever it collided with? And with whatever scale it has during the process?**

# Answer
It's much simpler than you think:

```
void OnCollisionEnter(Collision col)
{
    transform.parent = col.gameObject.transform;
}

```

You don't need the late update.
> 2 votes

---
Tags: c#, collision-detection, unity
---


# Question
Title: LibGDX - Level management on a level-based game
I'm new to LibGDX and android development in general and am trying to do a puzzle game. Being a level-based game, i'm trying to make it so in every level a certain number of blocks (just rectangular sprites) appear in a certain position / rotation, like in the image linked below:

https://i.gyazo.com/52e6c71e1f05ab4529e0fec9d4f80bd7.png

I've doodled some levels already but i'm really not sure about how to make the blocks's rearrangement over the levels. How exactly should one manage this? As the position of the blocks won't be random i was thinking about reading from files the information from every level (x, y, rotation, colors, etc. for every block) but to do that i would have to manually organize every level's blocks properties information (to then save), and, considering it would have atleast 100+ levels, it would take too long... Other than that, i could have them as plain assets but having an asset for every single level doesnt't look like an efficient solution either. Do you have any tips, please?

# Answer
> 1 votes
In a puzzle game that I have been working on I have found that an XML file has been a rather efficient way to store level data.

For example, you could have an xml file for each level pack

```
   <LevelPack>
      <Level number="1">
        <Block x="0" y="0" rotation="90" color="#FF0000" />
        <Block x="50" y="22" rotation="45" color="#00FF00" />
      </Level>
      <Level number="2">
        ...
      </Level>
   </LevelPack>

```

You could then serialize the xml file into some sort of model object in your code. Even with 100+ levels this should be easy to manage and is way less time consuming than making a level editor.

---
Tags: java, android, libgdx
---


# Question
Title: How can I use shaders in Unity to write a scientific computing program?
I want to write a GPU shallow water code on Unity3D. For sure, performance matters a lot. I've done this before using DirectX and C++. But for a couple of reasons I want to redo it in Unity3D.

I have some hands on experiences with Unity3D, but I have no idea how I can write GPGPU codes, like what I did in DirectX.

In DirectX I am using textures as my data structure for the properties of water cells (height, x-velocity, y-velocity, etc.) and HLSL shaders as my parallel computational functions (kernels).

Furthermore, I prefer my code to be \[near\] cross-platform. Is it possible to do something similar in Unity3D using OpenGL?

I am an engineer, and not a game developer, so please keep it simple ...

# Answer
> 5 votes
In Unity you can do with shaders pretty much everything you could do with DirectX or other Framework/APIs as long as you use the shader for stuff like surface materials or post processing. Vertex and surface shaders are written in HLSL/Cg but are wrapped in ShaderLab code. I don't know how much that impairs your cross-plattform requirement, but since Unity supports a broad spectrum of target platforms, it should suffice.

Here is some more information on shaders in Unity: http://docs.unity3d.com/Manual/ShadersOverview.html

You store the shaders you write in .shader files. They are recognized by Unity as shader assets and can be chosen in Unity material assetes. Unity shows them automatically in a drop down menu at the very top of each material insptector (see http://docs.unity3d.com/Manual/Materials.html).

Keep in mind that this drop down menu is not structured the same way your .shader files are structured on your file system. They are structured by the path/name you assigned at the beginning of the shader lab code. So if your shader starts with:

```
Shader "foo/bar" {
[...]
}

```

your shader will appear accordingly under foo --\> bar in the material's shader selection menu. The name of the .shader file is not taken into account.

---
Tags: unity, opengl, directx
---


# Question
Title: Partial mesh culling by checking against the AABB-tree of objects vertices instead of only the AABB of the whole objects
First thing: this is more of a conceptual question than an implementation oriented one, but still tips about implementation will be very much welcome if you happen to have any (athough I have some experience programming different parts of games, graphics are certainly my weak spot - as you will see).

So, I have an application in which all high-poly objects have their vertices grouped in an object-specific AABB-tree to speed up the narrow-phase of collision detection. Now, it occurred to me the following. Since that structure is already in place, would it be possible to use it for culling parts of objects instead of the usual all-or-nothing approach of the frustum and occlusion culling techniques?

The idea for that is simple in concept. Instead of testing for visibility only using the whole objects' AABB, I would do that first but in the positive cases I would proceed to visibility checks of the sub-AABBs containing that object's vertices. Once identified the sub-AABBs that are visible, only the triangles that are contained in these sub-AABBs would be sent to the GPU for rendering.

Therefore, in a more systematized way, my three related questions are:

1) is such an approach even possible in what regards the way GPU gets and processes the mesh geometry information pulled from CPU?

2) given that in such scenario the CPU would have to break the meshes somehow and pass to the GPU only the vertices that were identified as being in the visible parts of the visible objects, wouldn't that pose additional load on the processing time such that the cost would overcome the gains?

3) most importantly, passing to the GPU only some triangles of a mesh could cause graphically distorted results when shader and texture are rendered for that partially-only rendered object?

I searched quite a bit for academic references on this subject but came almost empty. I would gladly welcome reading suggestions of any sort.

# Answer
I'll answer your question(s) in the order you asked:

Therefore, in a more systematized way, my three related questions are:

> 1) is such an approach even possible in what regards the way GPU gets and processes the mesh geometry information pulled from CPU?

It's possible to only send N vertices from a vertex buffer using the offset & size arguments in most APIs.

> 2) given that in such scenario the CPU would have to break the meshes somehow and pass to the GPU only the vertices that were identified as being in the visible parts of the visible objects, wouldn't that pose additional load on the processing time such that the cost would overcome the gains?

Absolutely - in modern GPUs the overhead of each draw call is very high, so your proposed plan is likely not of great benefit unless the model is exceptionally high polygon. Imagine a case where the arm, head and foot of a model are visible because the model is 'looking into' the frame. You would have three draw calls - one for the arm, one for the head and one for the foot. This defeats any optimizations. Remember that the hardware performs viewport clipping - the triangles are transformed into clip space and potentially rejected there prior to any rasterization. This is relatively efficient. Furthermore, meshes are split on *material* boundaries, which might be spread all over the model which complicates the value of your approach. Often a single vertex buffer is shared among multiple materials - a collection of shader parameters and textures. Each material must be issued with a unique draw call. Artists often make every effort to use a single material per model to minimize draw calls but it isn't always possible.

> 3) most importantly, passing to the GPU only some triangles of a mesh could cause graphically distorted results when shader and texture are rendered for that partially-only rendered object?

No - this won't cause any problems as long as you guarantee sending all of the visible, front-facing triangles - the GPU only cares about what is visible, not the ones that are clipped off screen.

Ultimately, I don't think this is worth the extra effort as breaking up the draw calls will reducing batching, which is really important for performance.
> 1 votes

---
Tags: rendering, aabb, culling, frustum-culling, visibility-determination
---


# Question
Title: How Apple Metal API distinguishes uniforms from vertices buffers?
I am not sure how metal distinguishes uniforms from vertices buffers? As far as I know code for passing uniforms in buffers are the same like for vertices:

```
[self.commandEncoder setVertexBuffer:positionBuffer offset:0 atIndex:0];
[self.commandEncoder setVertexBuffer:uniformBuffer offset:0 atIndex:1];

```

In shader code there is no keyword defining some struct as uniforms, so how Metal know it? In Opengl GLSL was uniform keyword which was clear for me but I can't figure how it is solved in metal.

# Answer
They are defined in vertex shader signature, eg.

```
vertex ColorInOut unlit_vertex(device vertex_t* vertex_array [[ buffer(0) ]],
                            constant uniforms_t& uniforms [[ buffer(1) ]],
                            unsigned int vid [[ vertex_id ]])

```

Earlier I define them like this:

```
typedef struct
{
    matrix_float4x4 _ModelViewProjectionMatrix;
    float4 tintColor;
    matrix_float4x4 _ShadowProjectionMatrix;
} uniforms_t;

typedef struct
{
    packed_float3 position;
    packed_float2 texcoord;
    packed_float3 normal;
    packed_float4 tangent;
    packed_float4 color;
} vertex_t;

```
> 3 votes

---
Tags: shaders, rendering, metal
---


# Question
Title: the half of the screen does not seem to work correctly
I am not such a professional coder but trying to code something on Unity. However, when I try to play the application in my android phone, the half of the screen does not seem to work correctly:

Can you guess what the reason is for that?

Up to now, I have changed screen resolution but it did not solve my problem.

Thanks for your help!

# Answer
After changing Main Camera setting according to this photo:  , I have solved my problem.

@Jon might have said same thing but my English was not enough to understand. Thank you all for your help!
> 1 votes

# Answer
Gameobjects with same coordinates or depth values sometimed cause jitter or overlap (as seen in your question). Try changing depth or sorting axis.
> 0 votes

---
Tags: unity, screen
---


# Question
Title: Unity3D Sprite tearing on Android Smartphone
The game was running on Samsung Galaxy Trend 2.

On other smaptphones and emulator it seems running properly without glitches.

Sprites import settings are following:

Could someone explain why this happens?

# Answer
99.99% of the time "Generate Mip Map" is the culprit behind such problems. Please switch of this option for all sprite import setting. This option is only needed for 3D objects where the engine can scale down the texture according to the z distance for performance optimization.

You can read more about Mip Maps in this link - https://en.wikipedia.org/wiki/Mipmap
> 1 votes

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


# Question
Title: Is it necessary to use texture filtering if I use texture coordinate system?
I have one question about using texture filtering. It's clear when I used normalized texuture coordinates (in any API) for example from (0,0) to (1,1) it is necessary to use texture filtering because it's not obvious which pixel should be taken for example at point (0.5, 0.5).

But what in case when I use texture coordinate system. For example I use exact pixel position to assign it to fragment in fragment shader, for example (332,543). Is it necessary to use texture filtering in that case in order to avoid texture artifacts?

# Answer
As more I think about this I found it is always necessary to use texture filtering to avoid texture artifacts. It is because rasterized image which will be textured in fragment shader can have different size of pixels than pixel (texels) in texture.
> 1 votes

---
Tags: textures, coordinates, fragment-shader, uv-mapping, filtering
---


# Question
Title: Term for coordinating design elements to produce larger possibility spaces?
The concept is when content elements work together in such a way to produce more possibilities, playable content, or engagement than the relative amount of added content.

## Mathematically:

**A** content gives you **x** units of gameplay

**B** content gives you **y** units of gameplay

*(units of gameplay are however you'd like to measure them, hours of play, total items, actions/discussion branches, etc.)*

```
A = x
B = y
A + B = x*y*?

```

So that when the game includes both:

`A + B`

The gameplay unit increase could be:

```
x * y
(x + y) * c
x ^ y

```

This concept of expressing it mathematically leads me to want to call this **Content Multiplication**. But I haven't been able to find much on a specific term for this (most of my attempts have lead me to math games).

## Example:

In a game like Minecraft, there's a mechanics and dynamics that define crafting. By themselves they produce a set of craftable items. Once a player crafts them there's less or no desire/need to craft them again.

Then a relatively small mechanic is added that causes loss, perhaps on death or through durability. The impact on player motivation and time played is much larger. Forcing players to either recraft items, or to craft extras preemptively. No new items have to be added to the crafting system, and having players lose items isn't a big change (not a lot of work).

Specifically if we look at just these two mechanics, and the expected impact they have together. Perhaps we're talking about Minecraft 0.1, and only crafting exists, and a decision needs to be made on what next feature to add, that provides us with the most benefit in gameplay content for development effort.

## Conclusion

Is there a term to describe the intentional design of coordinated mechanics and system to produce larger sets of content with minimal effort?

---

## Edit: Emergence

Emergence typically refers to unforeseen and unintended results rising from a rise in complexity. Emergent results are frequently hard to quantify, or to ascribe cause to specific elements.

What I'm looking for is an explicit, deliberate, and predictable outcome from the addition of a single element to an existing system.

## Contrasting Example:

An example of emergence can be found in the original Deus Ex. Being able to place mines on walls and jump off of them. This effect was (likely) unintended, caused by the interaction of complex systems, and in cases where it could be used to skip content, actually reduced the amount of gameplay. Emergent Gameplay

While designing for emergence can be intended, the outcome is less certain or planned.

# Answer
An emergent system, perhaps? I think you're describing something very similar to emergence, which is when an ensemble produces a set of characteristics not displayed by any of its individual components.

Tracy Fullerton's Game Design Workshop has an interesting section on games as systems, which might provide more insight.
> 3 votes

---
Tags: game-design, terminology
---


title: DirectX is difficult sometimes

text:
# Question
Title: DirectX is difficult sometimes
I recently started DirectX 11. Sometimes I can't get my head around it.

1. First of all what are COM objects and why we do have to release them?
2. I have done most of initialization, but I am stuck in the rendering pipeline. How is a game structured? I mean you do the initialization (device, swapchain, viewpoint etc, back buffer etc.), you do the rendering pipeline and then what, do you have a framework, a very basic engine, you are done with low level stuff and continue programming graphics now?
3. How much do I have to learn directX, is it really that difficult?

# Answer
> 1 votes
1. COM objects are objects that forward their calls to another environment. How it works exactly is not important, what is important is that the underlying resources are reference counted; you increment the refcount with `acquire` and reduce it with `release`. when you create a COM object it is automatically initialized with a refcount of 1 so a single release with destroy it again.

If you fail to release one it will leak and may cause issues for your system.
2. After initialization you would start the game loop. This is typically a while loop that checks the input, updates the game engine and renders the game to the screen.
3. I'm not going to get into this part as it's off-topic here. But I'll say it's easier if you use a game engine to build your game with as it would have most of the rendering and physics already implemented.

---
Tags: directx11
---


# Question
Title: How to use .fbx for 2D animation in unity 2D
I am new to unity so please bear with me. I have come to know that for animations it is better to fbx format in unity rather than sprite sheets. I am using unity 5.2 and till now i created all my animations inside unity using sprite sheets. I have been looking at fbx and i cant seem to understand how to use the fbx model i imported in a 2d game? All tutorials are for 3D games. Once the fbx is imported , it creates a prefab with all animations in it.. but how to use them ..? Can someone point me to a good tutorial or so..

thanks

# Answer
> 1 votes
First off, "better" is a relative term. 2D animation (2D games in general, not just in unity) is generally done using spritesheets because they give you the most flexibility. That said, Unity can display any 3D content within a 2D game, so you can use a 3D animation like fbx. That will give you an advatage with interpolation/variable framerates, but at the cost that the appearance of the animation is less flexible.

The thing to realize is that it's still fundamentally a 3D animation, it's just viewed from one side. Thus create the animation in a 3D animation tool, but make it work with a static side view. For example, the 3D parts may actually be planes oriented to face the camera.

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


title: Frame timer does not show time

text:
# Question
Title: Frame timer does not show time
I am currently using DirectX11 and MFC. The top of the window should tell me how long it takes to render the cube (in seconds). At the moment the cube is rendered but when I try to work out how many seconds it took to render the cube I keep getting 0 on the top of the window. This cannot be right. Help please?

This is my Ondraw function:

```
void CLearningVisualCView::OnDraw(CDC* pDC)
// I want the OnDraw function to create the cube..
{

    CString TimerReports;

    // TODO: add draw code for native data here

    CLearningVisualCDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    if (!pDoc)
        return;

    Timer.GetStartTime();
    Render(); // This renders the cube

    Timer.GetEndTime(); // The counts stopwatch ends.
    Timer.DeltaCountDifference(Timer.StartTime, Timer.EndTime);
    Timer.GetSecondsPerCount();
    Timer.FrameTime(Timer.DeltaCounts, Timer.SecondsPerCount);

    TimerReports.Format(_T("%.100I64d"), Timer.Time);

    //TimerReports.Format(_T("%.5I64d"), Timer.FrameTime(Timer.DeltaCounts, Timer.SecondsPerCount)); // This converts the DeltaCountDifference into a CString. It has 5 d.p.
    AfxGetMainWnd()->SetWindowText(TimerReports); // This displays my count difference to the top of the window.

}

```

This is my Timer class:

```
#include "stdafx.h"
#include "GameTimer.h"

GameTimer::GameTimer()
{

//  QueryPerformanceFrequency((LARGE_INTEGER*)&countsPerSec);
//  SecondsPerCount = 1.0 / (double)countsPerSec;

}

GameTimer::~GameTimer()
{

}

_int64 GameTimer::GetStartTime()
{

 QueryPerformanceCounter((LARGE_INTEGER*)&StartTime);

 return StartTime;

}

_int64 GameTimer::GetEndTime()
{

    QueryPerformanceCounter((LARGE_INTEGER*)&EndTime);

    return EndTime;

}

// The _int64& are references. We will link them to the StartTime and the EndTime in the CLearningVisualCView - OnDraw(). This is done by adding them as arguments.

_int64 GameTimer::DeltaCountDifference(_int64& TimeA, _int64& TimeB)
{

        _int64 DeltaCounts = TimeB - TimeA;

    return DeltaCounts;
}

float GameTimer::GetSecondsPerCount()
{

    QueryPerformanceFrequency((LARGE_INTEGER*)&CountsPerSecond);

    SecondsPerCount = 1 / CountsPerSecond;

    return SecondsPerCount;
}

_int64 GameTimer::FrameTime(_int64& TheDeltaCounts, float& SecsPerCount)
{

    Time = TheDeltaCounts * SecsPerCount;

    return Time;
}

```

# Answer
`SecondsPerCount = 1 / CountsPerSecond;`

That will always be 0. `CountsPerSecond` is an integer value, as is the constant `1`. Integer operations result in integers.

You will need to coerce the arguments into a floating point format before performing the division. The best way to do this without potential warnings would be:

`SecondsPerCount = 1.0 / static_cast<double>(CountsPerSecond);`

Which is the code you have commented out in your sample.

You also didn't show the header for that type, so there could be a bunch of errors there as well that we can't possibly know about.

Lastly, keep in mind that you may not be measuring what you think you're measuring, as calling graphics API draw commands will not actually draw the image. You need to flush the command queue or present the window backbuffer to ensure all the draw commands are actually processed. You are (probably) accurately measuring how long it takes your application to ask the GPU to do some work, which may or may not be what you want.
> 2 votes

---
Tags: directx11
---


# Question
Title: Get collision time between two moving, non uniform Axis Aligned bounding boxes
I have a problem finding the exact time of collision of two possibly moving or static objects. Both objects have AABB data (HalfExtents, Min, Max, Center vector and stuff) and a velocity vector. The objects, as I wrote, can move, but must not to. How can I get the exact collision time from now? Could you give me please a pseudo code, or at least some directions how can be this solved?

# Answer
It's been a while since I've had to write code to do this, but here's how I used to do it, so I'm not going to write any code for this post, but I'm going to describe the theory in a way that hopefully sets you down the right path. You didn't mention whether their rotations changes at all during a single collision test, so I am going to assume they are not. The math gets much more complex rather quickly if you have an angular velocity as well.

Each box is made up of 8 points, and 6 planes. Both boxes can be moving, but since we only need to find the time during the frame where they collided, we can transform 2 moving boxes into 1 moving box by adding the velocity of one of the moving boxes (box A) to the other (box B) before setting the velocity of box A to 0. So you know have 2 boxes, one which is not moving, and one which is moving. For the purposes of the algorithm we're about do, this will work, since we only care about the movement of the boxes relative to each other, and not their velocities relative to the rest of the world.

You can now take each of the corners of Box B (the moving one), and convert each of it's corners into a line that extends along this frame's velocity. You can then do a simple check of an intersection with each of these lines from Box B against each of the planes that make up Box A. If any lines cross any plane, then by doing a plane vs. line collision, you can find out where on the plane the line crosses. The planes that make up the box are infinite length, so we need to check if the point is within the bounds of the box's plane. You can then do a dot product with that point of intersection against the normal coming out of each of the other 5 planes and make sure that the dot product is negative, which means you are "behind" the direction the plane is facing. If you are behind all 5 of the other planes on your point of intersection, then you have a collision. Save the time value for where on that velocity vector you had a collision. Repeat the same steps for each of the 6 planes, and save the smallest t value that is between 0 and 1.

At the request of the original asker, I'm expanding this section. If you run the algorithm above, you'll get all of the collisions for where a corner in Box B intersected Box A. You will *not* have the collisions for where Box A's corner intersects Box B, so repeat the algorithm above, but reverse the boxes. To help visualize it, in the case of our boxes, think about the types of collisions that can occur here. Since the planes of the boxes are flat, and they are convex. The fact that they are convex means we don't have any interior points, every vertex in the shape is a point. So there are only a few ways that these boxes can collide. One of the points on Box A can pass through one of the flat planes in Box B. One of the points in Box B can pass through one of the flat planes in Box A. A flat plane of Box A can hit a flat plane on Box B (for example, if they both have the same rotation). Finally, a point on Box A can hit a point on Box B (the corners are touching). The first test we did will detect whether a corner from Box B penetrated Box A, but a corner from Box A penetrating one of the sides of Box B wouldn't be detected. To detect that case, we can do the same tests we did in the first step, but reverse Box A and Box B. This will allow us to catch that collision.

In my example, I listed 4 possible collision types, so I'll briefly go over the last 2. If the 2 boxes have co-planar sides, then our collision should still catch it, since if the 2 boxes have coplanar sides, then a corner still needs to pass through one of the planes we detected earlier, and we should still catch it. A similar case is also true for the corners penetrating each other. You can potentially miss some collisions due to floating point error. You may not run into this case, but if you do, the standard way of handling it is to put in a tolerance/fudge factor for each of these tests, so that very close "near misses" still collide.

This is a relatively simple example that illustrates how most of these collision tests are run. What they are all doing, at a fundamental level, is breaking the collision down into the simplest possible checks we can do, and then doing the checks using algorithms that can determine the exact intersection time. If you want your boxes to be rotating during the collision, then you'll have to figure out how to take the rotation account. For example, you could do the same thing but instead of straight lines, you would have to use a curved line instead, which gets more expensive (algorithmically). If you wanted to not have a constant rotational velocity, then you'll have to break it down further. At some point of complexity, you won't be able to break your primitives down enough, and you will have to look at other ways of determining whether you had a collision.

For speed purposes, you'll also want to do some quick checks that you can use to discard the possibility of a collision. For example, if the start and end points of each corner on one of the boxes are all on the same side of any edge planes that make up the other box, then for sure no collision has occurred (since you didn't cross any planes). This check will be much simpler and faster to execute before you process any further, so you can use those sorts of checks to optimize your code if needed.
> 1 votes

---
Tags: collision-detection, physics, intersection
---


title: Competing keyboard events

text:
# Question
Title: Competing keyboard events
When I was looking on how to handle key inputs in a game loop I came across the following pattern: All native key events (up or down) get queued in an event queue that is later processed. The outcome is an array, that says for each key if the key is down or up. Pretty straight forward. I then took a look in the DOOM 3 BFG source code and it seems, they do exactly the same:

DOOM-3-BFG/neo/sys/win32/win\_wndproc.cpp

```
LONG WINAPI MainWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) {
  int key;
  switch( uMsg ) {
      // ...
      case WM_KEYDOWN:
          // ...
          Sys_QueEvent( SE_KEY, key, true, 0, NULL, 0 );
          break;

      case WM_SYSKEYUP:
      case WM_KEYUP:
          // ...
          Sys_QueEvent( SE_KEY, key, false, 0, NULL, 0 );
          break;
      // ...
  }
  //...
}

```

DOOM-3-BFG/neo/framework/EventLoop.cpp

```
void idEventLoop::ProcessEvent( sysEvent_t ev ) {
  // track key up / down states
  if ( ev.evType == SE_KEY ) {
      idKeyInput::PreliminaryKeyEvent( ev.evValue, ( ev.evValue2 != 0 ) );
  }
  // ...
}

```

DOOM-3-BFG/neo/framework/KeyInput.cpp

```
void idKeyInput::PreliminaryKeyEvent( int keynum, bool down ) {
  keys[keynum].down = down;
}

```

I then started asking myself, what happens if a frame might take longer and the key down and up events happen in the same frame? Because that actually means that these events compete each other e.g. cancel each other out. How can this situation be handled or is this scenario uncommon?

# Answer
"What happens" depends entirely on how you process the keyboard event queue you're producing.

If, during the processing of the queue, you dispatch handling for both the key down and the key up event, nothing interesting happens: the things you do on key-down and on key-up still happen normally, they just happen with less of a delay between them.

If you instead process the queue once a frame and resolve it into a "current keyboard state", then the key state will probably, as you note, "cancel out" resulting in the key state showing "not pressed." Chances are, however, if all you're doing with the queue is turning it into a current state you're wasting your time (you could use the APIs that feed the queue to do that directly with no loss of functionality).

If, however, you're using the using the queue to get a higher-level keyboard state for the frame, one that for example distinguishes between a key being held down versus tapped, for example, you'll want be tracking event times in the queue so you know how long it was between key down and key up. If it was short enough, consider that a key "tap" and dispatch accordingly. If it was longer, maybe consider it "held" for the purposes of the frame.

If you just doing the second thing and want to avoid losing the key state for events that occur in a single frame, tracking the down/up time can let you do that as well.
> 1 votes

---
Tags: game-loop, input, events, keyboard
---


# Question
Title: How to avoid mouse click over the trigger object?
I'm detecting mouse clicks if the click is happening over the collider but I don't want to fire mouse clicks if it is on the trigger object. How to I do this? Any suggestions?

# Answer
How to detect clicks on object? . This is a question I had asked. The proper way to detect mouse clicks is to use RayCasting, RayCast2D for 2D. While Raycasting, you can specify layermask, which let's you ignore objects which you want to ignore.

The second answer on the aforementioned question provides a solution for 2D.
> 0 votes

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


# Question
Title: Unity2D 5 - Flickering sprites on Android
So the game had been working fine for a few days on Android phone without any issues. Today, after adding some scripts and tweaking the game a little bit (tweaks which have nothing to do with the sprites and the issue itself), the game assets/sprites started on flicker. On PC, they looked fine, but once ported to Android as a developer build, they started to flicker constantly, even after restart.

I decided to go in Player Settings and played with some check marks but nothing seemed to help.

Following are my current Player Settings :

Any help would be appreciated.

Oh also, I have GUI in my game, can it be the problem?

# Answer
> 1 votes
Most of the time "Generate Mip Map" is the core reason behind such problems. Please switch off this option for all sprite import setting. This option is only needed for 3D objects where the engine can scale down the texture according to the z distance for performance optimization.

You can read more about Mip Maps in this link - https://en.wikipedia.org/wiki/Mipmap

---
Tags: unity, 2d, android, screen, bug
---


# Question
Title: Unity3D RigidBody adding force diagonally (x,y,0) results in two separate movements instead of one diagonal movement?
The intentions of this function are to utilize the RigidBody component from a "target" object and clear its force while applying a diagonal force in the direction upwards and away from the side they are facing. I have omitted the portion in which detects the other direction for the sake of simplicity in reading the function as I've been testing this function while the user faces the right-hand direction.
Variables:

* **target** refers to the other object currently in the scene
* **targBody** refers to the RigidBody component of the target object
**damage** refers to the current damage integer of the object.
The damage used in this instance is from the target object
**facingRight** refers to a bool in which is true whenever the current object is facing the right-hand direction.

```
    public void Damage() {
        targBody.velocity = Vector3.zero;
        if(facingRight) {
            Vector3 newVel = new Vector3(target.GetComponent().damage/16, target.GetComponent().damage/16, 0);
            targBody.AddForce(newVel, ForceMode.Impulse);
            print("Stuff");
        }
        target.GetComponent().damage+=3;
    }
```

For some reason, when I apply the force, the target object doesn't move diagonally. Instead, it moves horizontally before moving vertically; however, for some strange reason the horizontal speed is always greater than the vertical speed as it goes so fast that it nearly teleports!
I'm not sure if this error happens because of a coding problem on my part that I'm just not recognizing or if it's a problem with RigidBody in which I need to use a workaround for.
Anyone have any ideas on what can make this function work the way I want it to?

# Answer
This code in my template project runs perfect and trow object diagonally:

```
    if (Input.GetKeyDown(KeyCode.Space))
    {
        rigi.velocity = Vector3.zero;
        rigi.AddForce(new Vector3(30, 30, 0), ForceMode.Impulse);
    }

```

So, i assume some possible reasons:

1. You have wrong Vector3 newVel initialization..
2. Your if statement calls multiple times and overwrite force every frame.
3. Some where in the code another script interrups movements.
> 2 votes

---
Tags: unity, rigidbody, monodevelop
---


title: Jump a gameobject when a key is pressed

text:
# Question
Title: Jump a gameobject when a key is pressed
I am working on a platform game,When I press the space bar the object should jump and when I release the space bar it should come down.

The code I have used for jump is

```
void Update () {
    transform.Translate(Vector3.right*Time.deltaTime);
    if(Input.GetKey(KeyCode.Space))
    {
        rigidbody2D.AddForce(Vector3.up*3);
    }

    if(Input.GetKeyUp(KeyCode.Space))
       {
        rigidbody2D.AddForce(Vector3.down);
    }

}

```

But when I release the space bar the object is not coming down

# Answer
> 0 votes
To make your code work, you should set gravity to 0 in inspector and reset Rigitbody velocity to zero each time before adding force:

```
    transform.Translate(Vector3.right * Time.deltaTime/5f);
    if (Input.GetKey(KeyCode.Space))
    {
        rigidbody2D.velocity = Vector2.zero;
        rigidbody2D.AddForce(Vector3.up,ForceMode2D.Impulse);
    }

    if (Input.GetKeyUp(KeyCode.Space))
    {
        rigidbody2D.velocity = Vector2.zero;
        rigidbody2D.AddForce(Vector3.down,ForceMode2D.Impulse);
    }`

```

Or you can let the gravity do all the job. Just add force up only, and when button is not pressed gravity will move your object down.

# Answer
> 3 votes
Use `Input.GetKeyDown()` . GetKey() only returns for the first frame when you pressed the key.

# Answer
> 3 votes
You have (at least) two fundamental problems. I'm assuming here that you're not using any friction or gravity, but I'll come back to that later.

The most obvious thing is that your upward force is 3x your downward force. Basic physics tells us that, if you apply a force of *3x* to an object to start its movement, it'll take a force of *3x* in the opposite direction **just to stop it moving**. You're applying 1/3 of the force necessary to *stop* the object, which isn't nearly enough to start it moving in the opposite direction.

The other thing that's happening (as others have noted) is that you're applying an even bigger upward force than you realise, because you're using `GetKey`. `GetKey` will return true for every frame that the button is held and so, if you press the key for 1/10 of a second and you're running 60FPS, you'll apply the force 6 times. When you release the key and `GetKeyUp` is true, it's only true for a single frame. That's skewing the balance of your forces even further.

So, probably, you need to switch to using `GetKeyDown` instead of `GetKey`, and make the downward force `Vector3.down * 6`. Then, you would hopefully see a change in direction.

However: it's worth noting at this point that you're using the physics engine here to handle your jumping, and the physics engine is capable of applying gravity and friction to your object. This could make your fall much easier to implement: simply stop applying the upward force, and your object will fall back to the ground!

# Answer
> 0 votes
You're method is fine, but you're adding too little force for it to jump. Assuming you have default gravity settings, try this :

`rb.AddForce (Vector3.up*30);` and you will see the object jumping.

For clarification, rb is reference to Rigidbody2D. In my `Awake()` method, I have: `rb=GetComponent<>(Rigidbody2D);`

# Answer
> 0 votes
```
void Update () {
if (Input.GetKeyDown (KeyCode.Space)) {
        transform.Translate(Vector3.up * Time.deltaTime*100);
        //Debug.Log("Clicked");
            }
    if (Input.GetKeyUp (KeyCode.Space)) {
        //transform.position=initialposition;
        transform.Translate(Vector3.down * Time.deltaTime*100);
        Debug.Log("Clicked");
    }
    if(Input.GetKey(KeyCode.RightArrow))
    {
        transform.Translate(Vector2.right*Time.deltaTime);
    }
}

```

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


# Question
Title: Referencing individual cells of a tilemap and changing texture
I have a tilemap and am trying to proceduraly generate islands on it by changing the texture of the tiles and marking it as land ( I want to do this without texture atlas for now). How do you change the texture of an individual tile and how do you mark the tile to distinguish it from other tiles within map as land . I have tried to do this but for some reason even though I reference an individual tile all tiles are changing textures.

```
private static TiledMapTileLayer baseLayer;
private static TextureRegion landTextureReg;
private static Texture landTexture;
private static TiledMapTile landTile;

public static TiledMap generateMap(){
landTexture = new Texture(Gdx.files.internal("hex_land_trans.png"));
landTextureReg = new TextureRegion(landTexture);
TiledMap map = new TmxMapLoader().load("ocean_hex_map.tmx");
baseLayer = (TiledMapTileLayer)map.getLayers().get(0);
baseLayer.getCell(1, 1).getTile().setTextureRegion(landTextureReg);
return map;
}

```

# Answer
Don't change the texture region of the `TiledMapTile`, change the `TiledMapTile of the`Cell`. Changing the tile itself will as you say cause all`Cell`s that reference that`TiledMapTile\` to be updated.

```
private static TiledMapTileLayer baseLayer;
private static TextureRegion landTextureReg;
private static Texture landTexture;
private static TiledMapTile landTile;

public static TiledMap generateMap(){
    landTexture = new Texture(Gdx.files.internal("hex_land_trans.png"));
    landTextureReg = new TextureRegion(landTexture);
    TiledMap map = new TmxMapLoader().load("ocean_hex_map.tmx");
    TiledMapTileSet tileSet = map.getTileSets().getTileSet("your_tile_set");
    baseLayer = (TiledMapTileLayer)map.getLayers().get(0);

    Cell newCell = new Cell();
// Do this if the landTexture is in the tileset already but just not used for the
    // specific tile (you likely want all your tiles in one tilesheet).
    newCell.setTile(tileSet.getTile(42)); // Or whatever the ID you're trying to change to

// This would work if you want to load the tile sperately as you seem to do right now
StaticTiledMapTile myTile = new StaticTiledMapTile(landTextureReg);
    newCell.setTile(myTile);

    // Set the cell at the coordinates you want to affect to a new tile, this won't change all the tile, just this cell
baseLayer.setCell(1, 1, newCell);
    return map;

```

}
> 0 votes

---
Tags: java, libgdx, tilemap
---


# Question
Title: Why does my Unity animator state "finish" before the visible motion does?
***Example:***

The TopAppearing motion - boost the alpha of the sprite from 0 to 1 for total of 2 seconds:

After TopAppearing state has been finished:

The TopAppearing's transition settings:

##

**Question:**

* Why is the Top's sprite alpha 235 after the TopAppearing animatior state has been finished?

# Answer
> 1 votes
This is an official bug in Unity Mecanim , similar problem posted on the unity forum http://forum.unity3d.com/threads/exit-time-of-1-but-animation-exits-before-finishing-full-example-included.319205/ . They have said that it will be fixed in Unity 5.2 , I currently have Unity 5.1 so can't confirm.

A quick and dirty fix in your case will be to change the "Transition Duration (%)" to 0.75

---
Tags: unity, animation, state
---


# Question
Title: Separating Axis Theorem - Calculate Normals from Points in 3D
So while researching for a method to detect collisions in a 3D space between (arbitrary rotated) boxes, I stumbled upon this excellent question with great resources for my further research and great answers: How many and which axes to use for 3D OBB collision with SAT

I now managed to implement nearly everything in C++, and I understand why I have to check all 15 axis and why they are important. Yet I don't understand, how to calculate a0, a1, a2, b0, b1 and b2 (the normals of A and B). Since I only have cuboids for collision detection, I would rather use normals instead of the edges. It does seem to be easier.

To be more precise: First of all, my data structure to save a OBB is a loose collection of 8 vertices of the cuboid **1\]**. I understand, how to calculate a normal mathematically. I just calculate the cross product of two edges... But I don't know which two edges to choose. If I look at a face of the cubiod, I have 4 edges I could use to calculate the normal for that face. Another problem is, that using the above mentioned data structure, I can't tell whether two vertices belong to one face.

*So what can I do to get the 3 normals of a cuboid programmatically?*

*Do I have to expand my data structure, or can the missing information be derived somehow in a easy way?*

**1\]** Example for a cuboid in my data structure (represented in JSON, with (x,y,z) being a point in double^3):

\[(0,0,0), (0,1,0), (1,0,1), (1,1,1), (0,1,1), (1,1,0), (1,0,0), (0,0,1)\]

# Answer
> 2 votes
I now managed to solve the problem by myself. I changed my data structure, so that the normals are saved separately. When initializing the cuboid, I know what vertices belong to which surface. I then just take three vertices (namely p\_1, p\_2, p\_3) of one surface (for example the surface which faces to positive x). The three vertices form a triangle on the surface. Now let p\_2 be the vertex which is at the right angle of the triangle. Then I proceed to calculate the edges with:

e\_1 = p\_1 - p\_2

e\_2 = p\_3 - p\_2

Now the normal can be calculated with n\_x = e\_1 x e\_2 (x = cross product)

The normals n\_y and n\_z can be calculated accordingly. I then just save the normals in the data structure and use them later when the collision detection begins.

I think that it would have been to complicated to calculate the normals with a loose collection of points, since the cuboids could have an arbitrary rotation. Thats why I rather changed the data structure.

Technically, this doesn't answer the whole question, since I didn't manage to calculate the normal by just using the collection of points where I don't know which point belongs to which surface, but I spent a lot of time and I think that it is not efficiently possible, though I cannot prove this statement.

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


# Question
Title: How should I use Monte Carlo method to simulate some police cars that keep patroling in a tile based map?
I have a tile map (isometric) and I have some police cars that they patrol all the time on the map, there is some building and other cars in map too so they are considered as constraints in my shortest path algorithm (below).

I use to randomly select some target for each police car and use A\* algorithm to find the path to the randomly selected destination tile and this cycles over and over. because cars should move all the time! (except those that gamer should control)

The problem is police cars routes are correlated and they do not just traverse the area *randomly*, for instance, they do not usually cover a same area or they do not repeat their own route so my implementation based on some random destination point wasn’t a good idea and the result was not satisfying. Take a look at the following picture, it shows how randomly selecting the destinations worked for me, obviously, it is a dumb patroling for sure, even a cockroache could do better!

Suddenly, I remembered Monte Carlo Method and I thought it would solve my problem, because it exactly does what I wanted to do, However may be I should use Zobrist Hashing since it is tile base in nature. Does anyone has any idea how should I use this kind of methods?

# Question in Brief :

How can I use Zobrist Hashing or Monte Carlo method to set destinations points for my patroling car (like police car)? If anyone knows another way to implement a patrolling method, he/she is very welcome to post an answer, I am not sure if Zobrist Hashing is the best and worth to implement.

---First Edit (added following paragraph) :

I need to distribute the cars and their destination points in a homogeneous manner. Every kind of solution that get me close to a good pattern could be my answer, of course there is a lot of methods to do so, but I dont have any clue.

# Answer
> 5 votes
As a former police officer I can offer some insight into how it really works, which might help refine your process.

Divide your area up into grids and assign a car to patrol in that area, the areas may overlap a bit but the aim is to ensure a geographic spread. This reduces the problem that Alex's graphic can show - that you get two cars essentially following each other around. You often see this problem in Sim City type games (for some reason garbage trucks spring to mind).

Within that area you can have a mix of total randomness. You won't nescessarily visit every street as a police officer. You aren't even necessarily looking for efficiency with A\*. What you could do is identify "hot" areas of the graph of streets and emphasise travelling over them. If you weighted streets for crime then something like a Kruskal's algorithm could be used.

If you want to add a bit more realism then occasionally generate "calls" which then would use A\* to travel to a location for the car. You could even grade the calls to occasionally pull neighbouring cars out of their areas for serious ones, and then have them head back once the call is completed. Add in a "busy" state for cars, perhaps with a distance / severity ratio to see if they drop what they are doing to answer a call.

Depends how far you want to take things. But in general you're not wanting true randomness, it won't look random.

# Answer
> 4 votes
How would a real police patrol a neighbourhood?

Presumably they would go to the "hottest" spots? Or the closest spot that they did not visited for some time?

I've tried something with a "dirt map" because criminals do dirty business. Each frame, each spot get "dirtier".

Currently in my test the patrol car goes to an intersection that has the most "dirt" combined with the shortest distance. Once the destination selected, it flags the destination so that no one else go there (you don't want all the police cars go patrol at the same sport at the same time).

Is this way to go appropriate? Maybe.

But maybe not. Maybe "theoretically" it is a good approach, but "realistic" games would be boring so it might not answer well to the "fun" need.

So what I suggest would be to clearly decouple your "find where to go" from your "go there" algorithm so that you could experiment easily.

From what I understand, the Monte Carlo algorithm is more related to statistical stuff, and your need has nothing much to do with statistics. It has too be based on a *need*.

---
Tags: path-finding, tilemap, spritekit
---


# Question
Title: How can I save an XNA texture as a PNG file?
I have a `Color[,]` variable and I already know how to convert it to a `Texture2D`. How do I then save it as `.png` image?

# Answer
> 3 votes
As specified in the doc

```
public void SaveAsPng (
         Stream stream,
         int width,
         int height
)

```

Did you try:

```
// myTexture = something
Stream stream = File.Create("file.png");
myTexture.SaveAsPng( stream, myTexture.Width, myTexture.Height );
stream.Dispose();
myTexture.Dispose();

```

---
Tags: xna, png
---


# Question
Title: Should I create an MMORTS game with server side coding?
I have gone through many articles on the internet and got to a final conclusion that their is **almost no way to protect the game** (it can be hacked or its code can be extracted from its APK) and should write **more server side code than client side code**.

But i also know that the only consequence i will face is that server would have to handle 2 times more of data.

And i wanted to ask you that if i should write **server side code** or **client side code** for an **MMORTS game** (Massively Multiplayer Online Real Time Strategy)?

# Answer
Any moderately popular multiplayer game will be targeted by hobbyist cheat developers who just want to exploit it for fun. But when you also add an incentive to cheat in form of price money, you are practically paying people to hack your game. It is a literal job offer to professional cheat developers.

When you want to prevent cheating, you need to calculate all game mechanics which influence victory or defeat on the server and not trust any results from the client.

When your RTS implements some fog-of-war mechanic, you also need to manage which information you send to the clients. Do not send any information over the network which is not supposed to be known to the receiver.

When you do this well, the only cheating you still need to be afraid of is automation, which can only be caught through heuristics.
> 1 votes

# Answer
*Foreword: I'n not an expert about MMOanything or games in general, but I have a decent grasp on security and I wrote more than a single client/server app. Also being an avid gamer kind of helps.*

Your conclusion about the inability to protect your game is essentially correct, at least if you expect it to be 100% cheat free: whatever logic you delegate to the client has a *chance* to be bent by a very determined player (and if money is involved, odds are you'll find some...), whether because you are *trusting* the client (eugh...) or due some glitch in the validation code you might use if you don't.

You could in principle make a game **completely** cheat free by delegating almost everything on the server side, and turn the app into a plain graphical interface that just shows the battle outcomes, and accepts inputs (with heavy validation too...).

Point is, while this approach is quite easy for gambling and very slow paced games (board games, for instance), it quickly becomes unpractical for all others, especially when visual delay is important (think about bullets, for instance), and unless you greatly simplify the RTS mechanics of your game, odds are this approach will not be suitable for you.

So this is what you *can do* to make your game reasonably cheat free: if your players compete against each other in a way that *it's disadvantageous for all players to cheat at once in a same game* (for instance because they gain nothing by favouring a player over another, or because the pot comes equally from all player funds) you can make each client validate the data coming from the others.

I'll make a simple example: suppose you delegate all bullets physics to the clients (a reasonable assumption), you can make sure that each client keeps tabs on the others or a subset of the other clients (as a full check would scale like O(N^2), even though reducing the checks would greatly reduce the security of the system as a whole).

As soon as a client detects someone firing at a rate not allowed by it's level or by the game rules in general, or some bullet reaching destination faster than expected, it will rise a red flag by the server and mark the whole game as invalid.

At this point the game can be cancelled (no money paid), and the offending player can be marked as a potential cheater (if it's the first offence) or banned, if he has been repeatedly marked (and *some external check verify his fault*, otherwise malicious players could use your own system to ban first class players... See how tricky this thing is? :) ).

Mind that this is a very basic example, with a very basic response from the system (which in turn might allow cheating by abusing the rules. A player might use this to cancel a limited number of unfavorables games to get a better shot, or just for griefing).

The topic is very complex, and not being an expert I'll stop here, I still hope to have gave you an idea about what expects you if go ahead

Hope this helps
> 4 votes

# Answer
You need to write both, probably. Some games leverage existing applications (MUDs for instance can use telnet) however odds are you are going to want your own client so that things are presented in a certain manner and the user can interact in a certain manner -- user experience, etc.

One form of cheating is to alter the game state in a manner that is not allowed. Because the client is entirely in user land you cannot trust input from it. This means your server needs to ensure the game state integrity. There are a number of techniques based on your game and requirements.

Another form of what is considered "cheating" in some games is botting (automated playing). This generally requires work on the client side of things such as memory scanning and other neat stuff, read up on VAC and Warden for client side techniques.
> 1 votes

---
Tags: php, mysql, mmorts
---


# Question
Title: Dynamic Hills like Contre Jour in Cocos2d
I'm interested in maps/environments which are flexible and change at runtime, such as those in Contre Jour.

I have looked for a long time to find out how to make this effect, but I couldn't find an answer. The closest I found was maybe something like this using springs to deform meshes.

Are there better methods for implementing this feature?

# Answer
It looks like it is probably based on curves - like maybe piecewise Bezier curves, or maybe B-splines.

Internally in the code they could also be using hermite splines, catmul-rom splines or some other variant but without seeing the code its nearly impossible to tell what specific curve is being used since many of the above are visually equivalent, but are calculated differently!

Anyways, curves are a deep topic, but here's a nice basic introduction to Bezier curves: http://blog.demofox.org/2014/03/04/bezier-curves/
> 1 votes

# Answer
I do not know how it is done there nor can you ask that specifically unless you contact the creator of that demo. What you can do is use a static body for the floor in it's present (current) state. Then use something similar to the bridge demo here (tap arrow key to the right -\> three times): http://www.jangaroo.net/files/examples/flash/box2d/

When you release the bridge here you'll need to create a static surface where the bridge was. Also, you may need to create the flexible bridge with the correct constraints when the user clicks the mouse.

One last thing is that it appears the surface is being pulled from multiple points. Not just the one where the user clicks but also a couple if nearby ones.
> 0 votes

# Answer
One approach is to take the coordinates of the users click in game world and interpolate the points on either side to alter the terrain. The result are going to be determined by your method of interpolation. For instance a linear interpolation will result in triangle forming.

https://en.wikipedia.org/wiki/Interpolation
> 0 votes

---
Tags: box2d, cocos2d-iphone, cocos2d
---


# Question
Title: How is persistence managed by browser games?
I was wondering,

when you play browser games you never seem to witness a page refresh, even if there is data being stored on the server. So how are databases handled by browser games.

In my opinion there are several possible scenarios:

1. Data is being modified during your absence. Let's say in FarmVille your plants will grow while you are not using the application. So is this data being constantly updated on the server or does the application calculate everything that might have happened in a fast forward when you launch it?
2. Let's say you are currently playing in the browser and you completed a mission and get a coin reward or something. Is this data-update instantly written to a database or is it somehow stored in some kind of session tracker (cookies?) and stored on the server once you leave the application?

If it is written to the server instantly how is this done without a page refresh? I mean if there is some kind of client/server communication there must be a page refresh right?

If the data is send to the server once you leave the application, how to handle a case where the user simply kills the browser process by simply closing it? Can this scenario be catched by code so the data can still be written?

I read about several options to use JavaScript for database communication but I guess this is not an option, security, right? Wikipedia says that this kind of games do rely on server-side code but how exactly is this accomplished?

In case this matters, my approach for a browser game would be a JavaScript application with a minimum of client/server communication.

# Answer
You can store the players progress either on the server or on the client.

When you are developing a single-player game where cheaters are only destroying their own game experience and not that of other players, storing the whole gamestate in JavaScript localstorage is a perfectly valid approach. Anything you store in localstorage is stored by the web browser, which means the application can retrieve it without having to contact the server at all. Caveats are that you can not share the game progress between browsers that way and that the game state is on the users machine, so they can hack it when they want to.

On a multiplayer game you likely want to store the users game state on the server to prevent the player from tampering with it. The communication between browser and client can be implemented by having the client call a webservice with XmlHttpRequest or by using web sockets. Nether technique requires a page refresh. When the user kills the browser window, you can not make sure that you get any further updates from it, so you should send state changes to the server as soon as possible.

Regarding storing the game states in a server-sided database: Usually you have the web browser communicate with a server-sided application and that server-sided application communicate with the backend database. Letting the users web browser access the database directly is dangerous because most database systems do not have permission handling systems which are flexible enough to prevent users from tampering with data they are not supposed to tamper with. The technology options for implementing such a server-sided application are manifold: Node.js, PHP, ASP, JSP, Ruby on Rails... just to name a few of the many options.
> 1 votes

# Answer
Your actions result in information being sent to their servers. This data is persisted on their servers in a database (probably).
> -1 votes

---
Tags: browser-based-games, databases
---


# Question
Title: Getting an NRE when using delegates in Unity
I have a game where I have balls bouncing and you shoot them. Since I need a way to end the level when the player shoots all the balls I though I would create a game controller script which will register to an event from the ball script. In the awake function in the ball script I'm using this:

```
if (this.gameObject.tag == "SmallestBall") {
        if(!touchedTheRope) {
            countBalls(false);
        }
    }

```

NOTE: In this code here I'm not performing a check if(event != null) then execute - because I already know there is a problem. In the game controller script in the awake function I'm using this code:

```
UniversalBallScript.countBalls += CountBalls;

```

In the method CountBalls in game controller script I have Debug.Log to print out the number of balls. Because the small balls are being instantiated I first just performed a test where I check if the tag == "SmallestBall" and I just Debug.Log in the console, it gives me 28 small balls, but when I use the code above to call the event (if (this.gameObject.tag == "SmallestBall") etc... I get 24 balls and 4 null reference exceptions. I dont know if it has something to do with the fact that the small balls are being instantiated but I'm calling event registration in Awake and I also call that event in the Awake function, I have also tried to put this code:

```
if (this.gameObject.tag == "SmallestBall") {
        if(!touchedTheRope) {
            countBalls(false);
        }
    }

```

In OnEnable and OnDisable and its the same problem, I get 24 balls and 4 null reference exceptions. And BTW the null reference exceptions appear first and after that other 24 balls pass regularly. Does anyone have any idea?

# Answer
> 1 votes
Just a thought, could it be because the dependent script is being activated on awake as well as it's parent? Maybe try placing the initialization stuff for the child script in the start method instead.

# Answer
> 0 votes
You have no control over the order in which scripts are `Awake()`ned.

In general, a script should only reference itself during `Awake()`. Any code which relies on other game objects already being initialized should be in the `Start()` event.

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