title: How to check for mesh overlap?

text:
# Question
Title: How to check for mesh overlap?
I'm creating a level editor in Unity. I need to detect when an object is intersecting another as I don't want to allow the user to place an object when it is colliding with something else.

In the below diagam, there is a corner road piece and a tree. The dashed red line represents the mesh bounds of the road and the blue dashed line represents the mesh bounds of the tree.

My current approach is to use `Physics.OverlapBox` with `mesh.bounds`. In the diagram, visually, it is clear that the tree does not overlap the road. However, the bounds do overlap, therefore I cannot place the tree there.

Whats the best way to check if they are actually colliding in an efficient way? The level editor could potentially have thousands of objects.

EDIT: I have since tried using Physics.ComputePenetration. Primitive-primitive checks work ok, primitive-mesh collider checks work ok, but mesh collider-mesh collider checks fail. From what I understand a concave mesh collider cannot interact with another concave mesh collider. Is there a workaround for this or must I momentarily make it convex before checking overlap? I just don't want to lose the accuracy of the concave collider.

# Answer
> 1 votes
To solve this I first use `Physics.OverlapSphere` to get the nearby colldiers. Then for a more precise calculation I use Physics.ComputePenetration.

However, some of my assets utilize concave mesh colliders. As stated in the docs, a concave mesh collider cannot collide with another concave mesh collider. To fix this, I momentarily make the mesh collider convex before calling the overlap sphere.

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


# Question
Title: Set multiple render targets with OMSetRenderTargets using ComPtr<T>
I've recently decided to get rid of pretty much all of the raw pointers from my Direct3D code, and I ran into a problem with using `ComPtr<T>` template with **multiple render** targets.

Microsoft suggests using `ComPtr<T>` for D3D instead of `unique_ptr<T>` or `shared_ptr<T>`. However even their example shows how to use it with `OMSetRenderTargets`, but I couldn't really find anything how to use it when you have to bind an array of managed objects.

Here's some code of my current solution:

```
class Texture{
public:
    void Initialize(const Bitmap &bitmap){ /* ... */}

    ID3D11ShaderResourceView* GetShaderResourceView() const { return this->m_pResourceView; }
    ID3D11RenderTargetView* GetRenderTargetView() const { return this->m_pTargetView; }
    ID3D11Resource* GetTextureResource() const { return this->m_pTexture; }

    ID3D11Texture2D* GetTexture2D() const { return static_cast<ID3D11Texture2D*>(this->m_pTexture); }

private:
    ID3D11ShaderResourceView * m_pResourceView;
    ID3D11RenderTargetView * m_pTargetView;
    ID3D11Resource * m_pTexture;
}

class Renderer{
public:
    void Initialize(const Window & targetWindow){ /* ... */ }

    void SetDepthStencilView(ID3D11DepthStencilView* pDepthStencilView = nullptr){
        n = n < RENDER_TARGET_MAX ? n : RENDER_TARGET_MAX;
        if (!n && pRenderTargetView == nullptr) {
            m_renderTargetViews[0] = m_myRenderTargetView;
        } else {
            m_renderTargetViews[n] = pRenderTargetView;
        }
    }

    void SetRenderTargetView(ID3D11RenderTargetView* pRenderTargetView = nullptr, size_t n = 0){
        if (pDepthStencilview == nullptr) {
            m_depthStencilView = m_myDepthStencilView;
        }
        else {
            m_depthStencilView = pDepthStencilview;
        }
    }

    void ApplyRenderTargetView(size_t count = 1){
        m_renderTargetViewCount = count < RENDER_TARGET_MAX ? count : RENDER_TARGET_MAX;
        m_deviceContext->OMSetRenderTargets(m_renderTargetViewCount, m_renderTargetViews, m_depthStencilView);
    }

private:
    ID3D11Device* m_device; // device context, swap chain, raster state, etc ...
    ID3D11RenderTargetView* m_renderTargetViews[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT], *m_myRenderTargetView; // This is the screen as a default
    size_t m_renderTargetViewCount;
    // depth stencil buffer, etc ...
}

void some_use_case(Renderer & render){
    Texture colorMap;
    Texture normalMap;
    Texture positionMap;

    render.SetRenderTargetView(colorMap.GetRenderTargetView(), 0);
    render.SetRenderTargetView(normalMap.GetRenderTargetView(), 1);
    render.SetRenderTargetView(positionMap.GetRenderTargetView(), 2);

    // ... Render geometry
    // ... Render posteffects
}

```

Keep tracking and releasing all of the resources are way too tedious, and It's reasonable to introduce some smart pointer solution here. How could I replace the pointer definition, and how could I bind it `m_renderTargetViews` to `OMSetRenderTargets`?

# Answer
> 0 votes
For single item arrays, you can easily use `GetAddressOf()` on a `ComPtr`, but for multiple item arrays you just create it on the stack:

```
Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_renderTargetViews[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT];
Microsoft::WRL::ComPtr<ID3D1DepthStencilView> m_depthStencilView;

….

 m_deviceContext->OMSetRenderTargets(1, m_renderTargetViews[0].GetAddressOf(),
    m_depthStencilView.Get());

...

ID3D11RenderTargetView* rtv[2] = { m_renderTargetViews[0].Get(),
    m_renderTargetViews[1].Get() };
m_deviceContext->OMSetRenderTargets(__countof(rtv), rtv,
     m_depthStencilView.Get());

```

See ComPtr.

---
Tags: c++, rendering, deferred-rendering, directx10
---


# Question
Title: How to detect the border of the screen and bounce back?
```
            if (bucket.x > 0) {
                rect.x += 200 * Gdx.graphics.getDeltaTime();
            }
            if (rect.x < 0) {
                rect.x = 0;
                rect.x += 200 * Gdx.graphics.getDeltaTime();
            }

            if (rect.x > Gdx.app.getGraphics().getWidth() - 30) {
                rect.x -= 200 * Gdx.graphics.getDeltaTime();
            }

```

I have a rectangle, it has a width of 30 px, I want to move from it's x point till the edge of the screen, when it gets there I want it to go back to the other edge. it's only moving till it hits one edge and it stops.

This might be a basic question but I'm new to Libgdx and I can't find documentation. If I add a `while (true )` loop the app would stop working. Basically I want it to move infinitely along the x axis back and forth from right edge to the left edge.

I tried something like

```
`if (rect.x > 800 - 30) `

```

it won't work either and I don't like specifying the width of the device explicitly. Basically it's moving but never detecting the right edge of the screen

# Answer
> 1 votes
You need to move by a determined speed your rectangle **once** a loop.

```
// In your declaration
float speed = 15; // Pixels / second

// In your game loop
rect.x += speed * Gdx.graphics.getDeltaTime();

```

When you reach the edge of the screen, you need your speed to become the **opposite** of your current speed

```
// Check if rectangle is out of screen
if (rect.x + rect.width > screenWidth || rect.x < 0)
{
    speed = -speed;
}

```

That's it, and it works exactly the same for Y

# Answer
> 1 votes
In order to simulate physical event (bounce, collision..) you can use Box2d module from LibGDX. instead of calculating the transformation you define the object, apply a force and see it applies to your objects.

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


title: GPU Gems Chapter 1, update normal

text:
# Question
Title: GPU Gems Chapter 1, update normal
Had plans to follow GPU Gems to gain knowledge in Shaders - but my journey came to an abrupt end.

```
float Wave(x, y, t){
  float w = 2 / _Wavelength;
  float phase = _Speed * w;
  return float(_Amplitude * sin(dot(_Direction.xz, float2(x, y)) * w + t * phase);
}

...
o.vertex.y += Wave(v.vertex.x, v.vertex.z, _Time.y);

```

Offsetting the vertices was no issue, but then I met partial derivatives to solve the normal for each vertex. Starting at equation 4a to equation 7.

I assumed looking at equation 7 that one didn't have to fully grasp derivatives seeing as the last step

Equation 7: $$\sum(w\_i * D\_i \cdot x * A\_i * cos(D\_i \cdot (x, y) * w\_i + t * \varphi\_i))$$

So I tried to update the normal (well actually color, but just to visualize) using this function;

```
float3 normal(float x, float y, float t){
  float w = 2 / _Wavelength;
  float phase = _Speed * w;
  return float3(
    w * dot(_Direction.xz, float2(x, 0)) * _Amplitude * cos(dot(_Direction.xz, float2(x, y)) * w + t * phase),
    1,
    w * dot(_Direction.xz, float2(0, y)) * _Amplitude * cos(dot(_Direction.xz, float2(x, y)) * w + t * phase)
  )
}

...
o.color.xyz = normalize(normal(v.vertex.x, v.vertex.z, _Time.y));

```

It does however not seem to display what I would describe as good normals for the wave surface. So obviously I'm doing something wrong.

Ignoring the green channel here using the full code pasted below.

Would expect the colors to blend more smoothly and uniformly. Seeing I only got one wave this far.

What I am wondering is how to get the normals one would expect or if this is the expected result following the math (or rather what I could make of it) in GPU Gems.

Note: I am attemping this in Unity, so I did adapt what I assumed to be Z-up to Y-up from the GPU Gem book.

Paste to current code

GPU Gems Chapter 1

# Answer
> 0 votes
# This is expected behavior

Your shader is a *vertex* shader, which means color values are calculated *per vertex* and linearly interpolated across the triangle, giving the non-uniform result you see. If your mesh had more triangles, those inconsistencies would decrease as more points are being calculated and the harsh transitions would be smaller.

Alternatively, you could use a different shader type (eg surface shader), but as the underlying data for the slope is vertex based, you'd be taking assumptions that would end up giving the same result (but take longer to compute) or write code that *non-linearly* computes the slope across your surface-- no assumptions!--(which would take the longest to compute).

# Answer
> 0 votes
I would like to add this as a comment but I don't have enough reputation. To get something working I had to change the formula a bit:

```
float ger( vec2 uv )
{

    float ste = 1.5;
    float amp = 0.7;
    float wav = 1.9;
    float spe = 1.5;

    uv.x *= 0.1;
    uv.y *= 0.3;
    uv.x += 1.0 * amp * cos( uv.x - iTime * spe + ( uv.x + uv.y ) );
    uv.y += ste * amp * sin( uv.y - iTime * spe * 0.5 + ( uv.x + uv.y ) );

    float c = 0.3 * sin( wav * ( amp ) * ( uv.x + uv.y ) + iTime );

    return c;

}

```

By the way you can get normals from a finite differences method by feeding your function to this function, here EPS or epsilon is a really small number like 1e-4

```
vec3 nor( vec3 p )
{

    vec2 e = vec2( EPS, 0.0 );

    return normalize( vec3( map( p + e.xyy ) - map( p - e.xyy ),
                            map( p + e.yxy ) - map( p - e.yxy ),
                            map( p + e.yyx ) - map( p - e.yyx )
                           )
                     );

}

```

Here is a link to a fragment shader that does the same you are looking after: https://www.shadertoy.com/view/MtVcW1

---
Tags: unity, shaders, water, cg, shaderlab
---


# Question
Title: Unity - job system compatibility for end user?
I'm thinking about using Job system. But it requires .Net 4.x (also look like .Net 4.x will be default for Unity in 2019). It is a little hassle for me cause I'm using Visual Studio 2015, I have to download & install .Net target pack 4.7

My question is: If my game is developed with .Net 4.7.2 (so that I can use Job system), does it require the end user installing .Net 4.7.2 to play the game?

My target user is low-end PC (they may using windows 7, I see that .NET Framework 3.5.1 is included in Windows 7)

# Answer
> 1 votes
.NET is not installed onto the computer in the same way something like Java is. .NET is handled through the OS and Unity's additional functionality is given in the build.

According to your link, if Windows 7 is a key part of your demographic, you will lose some functionality that is in .NET 4.x that isn't in .NET Standard 2.0. While the job system will require 4.x, Unity's policy is to try and build as much of their game on .NET Standard as possible, to avoid situations like this. There will likely be sections of the job system you can use and others you can't on Windows 7. If you want to use the job system, you will need to research which parts of the game are built on 4.x and use SystemInfo.operatingSystem or similar to create special code for the OS not built on .NET 4.x

https://docs.unity3d.com/Manual/dotnetProfileSupport.html

---
Tags: unity, .net
---


# Question
Title: Unity3D Build Configuration for Deployment/ Publish
Is there the option within Unity3D to specify build configurations?

My goal is relatively simple - when building for mobile stores (Play Store/ App Store) I want to make sure my app is pointing to the production services, rather than the test one I use in the editor/ testing on devices.

It's controlled by a field on a `MonoBehaviour` currently, but we I need to remember to flip it from `Test` to `Production` before doing a build and publish.

# Answer
Unity's build system is very scriptable, would have a look at their Build Player Pipeline docs, and BuildPipeline.BuildPlayer

You can use the sample code the provide as a base for creating menu items you select that initiate builds with a specific configurations. I would use this in conjunction with Scripting Define Symbols that to define DEV\_BUILD or PRODUCTION\_BUILD so you can use preprocessor checks wherever they're needed.

For example, this would create a menu item for initiating a Development iOS build -- could set a method for each platform / target:

```
public class MyBuildController
{
    [MenuItem("Build/iOS Dev")]
    public static void BuildiOSDev()
    {
        // setup basic build options (scenes, platform, target directory)
        BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
        buildPlayerOptions.scenes = new[] { "Assets/Scene1.unity", "Assets/Scene2.unity" };
        buildPlayerOptions.locationPathName = "iOSBuild";
        buildPlayerOptions.target = BuildTarget.iOS;
        buildPlayerOptions.options = BuildOptions.None;

        // set scripting define symbols so can use conditional compilation for things that target Dev / Production
        PlayerSettings.SetScriptingDefineSymbolsForGroup( BuildTargetGroup.iOS, "DEV_BUILD" );

        // start build
        BuildPipeline.BuildPlayer(buildPlayerOptions);
    }
}

```

Your code can then use conditional compilation to include or exclude code that should run when targeting a dev build:

```
#if DEV_BUILD
Debug.Log( "Hi from Dev Build" );
#endif

```
> 1 votes

# Answer
I believe this article might have some answers for you https://docs.unity3d.com/Manual/PlatformDependentCompilation.html

Simply check what platform you're on and set the production service accordingly.
Works the same in both C# and JavaScript.

```
var envi = test

#if UNITY_IOS
  envi = ios
#elif UNITY_ANDROID
  envi = android
#endif

```

You can also make a development build (checkmark in the build menu) and use the `Debug.isDebugBuild` to check if the current build is a development build
https://docs.unity3d.com/ScriptReference/Debug-isDebugBuild.html

```
var envi = prod
if (Debug.isDebugBuild) {
  envi = test
}

```
> 1 votes

---
Tags: unity, mobile, publishing, appstore, build-process
---


# Question
Title: What makes a game a game vs something else like a puzzle or a toy?
Famously the Sims and similar games have been described by some designers as Toys and not "really" games.

I'm curious if there is a good answer to what makes something a game.

For example many companies sell Sudoku games - EA has an iPhone one, IronSudoku offers a great web based one, and there are countless others on most platforms.

Many newspapers publish Sudoku puzzles in their print editions and often online.

What differentiates a game from a puzzle? (or are all Sudoku "games" misnamed?)

I'm not convinced there is a simple or easy answer - but I'd love to be proven wrong. I've seen some definitions and emphasize "rules" as core to something being a game (vs. "real life") but puzzles have rules as well - as do many other things.

I'm open to answers that either focus only on computer games (on any platform) or which expand to include games and gameplay across many platforms. Here to I'm not fully convinced the lines are clear - is a "game" of D&D played over a virtual tabletop with computer dice rollers, video & audio chat a computer game or something else? (I'd lean towards something else - but where do you draw that line?)

# Answer
Previous posters have pretty well nailed down the difference between a "toy" and a "puzzle or game"; puzzles and games have a goal, whereas toys are just meant to be played with until you're sick of it.

I would define the difference between a "game" and a "puzzle" as the element of competition. In a game, you're competing *against* something: another player, an AI, time pressure, &c. Essentially, you might *lose* a game through the action of another agent, whereas with a puzzle the only way you fail to win is by giving up.

This definition automatically implies that competitive puzzle-solving becomes a game, which makes sense to me. Also, puzzle-solving against a countdown timer becomes a game, which is again fine with me.

Stated another way, my distinctions among these three terms are their ending conditions.

* toy: give up
* puzzle: win OR give up
* game: win OR lose OR give up before completion

Note that altering your perspective can move a particular artifact among these categories. Generally, expanding your time scale will tend to move an artifact up the chart. For example, each life in Portal is clearly a game; either you beat the level, or GlaDOS kills you. However, Portal as a whole is more of a puzzle, since in the end you WILL either figure out the way to beat the level, or you'll give up; GlaDOS never permanently prevents you from trying again. Completing a shelter before the monsters get you in Minecraft is a game; eventually completing your shelter, possibly with many respawns, so that you'll be safe from monsters in the future is a puzzle; Minecraft as a whole is clearly a toy (it has no built-in permanent end condition).

This classification isn't perfect, of course. Dwarf Fortress is an interesting example. As a game, your objective on a single embark is presumably to create a fortress that can... something. Hmm. As a toy, the possibilities are limitless; I've seen a 4-function calculator implemented in DF (yes, this is ~~insane~~ awesome). The problem with my classification is that any given DF fortress clearly has a *lose* condition, or you can stop playing (give up), but it has no obvious win condition. You can set your own win condition, which clearly makes it a game, but without doing so it doesn't really fall into any of these possibilities. Possibly I need a 4th category for "toys that menace with spikes of evil" to fit a single DF fortress into.

EDIT: I think Joe Wreschnig nailed it in the comments. The essential difference between a game and a puzzle is that a game can be lost, whether through competition, a timer, or whatever. I was kind of working toward this but couldn't quite articulate it. Thanks Joe!
> 17 votes

# Answer
A toy is an instrument with which you play.

A game is a system of rules for structured play.

A puzzle is a type of game where completion results from discovering a hidden solution.

Obviously the "computer game industry" and most of its customers calls any sort of software entertainment product a game, and thus it is one. However, if you choose to be more specific, the definitions above can help.

(Yes, these are a bit vague and can overlap. Most things in life cannot be clearly segregated into one pile or another. If I show you something red you'll agree it's red, and if I show you something orange you'll agree it's orange, but there are infinite shades in between.)
> 7 votes

# Answer
A discussion on the B&CGSE meta site over what is on-topic proposed a distinction that I like:

> A single-player activity with a goal and legal moves is a game, as opposed to a puzzle, if it also possesses a clear losing condition; that is, a game-state under which the goal can no longer be achieved.

So sudoku is a puzzle but not a game - you can't lose sudoku, only give up before solving it.

Klondike solitaire is a game, not a puzzle - even though there's no competition, you can lose it, when you can't make any more moves.

In Minecraft, The Sims, D&D, and so on, losing/winning is a more analog spectrum. But getting your work blown up by a creeper, having your Sims die alone and miserable, or getting killed before finding the artifact are still clear cases of loss, I think. Winning, on the other hand, is more about personal goals - I built that thing, I reached level 20, etc.
> 5 votes

# Answer
There are two very different questions here.

All puzzles are games to some extent. Not all games are puzzles. Calling Sudoku a "game" or a "puzzle" doesn't seem to make a difference to me, and I don't think it's a very interesting question. Unfortunately it seems to be the bulk of your question. Maybe there's an argument that a specific instance of a sudoku board is a "puzzle" whereas the sum total of the rules and the concept of sudoku is the "game".

What makes a game a "toy" is a bit more interesting to me, if only because some of the iconic games of recent times have very toy-like qualities. Minecraft is a toy. So's The Sims. So's Garry's Mod.

Toy-type games are typically heavy on some kind of emergent behavior. Often times it's physics related, sometime's it's AI related, but there's a pretty common theme of a lot of user direction. The idea is that you're not trying to hit some specific game-designer-given goal, but instead you're put in an environment with certain rules and playing around with those rules is what gives you your enjoyment.
> 4 votes

# Answer
I think this can be rather simple or rather complex.

* You don't really 'play' a toy, but you can play *with* a toy. Pretty similar for the sims. You can make situations that are games, but it is more open-ended.
* Puzzles are totally goal-driven. To 'win' you must solve it. Toys on the other hand have more of an intended use than a goal and you typically can't win at a toy. Sometimes a game can be a set of puzzles that tie coherently together (like chess) but it can be much more and the path to the goal is not generally a static set of state changes.
* Not always, but games are usually *designed* to entertain or otherwise engage players. Not to say other models do not also do this... This point is tough for me to describe but it is at least partly obvious. All three examples can be fun..differently.
* It may be possible to say that all games are puzzles in that they all rely on some degree of problem solving, even reaction-driven games. The programing certainly makes it feel like you are setting up puzzles. I think there is a difference in there somewhere though.

Sorry that half of this is a bit vague, that's quite a brain teaser, lol :) I will try to come back to this if I can think it through a bit further.
> 0 votes

# Answer
Everyone already got bits and pieces right. This is the only difference:

Puzzles are made with an objective, a goal in mind. The "win" scenario in a puzzle involves you "cracking the code", so to speak.

Games do not have that only goal. Almost all games are competitive, so there´s that. There are points involved, various sorts of ways of solving it.

For example. A chess puzzle is a puzzle using the pieces and board of chess to achieve a certain solution. That´s what makes it more a puzzle, than a game.

But Chess itself is not a puzzle - mostly - when you play against another human being, or machine. It´s a game. Because there´s no definitive way of going about a game of chess. You can start by this side, by that side, you can bargain, you can lose pieces, etc. You can win, you can lose, and it can even be a draw, but there´s no way a chess game needs to "play out" in order for it to be solved. There´s lots of different ways to play and lots of different things that can happen, and that´s a game.

That´s the difference.
> 0 votes

# Answer
For myself, I think there's a spectrum that goes like this

**Pure Toy ------ Pure Puzzle ------ Puzzle w Limited Time ------ Pure Game**

And it follows human existential phenomenas of:

**Exploration ------ Problem-Solving ------ Competitive Problem-Solving ------ Competition**

A pure toy represents exploration. No strict goals, you just explore and do what you like. This is why people get bored with toys quickly once they figure them out and adults have no use for toy cars in the sense that a kid might (adults still can collect them which is a form of competition).

With a pure puzzle, you have a cognitively demanding goal and an unlimited amount of time to come up with a solution. When we add limited time, we're introducing a pseudo-competitive element. You can now lose, whereas before you'd be able to work on a puzzle indefinitely. This is why something like Tetris is fairly close to a game, which is the source of confusion. Especially in the case of Tetris, where you not only have a limited time, but also alter the conditions, making it harder to solve further puzzles if you mess up rather than having one rock solid grid of Minesweeper or Sudoku. Tetris, therefore, is sitting firmly between a game and a puzzle.

With pure game, the goal usually becomes simpler and the challenge shifts from a cerebral obstacle to overcoming a living system competing against you. You can lose or win to another player or an AI. So, in a game of chess, you need to move your figure over the enemy King, but another player does his best to prevent that and take your King. Instead of only you altering the conditions yourself, another player is now also altering the conditions to screw you, using a strict set of same rules. If you want to win, you need to learn a variety of strategies, you need to learn to foresee possible outcomes, and, as a result of tons of repeated games, you might hit a plateau and discover your embodied limit that you won't be able to overcome, but get much better than the majority of new players anyway and therefore get respect from the competition (as well as additional bonuses of human connections and friendships).

If you take something like Doom, which is commonly thought of as a game, under my classification it dances between Toy, Puzzle and Game depending on the difficulty and your experience with the game (and maybe participation in something like a Speed-running community). At first it's a toy with game-like elements, but when you familiarize yourself with enemy's patterns, maps and mechanics and raise the difficulty it becomes a kind of a puzzle where you have to come up with the strategy and execute it right. However, the enemies lose the allure of being actual opponents they seemed at first and become predictable robot obstacle which shifts Doom further to the left from "Pure Game".
> 0 votes

# Answer
Suppose the difference is that a game requires you to interact with another player - i.e. with a proper feedback loop, i.e. something you do will effect something they do which will then effect something you do etc.

A puzzle does not (cannot?) contain the same level of interaction, even with the puzzle setter.

The mechanism of a puzzle is therefore to work towards a solution - rather than to interact with, and try to do better than, an opponent.
> -1 votes

---
Tags: game-design, game-industry
---


# Question
Title: Unity - Joint tearing under larger force
I have a chain that is made of connected configurable joints. I used ultimate rope builder for the rope chain creating.

The problem is that when i apply a larger force to the chain, it starts to tear and chain links starts to flicker and move chaotically.

Video available here: https://youtu.be/zGOgk4Ictt0

What could be causing such a behavior ?

# Answer
> 6 votes
This is an effect of the joint-solver that tries to keep the joints together but fails to do so when big forces are applied.

This occurs frequently when a "rope" consist of a large amount of small individual elements and joints.

Things you could do to improve the behavior:

* reduce the amount of joints in your rope. Example: Create a physics-chain with only 3 or 4 segments and use a spline-interpolation to calculate positions and angles of your visual chain elements.
* Create an additional spring-joint from your character to the "ball" to ensure the ball will never be further away from the character than the actual rope length.
* Sometimes it helps to increase the mass of the rope elements.
* Increase your "Solver Iteration Count" in the physics-settings.

# Answer
> 3 votes
Exact the same problem as you. Mostly I agree with @bummzack, but not the last one: Increase your "Solver Iteration Count" in the physics-settings. If this number is too large, the problem will get worse!

If you can afford the jittery, you can set this number to 1. Then the solver never fails, but more jittery.

Moreover, here is the official way to keep stability:

> * Avoid small Joint angles of Angular Y Limit and Angular Z Limit. Depending on your setup, the minimum angles should be around 5 to 15 degrees in order to be stable. Instead of using a small angle, try setting the angle to zero. This locks the axis and provide a stable simulation.
> * Uncheck the Joint’s Enable Preprocessing property. Disabling preprocessing can help prevent Joints from separating or moving erratically if they are forced into situations where there is no possible way to satisfy the Joint constraints. This can occur if Rigidbody components connected by Joints are pulled apart by static collision geometry (for example, spawning a Ragdoll partially inside a wall).
> * Under extreme circumstances (such as spawning partially inside a wall or pushed with a large force), the joint solver is unable to keep the Rigidbody components of a Ragdoll together. This can result in stretching. To handle this, enable projection on the Joints using either ConfigurableJoint.projectionMode or CharacterJoint.enableProjection.
> * If Rigidbody components connected with Joints are jittering, open the Physics Manager (Edit \> Project Settings \> Physics) and try increasing the Default Solver Iterations value to between 10 and 20.
> * If Rigidbody components connected with Joints are not accurately responding to bounces, open the Physics Manager (Edit \> Project Settings \> Physics) and try increasing the Default Solver Velocity Iterations value to between 10 and 20.
> * Never use direct Transform access with Kinematic Rigidbody components connected by Joints to other Rigidbody components. Doing so skips the step where PhysX computes internal velocities of corresponding Rigidbody components, making the solver provide unwanted results. A common example of bad practice is using direct Transform access in 2D projects to flip characters, by altering Transform.TransformDirection on the root boon of the rig. This behaves much better if you use Rigidbody2D.MovePosition and Rigidbody2D.MoveRotation instead.
> * Avoid large differences in the masses between Rigidbody components connected by Joints. It’s okay to have one Rigidbody with twice as much mass as another, but when one mass is ten times larger than the other, the simulation can become jittery.
> * Try to avoid scaling different from 1 in the Transform containing Rigidbody or the Joint. The scaling might not be robust in all cases.
> * If Rigidbody components are overlapping when inserted into the world, and you cannot avoid the overlap, try lowering the Rigidbody.maxDepenetrationVelocity to make the Rigidbody components exit each other more smoothly.

---
Tags: unity, physics, rope-physics
---


# Question
Title: How to use the BillboardRenderer in Unity?
Since version 5 (?) Unity has a new component-type `BillboardRenderer`. Unfortunately the documentation is quite poor.

It can be added in the inspector by clicking on "Add Component -\> Misceallaneous -\> Billboard Renderer" but apparently it requires a `Billboard Asset` to do anything. There doesn't seem to be any way to create one from the Unity interface.

One of the few sentences from the equally poor documentation of BillboardAsset reads:

> **imageCount** Number of pre-baked images that can be switched when the billboard is viewed from different angles.

My newest project will have sprite/polygon mix graphics, so a component which renders a billboard with a different sprite depending on the view angle is something I could really make use of. But there doesn't seem to be any method to add such images.

So I wondered if you could post an example how this component is used.

# Answer
UPDATE (2018): There are more properties exposed since I wrote this answer. Maybe we can create it now, maybe not. Gotta research.

## You can't use it.

Here is decompiled `BillboardAsset` code:

```
using System;

namespace UnityEngine
{
    /// <summary>
    ///   <para>BillboardAsset describes how a billboard is rendered.</para>
    /// </summary>
    public sealed class BillboardAsset : Object
    {
        /// <summary>
        ///   <para>Height of the billboard that is below ground.</para>
        /// </summary>
        public float bottom
        {
            [WrapperlessIcall]
            get;
            [WrapperlessIcall]
            set;
        }

        /// <summary>
        ///   <para>Height of the billboard.</para>
        /// </summary>
        public float height
        {
            [WrapperlessIcall]
            get;
            [WrapperlessIcall]
            set;
        }

        /// <summary>
        ///   <para>Number of pre-baked images that can be switched when the billboard is viewed from different angles.</para>
        /// </summary>
        public int imageCount
        {
            [WrapperlessIcall]
            get;
        }

        /// <summary>
        ///   <para>Number of indices in the billboard mesh. The mesh is not necessarily a quad. It can be a more complex shape which fits the actual image more precisely.</para>
        /// </summary>
        public int indexCount
        {
            [WrapperlessIcall]
            get;
        }

        /// <summary>
        ///   <para>The material used for rendering.</para>
        /// </summary>
        public Material material
        {
            [WrapperlessIcall]
            get;
            [WrapperlessIcall]
            set;
        }

        /// <summary>
        ///   <para>Number of vertices in the billboard mesh. The mesh is not necessarily a quad. It can be a more complex shape which fits the actual image more precisely.</para>
        /// </summary>
        public int vertexCount
        {
            [WrapperlessIcall]
            get;
        }

        /// <summary>
        ///   <para>Width of the billboard.</para>
        /// </summary>
        public float width
        {
            [WrapperlessIcall]
            get;
            [WrapperlessIcall]
            set;
        }

        /// <summary>
        ///   <para>Constructs a new BillboardAsset.</para>
        /// </summary>
        public BillboardAsset()
        {
        }

        [WrapperlessIcall]
        internal extern void MakeMaterialProperties(MaterialPropertyBlock properties, Camera camera);

        [WrapperlessIcall]
        internal extern void MakePreviewMesh(Mesh mesh);

        [WrapperlessIcall]
        internal extern void MakeRenderMesh(Mesh mesh, float widthScale, float heightScale, float rotation);
    }
}

```

There is literally no way to set images, even by reflection. One may think: “okay, you can't do it directly, but maybe there is some kind of factory provided?”. I press **Find Usages** in decompiler and get: `BillboardAssetInspector` and `BillboardRenderer`.

Here is `BillboardRenderer`:

```
using System;

namespace UnityEngine
{
    /// <summary>
    ///   <para>Renders a billboard.</para>
    /// </summary>
    public sealed class BillboardRenderer : Renderer
    {
        /// <summary>
        ///   <para>The BillboardAsset to render.</para>
        /// </summary>
        public BillboardAsset billboard
        {
            [WrapperlessIcall]
            get;
            [WrapperlessIcall]
            set;
        }

        /// <summary>
        ///   <para>Constructor.</para>
        /// </summary>
        public BillboardRenderer()
        {
        }
    }
}

```

Wow, this class is even dumber. It's just logic-less data holder. Obviously, all work is done by `Renderer`. More precisely, by one or couple of `[WraplessIcall]`-methods in it. I won't put its code here because it's long and useless list of `[WraplessIcall]`-members.

Unlike **UnityEngine.dll** content, `BillboardAssetInspector` (that is residing in **UnityEditor.dll**) has real code in it. Again, I won't put its code here, because it's clear from its name that it's nothing more than **Inspector**, anyway.

Same situation with `BillboardAssetInspector`.

---

## Got it, it's for internal usage; but where is it used exactly?

In SpeedTree system (look at the last image in particular).

## Why does documentation explain useless stuff instead of warning against using it right away?

Probably, just copy-pasted everything from internal development documentation, improved parts that are important for newcomers and in general usage; then was too busy participating in VR hype to bother polishing such dark corners of documentation.

## What can we do about it?

Tell them that they overlooked this “dark corner” in the documentation, for example: In Unity Editor, open `Help → Report a bug...`, in `What is problem related to` choose `documentation`, etc.

## What can one use instead?

Possible options include:
> 6 votes

# Answer
To use BillboardRenderer, you need Billboard Asset, you can construct Billboard Asset with C# script. Check this post.

The Billboard Asset have content like this: Billboard.asset

```
 %YAML 1.1
 %TAG !u! tag:unity3d.com,2011:
 --- !u!226 &22600000
 BillboardAsset:
   m_ObjectHideFlags: 0
   m_CorrespondingSourceObject: {fileID: 0}
   m_PrefabInternal: {fileID: 0}
   m_Name: Billboard_Original
   serializedVersion: 2
   width: 10.350581
   bottom: -0.2622106
   height: 7.172371
   imageTexCoords:
   - {x: 0.230981, y: 0.33333302, z: 0.230981, w: -0.33333302}
   - {x: 0.230981, y: 0.66666603, z: 0.230981, w: -0.33333302}
   - {x: 0.33333302, y: 0, z: 0.33333302, w: 0.23098099}
   - {x: 0.564314, y: 0.23098099, z: 0.23098099, w: -0.33333302}
   - {x: 0.564314, y: 0.564314, z: 0.23098099, w: -0.33333403}
   - {x: 0.66666603, y: 0, z: 0.33333302, w: 0.23098099}
   - {x: 0.89764804, y: 0.23098099, z: 0.230982, w: -0.33333302}
   - {x: 0.89764804, y: 0.564314, z: 0.230982, w: -0.33333403}
   vertices:
   - {x: 0.47093, y: 0.020348798}
   - {x: 0.037790697, y: 0.498547}
   - {x: 0.037790697, y: 0.976744}
   - {x: 0.52906996, y: 0.020348798}
   - {x: 0.95930207, y: 0.498547}
   - {x: 0.95930207, y: 0.976744}
   indices: 040003000000010004000000050004000100020005000100
   material: {fileID: 2100000, guid: 6e680dda9368db5418f19388474277a2, type: 2}

```

Here is the C# code that used to generate the file above

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

     public class BillboardBaker : MonoBehaviour
     {
 #if UNITY_EDITOR
         public BillboardAsset m_outputFile;
         public Material m_material;

         [ContextMenu("Bake Billboard")]
         void BakeBillboard()
         {
             BillboardAsset billboard = new BillboardAsset();

             billboard.material = m_material;
             Vector4[] texCoords = new Vector4[8];
             ushort[] indices = new ushort[12];
             Vector2[] vertices = new Vector2[6];
             texCoords[0].Set(0.230981f, 0.33333302f, 0.230981f, -0.33333302f);
             texCoords[1].Set(0.230981f, 0.66666603f, 0.230981f,-0.33333302f);
             texCoords[2].Set(0.33333302f, 0.0f, 0.33333302f,0.23098099f);
             texCoords[3].Set(0.564314f, 0.23098099f, 0.23098099f,-0.33333302f);
             texCoords[4].Set(0.564314f, 0.564314f, 0.23098099f,-0.33333403f);
             texCoords[5].Set(0.66666603f, 0.0f, 0.33333302f,0.23098099f);
             texCoords[6].Set(0.89764804f, 0.23098099f, 0.230982f,-0.33333302f);
             texCoords[7].Set(0.89764804f, 0.564314f, 0.230982f,-0.33333403f);

             indices[0] = 4;
             indices[1] = 3;
             indices[2] = 0;
             indices[3] = 1;
             indices[4] = 4;
             indices[5] = 0;
             indices[6] = 5;
             indices[7] = 4;
             indices[8] = 1;
             indices[9] = 2;
             indices[10] = 5;
             indices[11] = 1;

             vertices[0].Set(0.47093f, 0.020348798f);
             vertices[1].Set(0.037790697f, 0.498547f);
             vertices[2].Set(0.037790697f, 0.976744f);
             vertices[3].Set(0.52906996f, 0.020348798f);
             vertices[4].Set(0.95930207f, 0.498547f);
             vertices[5].Set(0.95930207f, 0.976744f);

             billboard.SetImageTexCoords(texCoords);
             billboard.SetIndices(indices);
             billboard.SetVertices(vertices);

             billboard.width = 10.35058f;
             billboard.height = 7.172371f;
             billboard.bottom = -0.2622106f;

             if (m_outputFile != null)
             {
                 EditorUtility.CopySerialized(billboard, m_outputFile);
             }
             else
             {
                 string path;
                 path = AssetDatabase.GetAssetPath(m_material) + ".asset";
                 AssetDatabase.CreateAsset(billboard, path);
             }
         }
 #endif
     }

```

for more details, please check the post I gave in the beginning of the answer.
> 1 votes

---
Tags: unity
---


# Question
Title: Get the mesh Project Plane on Click and calculate its area
Here is the excerpt of my script which is calculating the **surface area** and **face area** of a mesh on `OnMouseDown` Event.

```
    private void OnMouseDown()
    {
         Mesh selectedMesh = this.gameObject.GetComponent<MeshFilter>().mesh;

        float surfaceArea   = CalculateSurfaceArea(selectedMesh);
        float areaFromXFace = CalculateFacingArea(selectedMesh, new Vector3(1, 0, 0));
        float areaFromYFace = CalculateFacingArea(selectedMesh, new Vector3(0, 1, 0));
        float areaFromZFace = CalculateFacingArea(selectedMesh, new Vector3(0, 0, 1));
        float areaFromClickedFace = ProjectionPlaneClickedArea(selectedMesh);

       string areas =  "\n Surface Area            : " + surfaceArea;
        areas += "\n Area From X-axis Face   : " + areaFromXFace;
        areas += "\n Area From Y-axis Face   : " + areaFromYFace;
        areas += "\n Area From Z-axis Face   : " + areaFromZFace;
        areas += "\n Area From Selected Face : " + areaFromClickedFace;
        Debug.Log("Areas :"+ areas);

     }

     float ProjectionPlaneClickedArea(Mesh selcectedMesh)
     {

        Camera c = Camera.main;
        Ray ray = c.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, 100f))
        {
             Debug.DrawRay(ray.origin, ray.direction * 100, Color.yellow);
             Debug.Log("normal :" + hit.normal);
             Debug.Log("Area from normal/direction : " + CalculateFacingArea(selcectedMesh, hit.normal));
                    return CalculateFacingArea(selcectedMesh, hit.normal);
                }
                return 0f;
       }

       float CalculateSurfaceArea(Mesh mesh)
       {
         //Limitation: Note that if your mesh has any double-sided faces or internal faces, they can bias this result.
         var triangles = mesh.triangles;
         var vertices = mesh.vertices;

         double sum = 0.0;

         for (int i = 0; i < triangles.Length; i += 3)               //iterate over the triangles of the mesh
         {
           Vector3 corner = vertices[triangles[i]];            //for each triangle, we'll compute vectors representing the two edges
          Vector3 a = vertices[triangles[i + 1]] - corner;
          Vector3 b = vertices[triangles[i + 2]] - corner;

          sum += Vector3.Cross(a, b).magnitude; //half the magnitude of the cross product of these edges gives us the area of the triangle
         }

        return (float)(sum / 2.0);
     }

     /// <summary>
     /// compute just the area of the mesh facing in a particular direction, you can try this version instead.
    /// Pass the direction you want to view the mesh from and it should compute the projected surface area of
    /// the faces facing at least partially in that direction.
   /// </summary>
    /// <param name="mesh"></param>
     /// <param name="direction"></param>
     /// <returns></returns>
      float CalculateFacingArea(Mesh mesh, Vector3 direction)
      {
          direction = direction.normalized;
          var triangles = mesh.triangles;
          var vertices = mesh.vertices;

          double sum = 0.0;

         for (int i = 0; i < triangles.Length; i += 3)    //iterate over the triangles of the mesh
         {
             //"Subtracting each 2nd & 3rd vertex" just gives the two edges of the triangle radiating from the initial corner.
             Vector3 corner  = vertices[triangles[i]];
             Vector3 a       = vertices[triangles[i + 1]] - corner;
             Vector3 b       = vertices[triangles[i + 2]] - corner;

            //The cross product divided by two gives the area of the triangle.
            //The dot product is what handles projecting this area onto the plane of interest.
            float projection = Vector3.Dot(Vector3.Cross(b, a), direction);

            if (projection > 0f)//only sum projected triangles
                 sum += projection;
                }
                return (float)(sum / 2.0);
      }

```

I am able calculate face area by `CalculateFacingArea` method it needs a mesh and direction which is working fine, as if i want to calculate the area of x direction i can use it

```
float areaFromXFace = CalculateFacingArea(selectedMesh, new Vector3(1, 0, 0));

```

**BUT** I have to provide the face/direction information dynamically which is i am doing in this function `ProjectionPlaneClickedArea` using a `raycast`. It is getting a hit point normals which i am using as a direction and passing it to the function. It is working well with some of the meshes but not with all meshes, for example below image:

As you can see if I click this object from the front then it should calculate Y Face area but it is calculating with X direction. The click point normal value is `(1.0, 0.0, 0.1)`.

While it is working fine if my clicked object axis are something like this:

In this case x is the facing are and it is working fine. I have this value of normal `(1.0, 0.0, 0.0)`.

I am neither geometry/math expert nor a modeler so I cannot identify that its Object's normal problem or it is calculation problem.

Remember I don't want to model all the objects in the same direction/axis, where i can get the direction hard-coded. I want to calculate the direction dynamically but correctly.

# Answer
You'll need to transform the normal into local coordinates before using it with the mesh.

```
float ProjectionPlaneClickedArea(Mesh selcectedMesh)
{
        Camera c = Camera.main;
        Ray ray = c.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, 100f))
        {
             Vector3 localNormal = hit.transform.InverseTransformDirection(hit.normal);
             return CalculateFacingArea(selcectedMesh, localNormal);
        }
        return 0f;
}

```
> 1 votes

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


title: How to resize a surface in Pygame?

text:
# Question
Title: How to resize a surface in Pygame?
How can I resize a `Surface` object in Pygame? Is there a way to bind a surface object into a `Rect` object, so that resizing the rect would also resize the surface (with `Rect.inflate_ip` method for an example)?

# Answer
There's no way to do this automatically, so if you want some sort of automation for the surface rescaling, you'd need to write your own wrapper class around `pygame.Rect`, that owns a rectangle, and takes in a surface, and resizes the surface when a method of the wrapper is called.

The resizing function you are looking for is `pygame.transform.scale`. Pass it a surface and the new size you want, and it will return a new surface, or place the result into an already created surface (this is faster).
> 1 votes

---
Tags: python, pygame
---


title: What is the purpose of a guild bank?

text:
# Question
Title: What is the purpose of a guild bank?
I've seen guild banks in Wow, or Dofus, and other MMO games.

In the guild I've been a part of, we mostly used the bank as storage; resources stored that end up not being used are wasted. Sometimes there is a free share policy, but there is always that one guy who will take stuff he does not really need and sells it.

This led me to wonder what is the original purpose of a guild bank, what do players like to use it for, and how can a game help them do it?

# Answer
They are usually supposed to be a feature which makes it easier for players to collaborate and work as a team by giving them a convenient way to share resources with each other.

Why players would want to do this is very game-specific. But a possible option could be to allow some members of the guild to focus on acquiring resources which are then consumed by the other players. They *could* ask the other players how much they need and then send them those resources manually through the game's trade system. But it would be more convenient if they just dump their resources into a common storage so the others can take as much as they need.

The risk of people abusing such a system for their own gain by taking more than they need and sell it to players outside of the guild for their personal profit is a social problem. Trying to find a technical solution to a social problem rarely works. The players are responsible to make sure they only recruit people they trust. But if you feel that you should add some tools for people to detect and prevent this kind of social problems, then you could try this in your game:

* Make sure that the guild members can see who took what from the guild storage and when. So when stuff keeps disappearing, they at least have the option to sanction members who abuse their privilege.
* Implement a permission system for guilds where they can decide which members get access to the guild bank. This enables guilds to restrict access for new members until they have earned their trust.
* Enhance that permission system to allow setting quotas and/or support multiple guild banks. That way guilds can decide who gets access to what kind of resources.
* If you notice that the guild bank gets used for purposes its not supposed to be used for (like a temporary buffer for overproduction the players can't store in their private storage), make sure the players have more appropriate ways to deal with that problem which are at least as cheap and convenient as abusing the guild bank.
> 3 votes

# Answer
The purpose of a guild bank (or similar shared-storage feature), is generally some combination of

* convenience for players or
* to provide an incentive to engage with the guild or equivalent social features of a game.

Where an individual game falls on those axes is largely up to the whims of the individual game design, and of course you can implement it however and for whatever reasons you want in your own game.
> 1 votes

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


title: OpenGL Textures not showing

text:
# Question
Title: OpenGL Textures not showing
So I'm currently working on a small C++ project for a school assessment and for some reason my Textures are not showing when I run the game. I don't get any compilation errors but they don't show up. I first used

```
int main()

```

only for my code but after reading up on functions I thought my code would be better if I used those. The game was working perfectly fine before I started using functions so my question is about the placement of a few parts of my code.

here is the entire code:

```
#include "raylib.h"

//Variable declaration
static int screenWidth = 800; // Set screen width.
static int screenHeight = 450; // Set Screen Height.
static int EnemyMove = 0;
static int Score = 0;
static int Lives = 5;
static int EnemySpeed = 6;

static Vector3 PlayerPosition = {336.0f, 361.0f, 0.0f}; //Define positions of all objects at the start of the game.
static Vector3 IceCreamPosition = {600.0f, 300.0f, 0.0f};
static Vector3 EnemyPosition = {75.0f, 25.0f, 0.0f};

static bool HasIce = true;
static bool IceShooting = false;
static bool HitEnemy = false;
static bool GameStarted = false;

Image Cone;
Image Ice;
Image Enemy;

Texture2D ConeText;
Texture2D IceText;
Texture2D EnemyText;

//local Function declaration
static void InitGame(void);         // Initialize game
static void UpdateGame(void);       // Update game (one frame)
static void DrawGame(void);         // Draw game (one frame)
static void UpdateDrawFrame(void);  // Update and Draw (one frame)

int main()
{
    // Initialization
    //--------------------------------------------------------------------------------------

    InitWindow(screenWidth, screenHeight, "Icecream Eater");

    InitGame();

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

    // Main game loop.
    while (!WindowShouldClose())    // Detect window close button.
    {

        UpdateDrawFrame();
    }

    // De-Initialization
    //--------------------------------------------------------------------------------------
    CloseWindow();        // Close window and OpenGL context
    //--------------------------------------------------------------------------------------

    return 0;
}

static void InitGame(void)
{
    Image Cone = LoadImage("Images/Cone.png"); //load image into CPU memory.
    Image Ice = LoadImage("Images/Ice.png");
    Image Enemy = LoadImage("Images/Enemy.png");

    Texture2D ConeText = LoadTextureFromImage(Cone);  //Convert the image into a Texture; Put in vram.
    Texture2D IceText = LoadTextureFromImage(Ice);
    Texture2D EnemyText = LoadTextureFromImage(Enemy);

    UnloadImage(Cone);
    UnloadImage(Ice);
    UnloadImage(Enemy);

    SetTargetFPS(60); //define Target Frames per second.

}

static void UpdateGame(void)
{
    if(!GameStarted && IsKeyPressed(KEY_ENTER)){
        GameStarted = true;

    }
    if(GameStarted){
        // Update
        if(HasIce){ //If player has Ice the Ice will attach to the player.
            IceCreamPosition.x = PlayerPosition.x + 12;
            IceCreamPosition.y = PlayerPosition.y - 17;

            if(IsKeyPressed(KEY_SPACE)){ //if the Space key is pressed the player goes to a shooting state.
                IceShooting = true;
                HasIce = false;
            }
        }

        if(!HasIce && IceShooting){ //if the player doesn't have Ice and Is shooting check for collision with Enemy.
            if(((EnemyPosition.x - IceCreamPosition.x < 10 && EnemyPosition.x - IceCreamPosition.x > - 40) && (EnemyPosition.y - IceCreamPosition.y > -64 && EnemyPosition.y - IceCreamPosition.y < 34))){
                HasIce = true;
                IceShooting = false;
                Score ++;
                EnemySpeed += 2;
                EnemyPosition.x = 75;
                EnemyMove = 0;
            }

        }

            // Move player
        if (IsKeyDown(KEY_RIGHT) && PlayerPosition.x < (screenWidth - 64)) PlayerPosition.x += 2.5f;
        else if (IsKeyDown(KEY_LEFT) && PlayerPosition.x > 0) PlayerPosition.x -= 2.5f;
        else if (IsKeyDown(KEY_DOWN) && PlayerPosition.y < (screenHeight - 64)) PlayerPosition.y += 2.5f;
        else if (IsKeyDown(KEY_UP) && PlayerPosition.y > 325) PlayerPosition.y -= 2.5f;

        if(IceShooting){ //Shoots ice
                IceCreamPosition.y -= 5;
        }

        { //enemy movement
            if(EnemyMove <= 540){
                EnemyPosition.x += EnemySpeed;
                EnemyMove += EnemySpeed;

            }
            else if(EnemyMove >= 540 && EnemyMove <= 1080){
                EnemyPosition.x -= EnemySpeed;
                EnemyMove += EnemySpeed;

            }
            else if(EnemyMove == 1080){
                EnemyMove = 0;

            }
        }

        if(IceCreamPosition.y < 0 || HitEnemy){ //checks if icecream it the top
            HasIce = true;
            IceShooting = false;
            Lives --;
            EnemyPosition.y += 50;
        }

        if(Lives == 0){ // ends game if player has no lives left
                CloseWindow();

        }
    }

}

static void DrawGame(void)
{
         BeginDrawing();

            ClearBackground(RAYWHITE);

        if(GameStarted){
            //draw all Textures for in game.
            DrawTexture(EnemyText, EnemyPosition.x, EnemyPosition.y, WHITE);
            DrawTexture(ConeText, PlayerPosition.x, PlayerPosition.y, WHITE);
            DrawTexture(IceText, IceCreamPosition.x, IceCreamPosition.y, WHITE);

            //draw all HUD elements.
            DrawText(FormatText("Score: %i", Score), 10, 10, 20, LIGHTGRAY);
            DrawText(FormatText("Turns: %i", Lives), 700, 10, 20, LIGHTGRAY);
        }
        else{
            //draw starting menu.
            DrawText("Stop the crazy woman", 200, 50, 20, LIGHTGRAY);
            DrawText("from eating your icecream cone.", 200, 70, 20, LIGHTGRAY);
            DrawText("Make sure she is full by", 200, 90, 20, LIGHTGRAY);
            DrawText("Feeding her scoops of ice cream.", 200, 110, 20, LIGHTGRAY);
            DrawText("Press ENTER to begin.", 200, 130, 20, LIGHTGRAY);
        }

        EndDrawing();

}

static void UpdateDrawFrame(void)
{
    UpdateGame();
    DrawGame();

}

```

my question is regarding this part of my code

```
Image Cone = LoadImage("Images/Cone.png"); //load image into CPU memory.
Image Ice = LoadImage("Images/Ice.png");
Image Enemy = LoadImage("Images/Enemy.png");

Texture2D ConeText = LoadTextureFromImage(Cone);  //Convert the image into a Texture; Put in vram.
Texture2D IceText = LoadTextureFromImage(Ice);
Texture2D EnemyText = LoadTextureFromImage(Enemy);

UnloadImage(Cone);
UnloadImage(Ice);
UnloadImage(Enemy);

```

this is used to get the textures from the computer into ram and then into vram and then remove them from ram again. LoadImage cannot be used before the initialization of initWindow

does someone know why the images are not showing up?

```
Image Cone;

```

Image Ice; Image Enemy;

Texture2D ConeText; Texture2D IceText; Texture2D EnemyText;

I placed those in the variable declaration because otherwise I get an error telling me that those variables are not declared in scope.

if someone could help me that would be greatly appreciated

# Answer
The reason for this is something called scope.

These two lines:

* `Texture2D ConeText;` (at the top of your program)
* `Texture2D ConeText = LoadTextureFromImage(Cone);` (inside your `InitGame` function)

each define a *new* `Texture2D` variable called `ConeText`.

The reason you don't get a compiler error about re-defining an identifier is that these sit in two different *scopes*.

* the first is in Global Scope. Any code in your program can use `ConeText` to refer to this variable.
* the second is in the `InitGame` function's Local Scope. That means any line of code inside `InitGame` that says `ConeText` will refer to this local version. This is called Variable Shadowing, and the local `ConeText` is said to mask the global version.

Since this variable is local to `InitGame`, any value you put there will not be available to other code after `InitGame` returns. They'll just see the global `ConeText` which has still never been populated.

The fix is simple: if you don't want to declare a new variable, don't put the variable type before the name.

```
ConeText = LoadTextureFromImage(Cone);

```

This line says "take the *exisiting* variable `ConeText` and assign a value to it" rather than declaring a new local variable with the same name.
> 1 votes

---
Tags: c++, textures
---


# Question
Title: Creating materials in modeling program vs in Unity: when to do either?
This is something I should know the answer to by now, so I'm asking to clear up the gaps in my knowledge:

As I (re)learn about shaders, specifically in relation to Unity, I see all sorts of ways to create shaders/materials from within Unity to achieve various visual effects. (using Shader Forge / Shader Graph / manually writing ShaderLab or other shader languages).

I'm also aware that you can create shaders/materials from 3D modeling programs such as 3DS Max. My questions are: When would you choose one method over the other, or could you use both in conjunction? What is a normal workflow? Does material creation in Unity offer context-specific features that are not supported by modeling programs?

# Answer
> 1 votes
If your aim is to render the object in Unity, then you'll likely want to author your materials directly in Unity, or a tool with a dedicated Unity export pipeline, to ensure the result you see in your Unity game at runtime matches what you made in your material editor.

If you use the material editor in an external program, it's highly likely that it's being rendered with a different rendering pipeline than the one used within Unity. So you might tune it until it looks perfect in your external tool, only to find it doesn't look the same when you bring it into Unity, making your iteration process longer and more error-prone.

With regard to using ShaderForge / graphs / manually writing shader code, this is largely a matter of preference and personal workflow style. Some developers find it more intuitive to work in graphs, others prefer the explicit control and speed of editing when writing code.

You might find, depending on the material effect you want to create, you might change strategies - say if a particular feature isn't exposed in the graph, you might have to resort to code to get full control. Or if you want to create a version of an effect for which you already have a great example in graph nodes, it may be faster to modify that example rather than re-implement that functionality from scratch in code.

---
Tags: unity, shaders, graphic-effects, 3dsmax, materials
---


# Question
Title: Combining several passes in shader in Unity
I am very new to shaders but can't seem to find an answer to my problem. To put it simple I have created a flag shader, which can apply texture, animates and should also react to light. The problem is now that the shader doesn't work with both texture and light reaction at the same time. It can animate and react to light.

I created two passes, one for the color, texture and animation, and another pass with it reacting to a directional light.

I have tried out different blending options, but nothing seems to be correct.

This is a picture of it currently:

This is my code so far, I apologize for its messiness in advance :

```
 // Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

Shader "Custom/FlagShader1"{ // Shader file path in inspector
    Properties{              // Properties we will be working with

        _Color("Main Color", Color) = (1,1,1,1) // Property for changing color
        _MainTex("Main Texture" , 2D) = "white" {} // The tecture we will manipulate
        _Frequency("Frequency", Float) = 1 //The frequency of the flag , which is the number of waves
        _Amplitude("Amplitude",Float) = 1  // the Amplitude of the flag, which is the depth of the waves
        _Speed("Speed", Float) = 1 //Speed property, used to control how fast the flag waves.

    }
    Subshader {
        Tags{"Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent" "LightMode" = "ForwardBase"} // "Queue" Determines the rendering order.//"IgnoreProjector" set to true, means that this object will not be affected by projectors. //"RenderType" Categorizes shaders into  several predefined groups

        Pass{ // The number of passes. We only have one pass.
            Name "Animation"

            CGPROGRAM// We go from shaderLab into CG language

            // use "vert" function as the vertex shader
            #pragma vertex vert
            // use "frag" function as the pixel (fragment) shader
            #pragma fragment frag

            //Global variables
            uniform half4 _Color;
            uniform sampler2D _MainTex;
            uniform float4 _MainTex_ST;
            uniform float _Frequency;
            uniform float _Amplitude;
            uniform float _Speed;

            // vertex shader inputs
            struct vertexInput {
                float4 vertex : POSITION;
                float4 texcoord : TEXCOORD0;
            };

            // vertex shader outputs- these go to the fragment shader
            struct vertexOutput {
                float4 pos : SV_POSITION;
                float4 texcoord : TEXCOORD0;
            };

            // vertex shader- this is where the flag is animated
            float4 vertexFlagAnim(float4 vertPos, float2 uv) {
                vertPos.y = vertPos.y + sin((uv.x - (_Time.y * _Speed))*_Frequency) * (_Amplitude* uv.x);
                //the axis we will animate(x) and it is moved with time.y
                return vertPos;
            }

            // vertex shader. Runs on each vertex of the 3D model.
            vertexOutput vert(vertexInput v) {
                vertexOutput o;
                v.vertex = vertexFlagAnim(v.vertex, v.texcoord); // The animation
                o.pos = UnityObjectToClipPos(v.vertex); //Transforms a point from object space to the camera’s clip space in homogeneous coordinates.
                o.texcoord.xy = (v.texcoord.xy *  _MainTex_ST.xy + _MainTex_ST.zw);// Changing the tiling and offset.
                return o;
            }

            half4 frag(vertexOutput i) : COLOR{
                float4 col = tex2D(_MainTex, i.texcoord) * _Color; // sample texture and return it
                return col;
            }

            ENDCG
       }
       Pass{
            Name "Light"
            Blend Off
            CGPROGRAM

            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc" //Global variables

            // vertex shader inputs
            struct vertexInput {
                float4 vertex : POSITION;
                float3 normal : NORMAL;
            };

            // vertex shader outputs- these go to the fragment shader
            struct vertexOutput {
                float4 vertex : SV_POSITION; //pos
                float3 normal : NORMAL;
            };

            // vertex shader. Runs on each vertex of the 3D model.
            vertexOutput vert(vertexInput v) {
                vertexOutput o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.normal = UnityObjectToWorldNormal(v.normal);
                return o;
            }

            fixed4 frag(vertexOutput i) : SV_Target     {
                return saturate(dot(normalize(i.normal), _WorldSpaceLightPos0));
            }

            ENDCG
       }
    }
}

```

# Answer
You should think of a single pass of a shader as a complete render of the object:

* first, the vertex shader decides where the vertices should go within the camera's projection
* then, the rasterizer/interpolator selects which pixels are covered by the mesh and what blended values of the vertex shader output each one should use
* lastly, the pixel shader decides what colour to paint each of those pixels onto the screen / frame buffer / render target

Then you're done for that rendering pass. The object has been painted into the frame.

The next pass then runs, from scratch, with no memory of what the previous one did (apart from if you sample the old render target as an input texture to read the image-so-far). All you can do on a subsequent pass is paint over this already-drawn object (or under it, using the z buffer).

What this means for this case is that your second pass can't inject an alternate lighting & shading rule into the pixels drawn by the first, or carry the wavy vertex positions from the first pass into the second one. To combine these two effects, you have to do them both in one pass.

For this case in particular, the easiest way to get Unity to render something with lighting is to use a surface shader. We can specify a vertex function to use to modify the vertex before we draw it:

```
Shader "Custom/FlagShader" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0

        // Add flag animation parameters
        _Frequency("Frequency", Float) = 1
        _Amplitude("Amplitude",Float) = 1
        _Speed("Speed", Float) = 1
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        // Add vertex:vertexMod to use the "vertexMod" function to transform vertices.
        #pragma surface surf Standard fullforwardshadows vertex:vertexMod
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
            float3 worldNormal;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;
        // Add variables for flag animation.
        uniform float _Frequency;
        uniform float _Amplitude;
        uniform float _Speed;

        UNITY_INSTANCING_BUFFER_START(Props)
        UNITY_INSTANCING_BUFFER_END(Props)

        // Modify our vertex position & normal vector for shading.
        void vertexMod(inout appdata_full v) {
            float a = _Amplitude * v.texcoord.x;
            float phase = v.texcoord.x *_Frequency - fmod(_Time.y * _Speed, 2.0f * 3.141592653589f);
            float s = sin(phase);
            float c = cos(phase);

            v.vertex.y += s * a;
            normalize(float3(c * _Frequency * a + s * _Amplitude, _Frequency, 0.0f));
        }

        // Let Unity do its normal material & light calculations from here on in.
        void surf (Input IN, inout SurfaceOutputStandard o) {
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

You'll need a little extra to get it double-sided and shadowcasting, but that's the basic idea.
> 2 votes

---
Tags: unity, fragment-shader, vertex-shader
---


# Question
Title: What should i use as a board for my game?
I'm a beginning programmer and i need to make a game. The rough idea revolves around fleets fighting in turn based battles while you control your factions resources and manpower.

The original concept was to make a set of routes which the fleet could follow. A graph of location nodes connected by route edges that looks a bit like this:

I don't know how to make a map and make set locations on it.

On that note, i'm making this is html/javascript/css. This is a school assignment.

# Answer
> 0 votes
Regardless of the programming language, the easiest way to produce a flat map is with an array. In most languages, you'd use a 2D array so you could have a grid based area although I understand from this question How can I create a two dimensional array in javascript that it is rather difficult.

Once you have your array, you can then assign a value into the array to tell the game what is there.

For example, in this 6 x 6 map:
0 0 1 1 1 0
2 0 P 1 1 0
0 3 0 1 P 0
0 0 1 1 0 2
0 1 1 1 P 0
1 1 1 1 3 0

Where 0 represents land, 1 is sea, 2 is resource type 1, 3 is resource type 2 and P is a port which you can then use as an overlay for your boats to travel back and forth or anywhere that is a 1.

---
Tags: javascript, html5, strategy, board-game, css
---


title: Custom mobile keyboard in unity

text:
# Question
Title: Custom mobile keyboard in unity
I'm trying to create a falling word typing game like z-type.

I have used the code provided here — but it's is only for keyboards:

```
public class WordInput : MonoBehaviour {

    public WordManager wordManager;

    void Update () {

        foreach (char letter in Input.inputString)
        {
            wordManager.TypeLetter(letter);
        }
    }
}

```

I want to implement this on mobiles as well. So I have created a mobile keypad using a canvas and buttons for alphabets but I'm unable to link it to words shown on the screen.

# Answer
> 1 votes
It's reading letters from `Input.inputString`. So all we have to do is provide our own alternate input source.

```
public class CustomInput : MonoBehaviour {

    string inputThisFrame = "";

    // Call this method from your on-screen buttons.
    public void Type(string text) {
        inputThisFrame += text;
    }

    // Expose text the same way Input does.
    public string inputString {
        get {
             if(inputThisFrame != "")
                 return inputThisFrame;

             // Fall back on built-in input.
             return Input.inputString;
        }
    }

    // At the end of the frame, clear the buffer
    // so we start from scratch next frame.
    void LateUpdate() {
        inputThisFrame = "";
    }
}

```

Now you can:

1. Place an instance of CustomInput in your scene
2. Wire up your on-screen buttons to report their typing to the CustomInput instance
3. Modify WordInput so it takes an instance of CustomInput and asks for its `inputString` instead of the built-in Input.

The fallback we added above ensures the regular keyboard still works, when presentz which helps with testing.

---
Tags: unity, input, mobile, keyboard
---


# Question
Title: How to add emission to texture in shader?
I want a texture to emit itself by 1, not more. In Standard Shader I enable Emission and set texture to Color and Color to 1. I don't need emission to go beyond the object, I only need the texture to shine.

My shader:

```
Shader "Mobile/My Bumped Diffuse" {
Properties{
    _MainTex("Base (RGB)", 2D) = "white" {}
    [NoScaleOffset] _BumpMap("Normalmap", 2D) = "bump" {}
    _Color("Color", Color) = (1, 1, 1, 1)
}

    SubShader{
        Tags{ "Queue" = "Transparent" "RenderType" = "Transparency" }
        LOD 250
        ZWrite Off
        Blend SrcAlpha OneMinusSrcAlpha

    CGPROGRAM
    #pragma surface surf Lambert noforwardadd alpha:fade

    sampler2D _MainTex;
    sampler2D _BumpMap;
    fixed4 _Color;
    fixed4 _Emission;

    struct Input {
        float2 uv_MainTex;
    };

    void surf(Input IN, inout SurfaceOutput o) {
        fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
        o.Albedo = c.rgb;
        o.Alpha = c.a;
        o.Normal = UnpackNormal(tex2D(_BumpMap, IN.uv_MainTex));
    }
    ENDCG
}

    FallBack "Mobile/Diffuse"

```

}

# Answer
I added:

```
_Emission("Emission", float) = 0

```

And

```
o.Emission = c.rgb * tex2D(_MainTex, IN.uv_MainTex).a * _Emission;

```

Full code:

```
Shader "Mobile/My Bumped Diffuse" {
Properties{
    _MainTex("Base (RGB)", 2D) = "white" {}
    [NoScaleOffset] _BumpMap("Normalmap", 2D) = "bump" {}
    _Color("Color", Color) = (1, 1, 1, 1)
        _Emission("Emission", float) = 0
}

    SubShader{
        Tags{ "Queue" = "Transparent" "RenderType" = "Transparency" }
        LOD 250
        ZWrite Off
        Blend SrcAlpha OneMinusSrcAlpha

    CGPROGRAM
    #pragma surface surf Lambert noforwardadd alpha:fade

    sampler2D _MainTex;
    sampler2D _BumpMap;
    fixed4 _Color;
    float _Emission;

    struct Input {
        float2 uv_MainTex;
    };

    void surf(Input IN, inout SurfaceOutput o) {
        fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
        o.Albedo = c.rgb;
        o.Alpha = c.a;
        o.Normal = UnpackNormal(tex2D(_BumpMap, IN.uv_MainTex));
        o.Emission = c.rgb * tex2D(_MainTex, IN.uv_MainTex).a * _Emission;
    }
    ENDCG
    }

        FallBack "Mobile/Diffuse"

```

}
> 0 votes

---
Tags: unity, shaders, shaderlab
---


# Question
Title: How do I know if I'm abstracting graphics APIs too tightly?
When making a renderer that supports multiple graphics APIs, you would typically want to abstract your code in some sort of low level library that is tied with some graphics API like OpenGL, Vulkan, D3D11 and so on;

They work very differently from each other, so making a good generic API becomes essential; I've read that you would typically want to use a "back-end" that implements the basic functionality for each API you want to support, and a "front-end" which is what is used by the programmer to draw stuff on the screen.

How do I know if I'm making too much of a tight abstraction?

# Answer
> 43 votes
First of all, consider if it is actually worth it to support more than one graphics API. Just using OpenGL will cover most platforms and will be "good enough" for all but the most graphically ambitious projects. Unless you work for a very large game studio which can afford to sink several thousand person-hours into implementing and testing multiple rendering backends and unless there are some DirectX or Vulcan specific features you *really* want to show off, it is usually not worth the hassle. Especially considering that you can save a lot of work by using an abstraction layer someone else created (a 3rd party library or game engine).

But let's assume that you already evaluated your options and came to the conclusion that it is both viable and worth the time to roll your own.

Then the main judge of your abstraction layer's software architecture are your front-end programmers.

* Are they able to implement the game systems they want to implement without having to wonder about any low-level details?
* Are they able to completely ignore that there is more than one graphics API?
* Would it theoretically be possible to add yet another rendering backend without changing any of the front-end code?

If so, you succeeded.

# Answer
> 5 votes
Start by identifying what you actually need out of the "wrapper" part of the API. It's generally very, very simple: you need the basic resources (buffers, shaders, textures, pipeline state) and a way to use those resources to construct a frame by submitting some draw calls.

Try to keep any high-level logic *out of* the wrapper portion of the API. If you implement a clever scene culling technique in this portion of the API, well now you are on the hook to duplicate that logic in all of the backend implementations. That's a lot of extra effort, so keep it simple. Scene management should be part of a higher-level portion of the API that *uses* the wrapper rather than being *part of* the wrapper itself.

Choose the targets you will support and understand them. It's hard to write decent wrappers for "everything," and you probably don't need to (arguably you don't *need* to write a single wrapper, either, as noted in Philipp's answer). It's almost impossible to write a decent wrapper if you don't know the APIs you're going to wrap already.

Evaluate the state of your API regularly. It should in general have a smaller surface area than the underlying wrapped APIs; if you find yourself creating one-to-one wrapper types for every D3D structure or every OpenGL function call you are probably veering off course.

Look at what work has gone before. Sokol and BGFX are APIs that provide levels of agnosticism that may be useful to you, and are relatively easy to understand (the former especially).

# Answer
> 3 votes
Another point not yet mentioned which you should consider is what your performance goals are. If your goal is to have a graphics library that will yield good performance out of a cheap hardware platform, but also be usable on a variety of platforms that are vastly more powerful but use a different API, it may make sense to design your API around whatever abstractions are used natively on the platform where performance is an issue. Even if this causes a 50% speed degradation on the more powerful platforms, it may be worth it if it allows a 20% speed improvement on the platform where performance matters most.

---
Tags: graphics-programming
---


# Question
Title: LibGDX Box2dlights - Body Shadow Problem
While playing around with the box2dlights with libGDX, I have managed to get it all up and running, but have a problem with the shadow rendering.

This is what I currently have atm:

With the lighting on:

With the lighting off:

What I want is to have the shadow be rendered so that the body is visible when the light is shone upon it, so that the platform is visible.

Here's some of my code that I use to create and render my lighting:

```
    // world lighting creation
    rayHandler = new RayHandler(physicsWorld, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    rayHandler.setBlurNum(0);
    rayHandler.setBlur(false);
    rayHandler.setAmbientLight(.05f);

    // world lighting rendering
    rayHandler.setCombinedMatrix(cameraWorld.combined.scale(PIXELS_TO_METERS / SCALE_TO_SIZE, PIXELS_TO_METERS / SCALE_TO_SIZE, 0),
            cameraWorld.position.x / PIXELS_TO_METERS * SCALE_TO_SIZE, cameraWorld.position.y / PIXELS_TO_METERS * SCALE_TO_SIZE,
            cameraWorld.viewportWidth, cameraWorld.viewportHeight);
    rayHandler.updateAndRender();

    // player torch light creation
    torchLight = new ConeLight(rayHandler, 50, Color.WHITE, 50 / SCALE_TO_SIZE, x / SCALE_TO_SIZE, y / SCALE_TO_SIZE, angle, 35);
    torchLight.setStaticLight(false);
    torchLight.setSoft(false);

```

Any thoughts?

# Answer
Thanks to this link here,

I set the softness, `torchLight.setSoftnessLength(2.5f);`

and turned on the blur, `torchLight.setBlur(true);`

which fixed it, what I wanted.
> 1 votes

---
Tags: java, libgdx, box2d, lighting, shadows
---


# Question
Title: How to smoothly move camera when the player is climbing a diagonal staircase in 2D tile-based side-scroller?
I am working on a game, which is tile-based, similar to the way Terraria works. My player is 2 x 3 and can move over one-high obstacles, but this creates a very jittery effect, since my camera currently strictly follows the player. I was thinking of either somehow implementing a smoother camera movement or overhauling the player movement itself. I would love some feedback on how one might go about fixing this.

# Answer
In the scenario you describe, there are two points that could improve the smoothness of your camera: (1) the position of the camera with respect to the player, and (2) the movement of the camera towards its target position.

# Position of the camera with respect to the player

You mention your camera is locked to the player. I assume you instantly snap your camera's center of focus to the player position. It is possible to handle this differently by having a small frame around the player, where the camera does not follow the player. As soon as the player moves beyond the frame, the camera is "pushed" back towards the player.

In your case, you mention the jitter being caused by "jumps" in the vertical player position when he climbs a one-tile ledge. You can apply the framing strategy above to the X- and Y-movement of the camera independently. If you do want to keep the player centered on screen horizontally, but want to avoid jitter due to sudden vertical movement, you can apply the strategy to the Y-axis only.

Your current camera strategy might look like this in pseudo-code:

```
// Update the player position
...

// Update the camera position
camera.x = player.x;
camera.y = player.y;

```

To apply framing, you could modify your code like this:

```
// Update the player position
...

// Update the camera position
const float camera_frame_size_hor = 48.f;
const float camera_frame_size_ver = 32.f;
camera.x = min(max(camera.x, player.x - camera_frame_size_hor), player.x + camera_frame_size_hor);
camera.y = min(max(camera.y, player.y - camera_frame_size_ver), player.y + camera_frame_size_ver);

```

In the above cas,e the camera will only follow the player when he moves more than 48 pixels away from the camera center horizontally, or more than 32 pixels away from the camera center vertically.

# Movement of the camera towards its target position

You also mention you instantly snap the camera to the player position. Many games apply a form of smoothing to the camera movement. To apply smoothing, you calculate the target camera position as before. However instead of simple setting the camera's actual position to this target position, you gradually move its position towards the target.

Currently, you might simply set your camera position directly as follows:

```
// Update the player position
...

// Update the camera position
camera.x = player.x;
camera.y = player.y;

```

You could instead apply a simple low-pass filter as follows:

```
// Update the player position
...

// Update the camera position
const int camera_smoothing = 10;
float camera_target_x = player.x;
float camera_target_y = player.y;
camera.x = ((camera.x) * (camera_smoothing - 1) + camera_target_x) / camera_smoothing;
camera.y = ((camera.y) * (camera_smoothing - 1) + camera_target_y) / camera_smoothing;

```

# Combined camera strategy

The two techniques above can be applied independently to smooth your camera movement in a more sophisticated way. Your camera code might look like this:

```
// Update the player position
...

// Update the camera position
const int camera_smoothing = 10;
const float camera_frame_size_hor = 48.f;
const float camera_frame_size_ver = 32.f;

float camera_target_x = min(max(camera.x, player.x - camera_frame_size_hor), player.x + camera_frame_size_hor);
float camera_target_y = min(max(camera.y, player.y - camera_frame_size_ver), player.y + camera_frame_size_ver);
camera.x = ((camera.x) * (camera_smoothing - 1) + camera_target_x) / camera_smoothing;
camera.y = ((camera.y) * (camera_smoothing - 1) + camera_target_y) / camera_smoothing;

```

# Reference

I would like to recommend the following excellent article which analyses various camera strategies across many games. The articles has animated graphics to illustrate all strategies. Itay Keren - Scroll Back: The Theory and Practice of Cameras in Side-Scrollers
> 2 votes

# Answer
As Jelle van Kampen mentions in his answer; this is a valuable resource: Itay Keren - Scroll Back: The Theory and Practice of Cameras in Side-Scrollers

I'll provide my implementation of a camera system as well. The code below in in C# using Monogame. The principles should translate to any language.

The camera I use is of the type ‘Camera window’ with ‘LERP Smoothing’. It meams the camera follows the player, if the player pushes the boundaries of a window inside the camera viewport:

The blue area (1) is the gameworld. This area is bigger than the part shown on the player’s screen. The yellowish area (2) is the actual viewport that is rendered to the player screen. The reddish (3) part is the ‘camera window’: the player controlled character will always be inside that part. Only when the player actually pushes the boundaries of that inside section the view will move. Imagine the character moves to the right edge- the camera gets moved until the player is back inside the reddish area and will nog move again until the player reaches the edge again.

LERP smoothing means the camera ‘lags’ a bit and moves smoothly instead of immediate.

On to some code…

```
public class Camera
{
    private Rectangle _viewPort; // The portion rendered to the screen.

    private Rectangle _bounds;   // The total game area.
    private Rectangle _trackingBounds; // The area that an object is considered 'centered'.

    private Vector2 _targetPosition; // where do we want the camera to go?
    private Vector2 _currentPosition; // where is the camera really.

    private const float BOUNDSPERCENT = 0.30f; // The amount of border used to calculate the trackingbounds.

    public Camera(int width, int height, int worldwidth, int worldheight)
    {
        _viewPort = new Rectangle(0, 0, width, height);
        _bounds = new Rectangle(0, 0, worldwidth, worldheight);
    }

}

```

This code is the base of the camera class.

If you look at the constructor the camera initializes two rectangles:

the viewport– the dimension of the camera (the yellowish rectangle in the picture above) the bounds of the gameworld, the camera needs to know the dimensions of the gameworld; so it knows not to scroll outside the actual gameworld. This is the equivalent to the blue area in the picture. The variables should speak for themselves- note the ‘\_trackingBounds’ variable is equivalent to the reddish area in the picture.

The trackingbounds are calculated in a function like this:

```
//sets when the viewport should move in relation to the preferred viewport.
private void SetTrackingBounds()
{
    _trackingBounds = new Rectangle(
        _viewPort.X + (int)(_viewPort.Width * BOUNDSPERCENT),
        _viewPort.Y + (int)(_viewPort.Height * BOUNDSPERCENT),
        (int)(_viewPort.Width * (1 - (2 * BOUNDSPERCENT))),
        (int)(_viewPort.Height * (1 - (2 * BOUNDSPERCENT)))
        );
}

```

Here we calculate the trackingbounds based on the current viewport location and the dimensions are a relative portion of the viewport size (using the const BOUNDSPERCENT).

Another function we need is to keep the camera within the boundaries of the gameworld. This function keeps the camera within the bounds:

```
private void KeepCameraWithinBounds()
{
    if (_viewPort.X < _bounds.X)
        _viewPort.X = _bounds.X;
    if (_viewPort.Y < _bounds.Y)
        _viewPort.Y = _bounds.Y;
    if (_viewPort.X + _viewPort.Width > _bounds.Width)
        _viewPort.X = _bounds.Width - _viewPort.Width;
    if (_viewPort.Y + _viewPort.Height > _bounds.Height)
        _viewPort.Y = _bounds.Height - _viewPort.Height;
}

```

It is a simple check, the code should be self explanatory.

Now we have the basic operations done, We’re going to actually track an object:

```
public void TrackObject(Vector2 objectposition)
{

    if(objectposition.X<_trackingBounds.Left)
    {
        _targetPosition.X = objectposition.X - _viewPort.Width * BOUNDSPERCENT;
    }
    if(objectposition.X>_trackingBounds.Right)
    {
        _targetPosition.X = _viewPort.X + (objectposition.X - _trackingBounds.Right);
    }
    if (objectposition.Y < _trackingBounds.Top)
    {
        _targetPosition.Y = objectposition.Y - _viewPort.Height * BOUNDSPERCENT;
    }
    if (objectposition.Y > _trackingBounds.Bottom)
    {
        _targetPosition.Y = _viewPort.Y + (objectposition.Y - _trackingBounds.Bottom);
    }
}

```

Let’s have a closer look: the function takes a Vector2 position in the gameworld. We check how the position is outside the tracking boundaries. if the position is outside the boundaries of the tracking window; the top left position of the camera rectangle is calculated that puts the object back inside that window.

The top left location is stored in a Vector2 targetposition variable. So the camera itself is not yet moved- instead we set the position we want the camera to move towards.

So far we have the functions to initialize the camera, calculate the boundaries of the tracking window and set the target position of the camera in relation of an object. Let’s put these things together and move the camera!

```
public void Update(GameTime gt)
{
    _currentPosition = Vector2.Lerp(_currentPosition, _targetPosition, 5f * (float)gt.ElapsedGameTime.TotalSeconds);

    _viewPort.X = (int)_currentPosition.X;
    _viewPort.Y = (int)_currentPosition.Y;

    KeepCameraWithinBounds();
    SetTrackingBounds();
}

```

Every frame the camera is updated. I use the Vector2.Lerp function to smooth the movement. Every frame it gets a percentage closer to the target. If the distance between the current and target position is big, the camera will move quick until the distance becomes so tiny (subpixel effectively) so the camera has reached the destination. One can play with the magic number in there (the 5f) so make the camera respond quicker or slower. The speed should depend on how fast objects in the game move, so the camera can keep up.

Then the camera viewport rectangle is moved and is checked against the bounds. Once all movement is done- the tracking window is recalculated.

The main game loop now needs to know what the camera is showing so:

```
public Rectangle View
{
    get { return _viewPort; }
}

```

The result is we have everything required to make a smooth moving, windowtracked game camera!

To use it, in the main gameloop:

```
public void Update(GameTime gameTime)
{
    //handle game logic.

    //update the camera
    _camera.Update(gameTime);
    _camera.TrackObject(_player.Position);
}

public void Draw()
{
   Rectangle viewport = _camera.View;

   //do culling or something using the viewport that is just set
   // or
   //Draw the game, using the top left-
   //   corner of the viewport to know how to position your entities.
}

```

Hope this gives some inspiration on a camera system.
> 2 votes

# Answer
Can you provide some code ?

Do you move the player in the `FixedUpdate`? and apply camera movement in the `Update` ?

You should use `FixedUpdate` for camera movement AND player movement if your movement are physic based. You should use `LateUpdate` for the camera movement AND `Update` for player movement if your movement are not physic based
> 0 votes

# Answer
You could easily implement a smoother like you suggest by filtering the
camera position in a box car averager (aka: moving average).

Store the points in a fifo queue large enough to span the time it takes to jump one stair (x2) and make the camera position be the average of those points.

When a new position arrives remove the oldest and add the new one and preform a new average calculation.
> 0 votes

---
Tags: 2d, camera, tiles, side-scroller
---


# Question
Title: How to stop all character movement when jumping against the side of a platform?
My Sprite is Moving against a platform.

I have a script and an unusual one (that's what one of the member said.) My isGrounded isn't using any rayCasting. I didn't have any problem with it but when I created a platform and jump against it:

1. My character would fall down slowly.
2. If I try to move against the platform, I would be able to move and it would appear as if the character was flying.

So question is, how can I stop all my movements, jumping everything, when I collide like this with a platform?

My Code is:

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

public class pScript : MonoBehaviour {
    public Rigidbody2D rb;
    [SerializeField]
    public Transform[] Points;
    [SerializeField]
    public float radius;
    [SerializeField]
    public LayerMask layer;
    public bool jump;
    public bool isgrounded = false;
    [SerializeField]
    public float MoveSpeed;
    [SerializeField ]
    public float jumpHigh;
    public bool facingRight;
    public Animator animator;
    public Object CallfPanel;
    public Object CallfText;
    public float Move = 8f;
    public Vector3 Dir;
    public Vector3 tart;
    // Use this for initialization
    void Start () {
        rb = GetComponent<Rigidbody2D> ();
        animator = GetComponent<Animator> ();
        CallfPanel = GameObject.Find ("Panel");
        CallfText = GameObject.Find ("Text");
    }

    // Update is called once per frame
    void Update () {
        RaycastHit hit;
        Debug.DrawRay (transform.position, Vector3.right, Color.white, Move);
        tart = new Vector3 (200, 300, transform.position.z);
        Dir = Vector3.right;
        if (jump == true) {
            if (Physics.Raycast (tart, Dir, out hit, Move)) {
                jump = false;
            }
        }

        float horizontal = Input.GetAxis ("Horizontal");
        animator.SetFloat ("speed", Mathf.Abs (horizontal));

        isgrounded = isGrounded ();
        rb.velocity = new Vector2 (horizontal * MoveSpeed, rb.velocity.y);
        if (Input.GetKeyDown (KeyCode.Space)) {
            jump = true;
        }
        if (isgrounded && jump == true) {
            isgrounded = false;
            rb.velocity = new Vector2 (0, jumpHigh);
        }
        if (isgrounded == false) {
            jump = false;
        }
        changeDirections ();
    }
    private bool isGrounded(){

        if (rb.velocity.y <= 0) {
            foreach (Transform points in Points) {
                Collider2D[] collider = Physics2D.OverlapCircleAll (points.position, radius, layer);
                for (int i = 0; i < collider.Length; i++) {
                    if (collider [i].gameObject != gameObject) {
                        return true;
                    }

                }

            }

        }return false;
    }
    public void changeDirections(){
        float horizontal = Input.GetAxis("Horizontal");
        Vector3 theScale = transform.localScale;
        if (theScale.x == 1) {
            facingRight = true;
        } else {
            facingRight = false;
        }

        if (horizontal > 0 && !facingRight || horizontal < 0 && facingRight) {
            theScale.x *= -1;
            transform.localScale = theScale;
        }
}
    public void showTextDuration(){
        float lifetime = 4.0f;
        Destroy (CallfPanel, lifetime);

}
}

```

# Answer
> 0 votes
I'm not sure about how exactly to do this in Unity rigid body physics but this is how I would do it in a conventional approach.
Create a collision detection function for four sides then replace `isGrounded` with `bool collisions[4]`, and `isGrounded()` with your new collision detection function.
Instead of what you're doing now, check for collisions after the player moves and if the character is inside of an object, eject him to the edge of that object in the direction the player came from. Make sure the character is never inside the object when the frame ends.
Also, I don't use Unity, but wouldn't it be simpler to use more conventional methods to create a platformer? Is there a specific reason you have to make it harder on yourself and use rigid body physics?

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