# Question
Title: How can I make user-friendly polar coordinate movement around a circle?
I am working on a 2D game where you land on planets with a ship and can exit the ship and walk around.

These planets are very small (think ~350 pixel radius sometimes), and are seen from the side. So you can easily see the whole planet on the screen generally.

This may be sort of confusing so here's a picture:

I am using the A and D keys to move counter-clockwise and clockwise, respectively. The problem is that if you are on the "top" of the planet (upper half), this makes sense: A moves to the left, D moves to the right. However, if you are on the "bottom" of the planet (bottom half), A moves to the right, and D moves to the left.

Any ideas on how can I make this more user-friendly?

# Answer
> 38 votes
My first suggestion would be to just stick with `A` = Counter-clockwise and `D` = Clockwise movement. It is not very confusing and is pretty much the "standard" (i.e. most common) choice when it comes to orbital movement like this.

Another way would be to change the way your game moves. Instead of moving the player when they are on a planet you could rotate the planet instead. This is also a very common choice but it can be disorienting if you have multiple planets on screen since *everything* except the player will have to rotate. If you decide to use this method it could help to only display a part of the planet to reduce the amount of moving objects your eye has to keep track of:

If you are free to use the mouse you could always use mouse clicks to move around. Clicking on a location will cause the player to move towards that point and it will automatically choose the shortest direction. Circles are "clicks" and arrows are shortest direction.

As an added bonus it's also very easy to translate to Mobile controls if you wish to publish your game as an app as well.

# Answer
> 16 votes
When the character gets out of the ship, reorient the view so the character is on top of the planet, and then move the view with the character as they walk around. This way the character is always on top with respect to the view when on a planet, so the left/right controls can stay consistent no matter where you land.

# Answer
> 11 votes
One approach (often used in third-person games with stick-based movement that also have non-static cameras) is to establish the frame of reference for movement every time the input begins (in your case, when the key is pressed) and keep that frame of movement until the input terminates (the key is released). This means the "A" key would always move the character "to the left," whatever that was -- clockwise if it's on the bottom of the circle, counter-clockwise otherwise -- until the key was released.

Unfortunately, since you're constrained to a circle, this technique will still fall apart when the character is at or near the extreme left or right extents of the circle. You can make it work simply by choosing arbitrarily which direction to go in, but the user may find it confusing. Possibly more confusing that simply sticking with the existing "A is always counterclockwise" approach you have now.

# Answer
> 10 votes
I suggest you take a look at a similar concept but then in 3d: Super mario galaxy.

https://youtu.be/\_8eJC4gIAm4?t=19m

At short movements the reference frame stays the same, the universe doesn't move, get beyond a certain threshold the universe moves along/shifts along so the reference frame is back in the middle.

You might wish to "movement blur" the universe when moving so it looks more natural and the eyes won't focus on the moving parts shifting positions.

I assume that Nintendo invested quite some research in getting the game play as smooth as possible and this is what they settled upon. I always like to look to what the bigger companies figured out, hoping they invested something in R&D for maximum comfort and playability.

# Answer
> 7 votes
Use `A`/`D` to move the character in the direction towards the leftmost / rightmost point of the planet, respectively, and `W`/`S` to move the character towards the topmost / bottommost points.

In this way, **the player is always moving the character in the same direction as the input movement** -- e.g. `D` always moves right, `S` always moves down, regardless of the character's position.

The game could either keep going in the same clock direction while the key is held down, or stop the character at the limiting point. If it stops, it doesn't seem like a big problem -- the player has a full quadrant in which to change their input if they want to keep going in the same clock direction.

Additionally, a circular `W`-`A`-`S`-`D` or `W`-`D`-`S`-`A` pattern of input results in circumnavigation of the planet, which seems fairly intuitive.

Holding down more than one key could just cause the most-recently-pressed key to take precedence, or you could use more complex behavior such as having eight limiting points.

# Answer
> 3 votes
This is one of two classic "mental model" problems suffered by a lot of games.

Every player develops a "mental model" for how game controls map onto game actions. As games have become more and more similar in their controls over time, people have begun to expect their established mental model to apply to new games, rather than developing separate models for separate games. Which would be fine, except that not every player has the same mental model of how controls should work.

For example, the other classic "mental model" problem is whether pressing up on a joystick (typically the right analog stick of a gamepad) should mean *looking up*, or whether it should mean *tilting forward* (i.e.: looking *down*). Neither model is objectively *right*, but most players only keep one of these two possible mappings in their head, and will be thrown off if a game does something different than they personally have come to expect.

Your question is exactly the same dilemma; the "mental model" issue here is whether pushing right on a control stick means "move to the character's right" (as in Resident Evil), or "move toward the right side of the screen" (as in Mario). Or in this case, "move clockwise" (as in Tempest, when using a traditional conversion from paddle to joystick controls).

Every player will have a built-in model that they're used to which they will be reluctant to change (or have difficulty changing). In any such "mental model" issue, you have three options for how to handle the issue:

1. As the developer, you pick which model is the best one for your game, and use it. Ignore the complaints of people who have trouble with your chosen model; they'll just have to adapt. And if your game is compelling enough, they will.
2. Implement both possible models, and let players choose which one they want to use.
3. Re-design the game to make sure that the mapping of controls-\>game actions remains the same, no matter which mental model someone is using.

Option 3 ("re-design the game so the mental models don't conflict with each other") in this case would mean rotating the camera with the player, so the player always appears upright on screen. That way, "right means go clockwise" and "right means go toward the right side of the screen" are always in alignment; there's no conflict any more and players won't become confused depending upon their mental model of how controls are supposed to work.

Option 2 would mean implementing both styles of control; one where pushing right takes you toward the right side of the screen, one where pushing right takes you clockwise, and having an options screen where the player can pick which control style they want to use.

Any choice here is valid; the different options just require different amounts of work and impose different constraints on your game. If it's really important to you for the player to be visible moving around on the "bottom" side of the planet, either for thematic or artistic reasons, then you won't want to use option 3, and should use 1 or 2. If not, then option 3 is probably the ideal choice.

> A minor implementation note for the "pushing the joystick to the right means moving toward the right side of the screen" control style: When implementing this control style, you should do it by mapping the joystick direction into a clockwise/anticlockwise choice, and then keep that same clockwise/anticlockwise decision until the joystick moves again, even as the player moves around to the bottom side of the planet. That is, pressing right while on top of a planet, or down while on the right side of a planet, would each start the character moving clockwise, and the character will then keep moving clockwise even around the bottom of the planet until the player moves the joystick again, even if they move to a part of the planet where that joystick direction would now be interpreted as being a different direction.
>
> This technique is often called "locking" the joystick control, and is generally used in 3D games when the camera makes a sudden rotation (which you don't want to cause the player to suddenly change direction), but can also be useful here in a 2D game, if a camera movement would otherwise make the player's unmodified inputs suddenly mean something different than they did before.

# Answer
> 2 votes
Use W/S/A/D for input (or up/down/left/right). Treat the input as an 8-way direction (including diagonals).

Then move the player in whichever valid direction (clockwise or anticlockwise) is closest to the direction that is pressed.

# Answer
> 2 votes
One option is instead of defining the association between key and direction of movement, to have:

* one key to move "forward" (in the currently selection direction)
* one key to "turn around" (switch direction)

This requires the character to have a clearly visible "direction".

Not sure that really makes much more sense than other options here, but just in case....

# Answer
> 1 votes
Down is where the gravity is. So when the player-character is on a planet, rotate the camera together with the movement of the player-character so that the character is always on top of the planet.

But while this makes navigation on the planet easier, it might disorient the player relative to other celestial objects. This is a tradeoff you need to decide on for yourself.

# Answer
> 1 votes
If you choose to use clockwise/counterclockwise movement, there are a number of things you can do to make the system easier to intuit for your players.

# Give the character prominent distinguishable directions

If the character is half blue and half red, then orientation becomes easy for players to remember. Instead of having to identify "clockwise" or "counterclockwise", the players either move in the blue direction or the red direction. If the character is always facing in one direction (preferably clockwise, so that movement is most intuitive while upright) it's even better, because English speakers (and anyone else with a left-to-right language) naturally tend to associate 'right' with 'forward', reinforcing the connection between the controls and the direction of movement.

# Never let the characters stop moving

As long as you are moving your character, it's easy to maintain what orientation your controls are in. After all, continuing to move in the direction you are moving in doesn't take any action at all, and when you want to reverse your movement, there's only one other key to choose. It's only when you start moving again after having stopped that you are faced with a choice. The longer you pause, the harder it will be to pick up again based on what you were doing before. By reducing pause frequency and pause lengths you can keep players from forgetting how to move.

# Answer
> 0 votes
There are multiple approaches to this.

1) How I would approach this would take sections of the planet: the top, left, right, and bottom sides (more if desirable). And have it so after the user presses a direction, the character will keep going that direction till they release that button. So if the character was on the left side and the user pressed up, then the character would go clock-wise till release. This way you don't have to worry about changes in the frame of reference while the character is moving, only after.

2) Another way would like how "Lovers in dangerous space-time" approach it. With a joystick, rather than have the frame of reference depending on the surface, they have it so the angle the joy-stick was the desired spot for "character" to stop at. So their frame of reference was at the center of their "planet". I say character and planet but they had modular ship parts on the outside where you determine where they go, ie which direction the thrusters are pointed to move the ship.

3) How you have it designed now. It can get a little getting use too but nothing players haven't seen before. You could edit it though so it appears the planet is rotating instead so the play is always "on top".

---
Tags: 2d, movement, user-experience
---


# Question
Title: How to implement wall-following behavior?
I am working on an action platformer and am trying to implement an enemy with simple wall-following behavior. I want the enemy to follow the boundary of whatever connected constellation of walls it is standing on, whether it's a freestanding platform or a connected room.

The enemy has a position, a velocity, a bounding rectangle, various points on the bounding rectangle (topleft, bottomright, etc.), and various points raycasted a few pixels outside the bounding rectangle (midleft\_raycast, bottom\_raycast, etc.). The walls are rectangular and have the usual attributes of a rectangle.

Currently I am implementing the wall-following behavior in the following way. If the enemy has a positive horizontal velocity, I check whether various corners intersect or don't intersect a wall. For example, if the bottomleft and bottomright no longer intersect a wall, I know the enemy has moved over a gap and his velocity needs to be adjusted for him to move downward. I realign his bottomleft corner to the wall's topright corner and change his velocity to a positive vertical velocity. I do something similar for the other cases.

Here is an illustration:

And here is my code:

```
        if self.state == "patrolling":

            # sprite travelling right
            if self.vel == vec(1, 0):
                if not tools.point_collides_any_wall(self.game, self.bottomleft) and not tools.point_collides_any_wall(self.game, self.bottomright):
                    # reposition sprite so it's touching the wall
                    self.bounding_rect.bottomleft = self.platform.rect.topright
                    # change velocity
                    self.vel = vec(0, 1)

                if tools.point_collides_any_wall(self.game, self.bottomleft) and tools.point_collides_any_wall(self.game, self.bottomright) and tools.point_collides_any_wall(self.game, self.topright):
                    # change velocity
                    self.vel = vec(0, -1)
                    # set platform
                    self.platform = [wall for wall in self.game.walls if wall.rect.collidepoint(self.midright_raycast)][0]

            # sprite travelling left
            elif self.vel == vec(-1, 0):
                if not tools.point_collides_any_wall(self.game, self.topleft) and not tools.point_collides_any_wall(self.game, self.topright):
                    # reposition sprite so it's touching the wall
                    self.bounding_rect.topright = self.platform.rect.bottomleft
                    # change velocity
                    self.vel = vec(0, -1)

                if tools.point_collides_any_wall(self.game, self.topleft) and tools.point_collides_any_wall(self.game, self.topright) and tools.point_collides_any_wall(self.game, self.bottomleft):
                    # change velocity
                    self.vel = vec(0, 1)
                    # set platform
                    self.platform = [wall for wall in self.game.walls if wall.rect.collidepoint(self.midleft_raycast)][0]

            # sprite travelling up
            elif self.vel == vec(0, -1):
                if not tools.point_collides_any_wall(self.game, self.topright) and not tools.point_collides_any_wall(self.game, self.bottomright):
                    # reposition sprite so it's touching the wall
                    self.bounding_rect.bottomright = self.platform.rect.topleft
                    # change velocity
                    self.vel = vec(1, 0)

                if tools.point_collides_any_wall(self.game, self.topleft) and tools.point_collides_any_wall(self.game, self.topright) and tools.point_collides_any_wall(self.game, self.bottomright):
                    # change velocity
                    self.vel = vec(-1, 0)
                    # set platform
                    self.platform = [wall for wall in self.game.walls if wall.rect.collidepoint(self.midtop_raycast)][0]

            # sprite travelling down
            elif self.vel == vec(0, 1):
                if not tools.point_collides_any_wall(self.game, self.topleft) and not tools.point_collides_any_wall(self.game, self.bottomleft):
                    # reposition sprite so it's touching the wall
                    self.bounding_rect.topleft = self.platform.rect.bottomright
                    # change velocity
                    self.vel = vec(-1, 0)

                if tools.point_collides_any_wall(self.game, self.topleft) and tools.point_collides_any_wall(self.game, self.bottomleft) and tools.point_collides_any_wall(self.game, self.bottomright):
                    # change velocity
                    self.vel = vec(1, 0)
                    # set platform
                    self.platform = [wall for wall in self.game.walls if wall.rect.collidepoint(self.midbottom_raycast)][0]

            self.pos = self.bounding_rect.center

```

This method works, but I can't help but think that there is a more elegant way. For example, what if I wanted the enemy to move in the opposite direction. I would need to write another chunk of (symmetric) code for this.

So my question is: **Are there other, simpler, or more general ways to implement wall-following behavior?**

# Answer
You could store your test points in a 2D array, like...

```
[0, 0]     [1, 0]

[0, 1]     [1, 1]

```

Then store two pairs: one representing the direction of movement, and one representing the direction to the nearest wall.

Using these two vectors, you can compose the indices for each corner you need to test:

```
trailingOutsideCorner.x = (movement.x - toWall.x) > 0 ? 0 : 1

trailingOutsideCorner.y = (movement.y - toWall.y) > 0 ? 0 : 1

```

This gives you the index of the rear corner against the wall you're travelling along. You can test that point for collisions, and if you don't get one, then you turn outward:

```
// move in the direction toward the wall we were following
newMovement = toWall

// our new wall is behind the direction we were going
newToWall = -movement

```

You can form a similar expression to test your leading inside corner:

```
leadingInsideCorner.x = (movement.x - toWall.x) > 0 ? 1 : 0

leadingInsideCorner.y = (movement.y - toWall.y) > 0 ? 1 : 0

```

If that has a collision, then you need to make an inside turn:

```
// move away from the wall we were on
newMovement = -toWall

// our new wall is in the direction we were travelling
newToWall = movement

```
> 1 votes

---
Tags: 2d, collision-detection, path-finding, collision-resolution, steering-behaviors
---


# Question
Title: 90% CPU on Profile Editor: Throttle mainMessageLoop
I have a big problem in my Unity game, in almost every scène of my game, my editor is laggy, when I record Porfile Editor / deep profile editor, here is the result:

I have no idea what is this throttle MainMessageLoop, what can I do ? Thanks you !

# Answer
so thanks to John Hamilton & DMGregory, I found the problem, and figure out a "kind" of a solution. The blue spikes was throwing this types of error:

```
Unaccounted time between: GPUProfiler.BeginQueries

```

I download the last version (from Unity 5.6.1 to Unity 5.6.3) and the problem is solved.
> 2 votes

# Answer
Hi i had same exact issue, turns out it was windows throttling performance down. Go to Power management settings and set your pc to Performance mode (i am on a desktop mind you), after that the stutter disappeared.
> 1 votes

---
Tags: unity, c#, profiler, cpu
---


# Question
Title: What does the TextureRegion.flip() method do?
I'm learning libgdx and don't understand the purpose of parameters passed to `flip(boolean x, boolean y)`. For example, I have code like this:

```
texture = new Texture(Gdx.files.internal("data/texture.png"));
textureRegion = new TextureRegion(texture, 0, 0, 20, 20);
textureRegion.flip(false, false);

```

My `TextureRegion` is flipped when both parameters are `true` and not flipped when they are `false`. But why does it need two parameters when it could have only one? The documentation says nothing about that.

# Answer
> 4 votes
textureRegion.flip(false, false); this will keep the original image as it is.

textureRegion.flip(true,false) it will mirror the image as below.ie it will flip the original image horizontally and preserve its y direction.

textureRegion.flip(false,true) ; it will flip the original image vertically and preserve its x direction

textureRegion.flip(ture,true) ; it will flip the original image vertically and horizontally

# Answer
> 3 votes
The parameters control which axis the image will be flipped around; sometimes you only want to flip around one or the other axis, instead of both.

The first parameter, if true, causes the image to be flipped in the X direction (horizontal flip) The second parameter, if true, causes the image to be flipped in the Y direction (vertical flip).

If both are true, the image is flipped around both axes.

---
Tags: java, libgdx
---


# Question
Title: How can I make a "wet surface"/"shallow puddle" shader in Unity?
In my game I need to create dynamic water puddles but I cannot find a tutorial that shows how I can make such an effect (an example of which is shown below). How can I do it?

# Answer
# Reflection

To create a wet shader, you first need to have a reflection.

You can use a Reflection Probe or a MirrorReflection3 but, I use a fake reflection (Cube Map) here because the shader can then be used on mobile.

```
Shader "Smkgames/TransparentCubeMap" {
Properties {
_Color("Color",Color) = (1,1,1,1)
_Cube ("Cubemap", CUBE) = "" {}
_Metallic("Metallic",Range(0,1)) = 1
_Smoothness("Smoothness",Range(0,1)) = 1
_Alpha("Alpha",Range(0,1)) = 1
}
SubShader {
Tags {"RenderType"="Transparent" "Queue"="Transparent"}
LOD 200
Pass {
ColorMask 0
}
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
ColorMask RGB

CGPROGRAM
#pragma surface surf Standard fullforwardshadows alpha:fade

struct Input {
float2 uv_MainTex;
float3 worldRefl;
};
sampler2D _MainTex;
samplerCUBE _Cube;
float4 _Color;
float _Metallic;
float _Smoothness;
float4 _EmissionColor;
float _Alpha;
void surf (Input IN, inout SurfaceOutputStandard o) {
fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;

o.Albedo = c.rgb * 0.5 * _Color;
o.Emission = texCUBE (_Cube, IN.worldRefl).rgb*_Color;
o.Metallic = _Metallic;
o.Smoothness = _Smoothness;
o.Alpha = _Alpha;

}
ENDCG
}
Fallback "Diffuse"
}

```

# Distortion

To add distortion to your reflection, you can multiply the normal map and the `worldRefl`:

```
float3 distortion = tex2D(_Distortion, IN.uv_Distortion);
o.Emission = texCUBE(_Cube, IN.worldRefl*distortion).rgb

```

# Procedural Shape

You can use noise to make a procedural shape:

Here's a Fractal Brownian Motion (FBM) tutorial.

```
Shader "Smkgames/FbmNoise"
{
Properties
{
_TileAndOffset("Tile and Offset",Vector) = (1,1,0,0)
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100

Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
#pragma multi_compile_fog

#include "UnityCG.cginc"

struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};

struct v2f
{
float2 uv : TEXCOORD0;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
};

float4 _TileAndOffset;
float _Step,_Min,_Ma;

v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv*_TileAndOffset.xy+_TileAndOffset.zw;
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}

// Author @patriciogv - 2015
// http://patriciogonzalezvivo.com

float random (in float2 st) {
return frac(sin(dot(st.xy,
                    float2(12.9898,78.233)))*
    43758.5453123);
}

// Based on Morgan McGuire @morgan3d
// https://www.shadertoy.com/view/4dS3Wd
float noise (in float2 st) {
float2 i = floor(st);
float2 f = frac(st);

// Four corners in 2D of a tile
float a = random(i);
float b = random(i + float2(1.0, 0.0));
float c = random(i + float2(0.0, 1.0));
float d = random(i + float2(1.0, 1.0));

float2 u = f * f * (3.0 - 2.0 * f);

return lerp(a, b, u.x) +
        (c - a)* u.y * (1.0 - u.x) +
        (d - b) * u.x * u.y;
}

#define OCTAVES 6
float fbm (in float2 st) {
// Initial values
float value = 0.0;
float amplitude = .5;
float frequency = 0.;
//
// Loop of octaves
for (int i = 0; i < OCTAVES; i++) {
    value += amplitude * noise(st);
    st *= 2.;
    amplitude *= .5;
}
return value;
}

        fixed4 frag (v2f i) : SV_Target
        {

float2 st =i.uv;

float3 color = float3(0,0,0);
color += fbm(st*3.0);
return float4(color,1.0);

        }
ENDCG
}
}
}

```

The FBM above shouldn't be used directly in to your shader because it has many GPU calculations and decreases performance. Instead of using directly, you can render the result to a texture with RenderTexture.

Shadertoy uses multiple passes, one per "buffer". As the name indicates, this pass stores the results in a buffer, which is just a texture. Unity will let you render to textures too.

# Creating Mask

You can make a thick and smooth mask with these functions:

**Step**

Outputs 1 if `[A]` is less than or equal to `[B]`, otherwise outputs 0.

**Smoothstep**

Blends smoothly between two values, based on where a third value is in that range, outputting values between 0 and 1. Think of it as a clamped inverse lerp with a smoothed output value.

# Result

```
/* Warning: don't use this shader because this is for preview only.
It has many GPU calculations so if you want use this in your game you should
remove the FBM noise functions or render it to texture, or you can use an FBM texture
*/
//Created By Seyed Morteza Kamaly
Shader "Smkgames/WetShader" {
Properties{
_MainTex("MainTex",2D) = "white"{}
_Distortion("Distortion",2D) = "bump"{}
_Cube("Cubemap", CUBE) = "" {}
_BumpMap("Bumpmap", 2D) = "bump" {}
_Metallic("Metallic",Range(0,1)) = 0
_Smoothness("Smoothness",Range(0,1)) = 1
_ReflectAlpha("ReflectAlpha",Range(0,1)) = 1
scaleX("UV.X scale",Float) = 10.0
scaleY("UV.Y scale",Float) = 10.0
_Smooth("Smooth",Float) = 0.4
_Intensity("Intensity",Float) = 1
}
SubShader{
Tags{ "RenderType" = "Transparent" "Queue" = "Transparent" }
LOD 200
Pass{
ColorMask 0
}
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
ColorMask RGB

CGPROGRAM
#pragma surface surf Standard fullforwardshadows alpha:fade

struct Input {
float2 uv_MainTex;
float2 uv_Distortion;
float3 worldRefl;
float2 uv_BumpMap;
INTERNAL_DATA
};
sampler2D _MainTex, _Distortion;
samplerCUBE _Cube;
float _Metallic,_Smoothness;
float4 _EmissionColor;
sampler2D _NormalMap;
uniform fixed scaleX, scaleY, _Smooth, _Intensity,_Alpha,_ReflectAlpha;

static const float2x2 m = float2x2(-0.5, 0.8, 1.7, 0.2);

float hash(float2 n)
{
return frac(sin(dot(n, float2(95.43583, 93.323197))) * 65536.32);
}

float noise(float2 p)
{
float2 i = floor(p);
float2 u = frac(p);
u = u*u*(3.0 - 2.0*u);
float2 d = float2 (1.0, 0.0);
float r = lerp(lerp(hash(i), hash(i + d.xy), u.x), lerp(hash(i + d.yx), hash(i + d.xx), u.x), u.y);
return r*r;
}

float fbm(float2 p)
{
float f = 0.0;
f += 0.500000*(0.5 + 0.5*noise(p));
return f;
}

float fbm2(float2 p)
{
float f = 0.0;
f += 0.500000*(0.6 + 0.45*noise(p)); p = p*2.02; p = mul(p, m);
f += 0.250000*(0.6 + 0.36*noise(p));
return f;
}

void surf(Input IN, inout SurfaceOutputStandard o) {
fixed4 c = tex2D(_MainTex, IN.uv_MainTex);

o.Metallic = _Metallic;
o.Smoothness = _Smoothness;
o.Alpha = 1;

float t = fbm2(float2(IN.uv_MainTex.x*scaleX, IN.uv_MainTex.y*scaleY));

float fbmMask = step(t, _Smooth)*_Intensity;
float3 distortion = tex2D(_Distortion, IN.uv_Distortion);
o.Emission = texCUBE(_Cube, IN.worldRefl*distortion).rgb*_ReflectAlpha*fbmMask;

o.Albedo = float4(1.0, 1.0, 1.0, 1.0)*tex2Dlod(_MainTex, float4(IN.uv_MainTex, 0.0, 0.0));

}
ENDCG
}
Fallback "Diffuse"
}

```

# Using Maps

Physically Based Shading

Here's a useful definitions:

> **Roughness** Describes the microsurface of the object. White 1.0 is rough and black 0.0 is smooth. The microsurface if rough can cause the light rays to scatter and make the highlight appear dimmer and more broad. The same amount of light energy is reflected going out as coming into the surface. This map has the most artistic freedom. There is no wrong answers here. This map gives the asset the most character as it truly describes the surface e.g. scratches, fingerprints, smudges, grime etc.
>
> **Glossiness** This map is the inverse of the roughness map. White 1.0 is smooth and 0.0 black is rough. Describes the microsurface of the object. The microsurface if rough can cause the light rays to scatter and make the highlight appear dimmer and more broad. The same amount of light energy is reflected going out as coming into the surface. This map has the most artistic freedom. There is no wrong answers here. This map gives the asset the most character as it truly describes the surface e.g. scratches, fingerprints, smudges, grime etc.
>
> **Specular** This map contains the reflectance information for both metal and dielectrics (non metal) surfaces. This is a key difference in the metal/rough and spec/gloss workflows. The same rules apply. You need to use measured values for metals and most all dielectrics will fall with the 0.04 - 4% range. If there is dirt on the metal, the reflectance value needs to be lowered as well. However, you can add different values in the specular map for dielectric materials since you have control to author the map.
>
> https://forum.allegorithmic.com/index.php?topic=3243.0

# Roughness

I don't know why, but the Unity standard shader doesn't have a smoothness map, so I wrote a basic shader and added this map.

```
Shader "Smkgames/SimpleSurface" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _GlossMap("GlossMap",2D) = "white"{}
        _Glossiness ("Smoothness", Float) = 1.5
        _Metallic ("Metallic", Float) = 0.5
        _MetallicMap("MetallicMap",2D) = "white"{}
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Standard fullforwardshadows

        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
        };

        half _Glossiness,_Metallic;
        fixed4 _Color;
        sampler2D _GlossMap,_MetallicMap;

        UNITY_INSTANCING_CBUFFER_START(Props)
        UNITY_INSTANCING_CBUFFER_END

        void surf (Input IN, inout SurfaceOutputStandard o) {
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            o.Metallic = _Metallic*tex2D(_MetallicMap,IN.uv_MainTex);
            o.Smoothness = _Glossiness*tex2D(_GlossMap,IN.uv_MainTex);
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

I think Unity doesn't have roughness, it only has metallic, but the alpha channel is for roughness and the red channel is for metallic. You can change the intensity with smoothness.

Source on GitHub.

# Useful links

https://80.lv/articles/how-to-create-wet-mud-in-substance-designer/

https://www.fxguide.com/featured/game-environments-partc/
> 127 votes

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


# Question
Title: XNA triangle grid not drawn using DrawIndexedPrimitives
I have just recently started working with Monogame (XNA). Now I had code that was drawing a grid using DrawUserIndexedPrimitives. However I read that it reloads the vertices in the GPU each draw, and I don't think that is going to cut it for me. Therefore I wanted to use DrawIndexedPrimitives instead.

However, when I made the switch, my pretty grid suddenly dissapeared. The question is thus: What did I do wrong using DrawIndexedPrimitives? The code within the draw method is given below:

```
game.GraphicsDevice.Indices = terrainIndexBuffer;
game.GraphicsDevice.SetVertexBuffer(terrainVertexBuffer);

game.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,
                                          0,
                                          0,
                                          terrainVertices.Length,
                                          0,
                                          triangleIndicesList.Length / 3);
// This worked VV
// game.GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList,
//                                               terrainVertices,
//                                               0,
//                                               terrainVertices.Length,
//                                               triangleIndicesList,
//                                               0,
//                                               triangleIndicesList.Length / 3);

```

Here `terrainVertices` is the list of vertices for the triangles, `triangleIndicesList` is a list representing the triangles (each three entries here refer to the vertices of one triangle). Outside of the Draw method, I initialized the grid and index list as follows:

```
terrainVertexBuffer = new VertexBuffer(game.GraphicsDevice,
                                       typeof(VertexPosition),
                                       terrainVertices.Length,
                                       BufferUsage.None);

terrainIndexBuffer = new IndexBuffer(game.GraphicsDevice,
                                     IndexElementSize.SixteenBits,
                                     sizeof(short) * triangleIndicesList.Length,
                                     BufferUsage.None);

terrainVertexBuffer.SetData<VertexPosition>(terrainVertices);

```

# Answer
It turns out that I forgot to initialize the terrainIndexBuffer with the array of indices. So I added the line `terrainIndexBuffer.SetData(triangleIndicesList);`
> 0 votes

---
Tags: xna, monogame
---


# Question
Title: Where to start in a project after the design phase?
I want to start a new project but I'm a beginner. I already have most of the ideas in terms of gameplay, lore,... I have written pages of notes and concepts about the game. Basically, I know most of the things I want to put in my game and a big part of their design is done.

I made a few small projects with Unity, I know how to program, I know how to use Blender and I have edited some textures. Basically, I know the basis most of the technologies I'll need to use.

The problem is that I don't know where to begin. Should I start with modelling? Create maps? Start with scripting? I'm undecided because many of these tasks can be done in parallel if you have people working with you and are more or less independent in early stages of development.

All of the answers I read were for people who didn't even have ideas in the first place and knew nothing about development. My problem is more about project management after the design phase.

# Answer
Well, if you have everything planned out, it think it's fair to say you can work on a proof-of-concept setup. make a test-map and character, and see if you can get most of the basic functionality to work. Try to work as modular as possible, so you can more easily scale your project and make changes.
> 2 votes

---
Tags: unity, blender, project-management
---


title: Loading image problem in libGDX

text:
# Question
Title: Loading image problem in libGDX
So i recently started learning libGDX, and I'm running into an error which did not occur in the tutorial series I was following.

I'm loading the image using :

```
killSkull = new Texture("KillSkull.png");

```

I made sure that i got the name as well as the extension correct, and the image is there in the assets folder.

I still get the error :

```
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load file: KillSkull.png
at com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:149)
at com.badlogic.gdx.graphics.TextureData$Factory.loadFromFile(TextureData.java:98)
at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:100)
at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:92)
at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:88)
at com.saumi.game.assets.Assets.load(Assets.java:12)
at com.saumi.game.Main.create(Main.java:25)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:149)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:126)
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: File not found: KillSkull.png (Internal)
at com.badlogic.gdx.files.FileHandle.read(FileHandle.java:136)
at com.badlogic.gdx.files.FileHandle.readBytes(FileHandle.java:222)
at com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:146)
... 8 more

```

# Answer
> 0 votes
You probably just have to change the working directory. If you're working in Eclipse you can follow these steps:

1. Try to run your application once (it will fail).
2. Now go to **Run Configurations** by pressing the arrow next to the green **Run** button:

You should see a configuration called **DesktopLauncher** if step 1 was done correctly.
3. After pressing **Run Configurations...** you should be greeted with a popup window. From here you can change your working directory:
    1. Select **DesktopLauncher** from the dropdown on the left. The panel on the right should change.
    2. Select the **Arguments** tab from the panel on the right.
    3. At the bottom change **Working Directory** to **Other: Workspace**
    4. Find your project and select the `assets` folder.

# Answer
> -1 votes
Is the image located in another folder within the assets folder? like assets/data/KillSkull.png if so you will have to include that folder name like this -\> killSkull = new Texture("data/KillSkull.png");

if the above one is not your case then try this out

killSkull = new Texture(Gdx.files.internal("KillSkull.png"));

# Answer
> -2 votes
After searching for this online the answer was actually something to do with run configurations.

You can find the answer here : https://stackoverflow.com/a/22833470

---
Tags: java, libgdx
---


# Question
Title: How to distinguish between different platforms using an interface
I'm creating a platform system using a raycast controller that uses an interface to perform different tasks based on the type of platform with which my player is currently colliding. Some of the platform types include ice, passable blocks and muddy ground.

I want to know how to better optimize my code, as I currently call Unity's somewhat expensive "GetComponent()" function every frame, even if I never change between blocks. What I'd like to do is only call GetComponent() when I change from one type of platform to a different type of platform (i.e. muddy ground --\> ice), but don't know how to do this using an interface.

I thought I would be able to compare types using enums, but you're not allowed to declare types in an interface.

```
        if (hit)
        {
            //I'd only like to run this block of code if the type of platform changes
            var platform = hit.collider.gameObject.GetComponent<IPlatform>();

            State.IsCollidingWithPassablePlatform = platform.IsPassable;
            State.IsJumpBoosted = platform.IsJumpForce;
            State.IsBoosted = platform.IsForce;

            xForce = platform.XForce;
            yForce = platform.YForce;
            zForce = platform.ZForce;

            defaultParameters.accelerationTimeGrounded = platform.AccelerationTimeGrounded;
            defaultParameters.accelerationTimeAirborne = platform.AccelerationTimeAirborne;

```

Interface example:

```
interface IPlatform {

float AccelerationTimeGrounded { get; }
float AccelerationTimeAirborne { get; }

float XForce { get; }
float YForce { get; }
float ZForce { get; }

bool IsPassable { get; }

bool IsForce { get; }
bool IsJumpForce { get; }

```

Ice platform:

```
public class PlatformIce : MonoBehaviour, IPlatform {

public float AccelerationTimeGrounded { get { return accelerationTimeGrounded; } }
public float AccelerationTimeAirborne { get { return accelerationTimeAirborne; } }

public float XForce { get { return xForce; } }
public float YForce { get { return yForce; } }
public float ZForce { get { return zForce; } }

public virtual bool IsPassable { get { return false; } }

public bool IsForce { get { return false; } }
public bool IsJumpForce { get { return false; } }

[SerializeField]
private float accelerationTimeGrounded = 1.0f;
[SerializeField]
private float accelerationTimeAirborne = 3.0f;

private float xForce = 0;
private float yForce = 0;
private float zForce = 0;
}

```

# Answer
> 2 votes
If your interface implementations differ only in the data they return from these getters, you might not need interfaces at all but a type object.

Then your platform script might be just an attachment point to glue this data structure to the game object:

```
public class Platform : MonoBehaviour {
    public PlatformProperties platformType;
}

```

And your PlatformProperties could be a ScriptableObject to make it easy to author in the editor and share between instances:

```
[CreateAssetMenu(fileName = "newPlatformProps.asset", menuName = "Level/Platform Properties")]
public class PlatformProperties : ScriptableObject {
    public Vector3 someProperty;
    // etc...
}

```

(You can of course use private serializable fields and getters to keep these things read-only if you want to enforce clean OOP here)

Determining whether the new platform is the same type as the old platform will still require getting a handle to the new platform — I can't tell you if "what's in the box" is the same as what's in my hand unless I open the box first.

But, we can at least detect whether we have a new box to open, rather than re-peeking into the same box every frame.

First, we cache the last platform collider and script we encountered:

```
Collider _lastCollider;
Platform _lastPlatform;

```

Then in your collision handling logic (be it an OnCollisionEnter or a raycast/other test)...

```
     // Do things like discarding non-foot collisions
     // and updating grounded state here.

    if(hit.collider == _lastCollider) {
         // no news, early-out.
         return;
    }

    // Look for a platform script on the new platform
    var platform = hit.collider.gameObject.GetComponent<Platform>();

     if(platform == null)
         return; // Not a platform.

     _lastCollider = hit.collider

      if(platform.platformType != _oldPlatform.platformType) {
          // Here we know it's a new type.
     }
     _oldPlatform = platform;

    // ... etc

```

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


title: Too fast swipe in Unity game

text:
# Question
Title: Too fast swipe in Unity game
I am letting the user to swipe around in some movement and to see the scene on mobile device.
Facing too fast swipe.
Need to make swipe slower, smother.Using the code:

```
foreach(Touch touch in Input.touches)
{
    transform.localEulerAngles = new Vector3(
        transform.localEulerAngles.x + touch.deltaPosition.y, transform.localEulerAngles.y + touch.deltaPosition.x, transform.localEulerAngles.z);
}

```

# Answer
You can control the movement speed by multiplying `touch.deltaPosition` values on a scalar.

`transform.localEulerAngles.x + touch.deltaPosition.y * scalar`

Where `scalar` is whatever you want it to be - 0.5 will make it twice slower, 2.0 will make it twice faster.
> 1 votes

---
Tags: unity, transformation
---


# Question
Title: Why not derive velocity from position updates in games?
Is there a reason why retrieving velocity of a 3d object in a game engine vs deriving it from position updates is preferable?

I am currently polling position at every step and deriving current velocity, however, there is also a "get velocity" option. I already need position but I'm wondering if the velocity in the game engine is preferable for some reason like it has less latency than the derivative.

# Answer
In the vast majority of situations, calling getVelocity is a vastly preferable approach.

* You don't have to be polling objects on the off chance that *next* frame you are going to need a velocity (which requires the position from last frame). If I have 10,000 objects and nee the velocity of 10 of them on any given frame, there's no point in storing off 10,000 old positions.
* The derived velocity you are getting is an "average velocity" over the frame. In many models, you want an instantaneous velocity.
* In many physics based systems, the equations of motion actually calculate the new position using the velocity, not the other way around.
* A velocity can be defined in the first frame, but you can't derive a velocity until the second frame.
* Instantaneous velocities often have properties. For example, the velocity of an object in orbit is always 90 degrees from the direction from the object to the planet. This will not always be true with the average velocities you can get from a derived velocity.
* a getVelocity function permits running the physics models at rates that are different from the frame rate. This can be useful if you need higher quality integration in your motion model.

I think you may be in a corner case where you *happen* to what to do all the extra effort required the derive an average velocity, so for you the two approaches are very similar. In most situations, they are not as similar.
> 10 votes

# Answer
Deriving velocity from position is actually used in some games & parts of games, when the implementation uses **Verlet integration** or similar techniques.

Here we replace a conventional Euler integration step

$$\begin{align} \vec v\_{t+1} &= \vec v\_t + \vec A(t) \Delta t \\ \vec p\_{t+1} &= \vec p\_t + \vec v\_t \Delta t \end{align}$$

(where \\$\vec A(t)\\$ is a function returning the average acceleration during the update at time \\$t\\$)

With a formula like this:

$$\vec p\_{t+1} = 2 \vec p\_t - \vec p\_{t-1} + \vec A(t) \Delta t^2$$

So here we store \\$\vec p\_{t-1}\\$ instead of \\$\vec v\_t\\$ from one frame to another, effectively reconstructing \\$\vec v\_t \Delta t\\$ from \\$\vec p\_t - \vec p\_{t-1}\\$

This entails an assumption that last update's \\$\Delta t\\$ is the same as this one, so **when going this route you'll definitely want to use a fixed timestep** to avoid strange and hard-to-debug divergence. (There are ways to approximately correct for time variations, but this only reduces the problem rather than eliminating it the way a fixed timestep does, and more simply too)

**Verlet integration has good numerical stability** compared to explicit Euler, and it's even time reversible, which is a neat trick.

It's also a really nice system to use when you want to implement **custom constraints** on objects - like keeping objects a minimum/maximum/fixed distance apart. You can apply your integration step, then snap your resulting position to the closest point satisfying the constraint, and you're done. The object's velocity implicitly reacts to the constraint because it's calculated from the position. This can make even complicated constraints & combinations very simple to author.

But, the behaviour of those constraints is **not always physically plausible**.

Imagine an object is at the rightmost extent of its constrained space, travelling rightward. In the next update, its integration takes it past its constrained envelope, and the constraint snaps it back to the edge - the same position it was in at the last timestep. Now in the next timestep, subtracting the two previous positions gives us zero: any momentum & energy the object had has simply vanished, rather than rebounding or transferring to another body in a physically-conserved way.

So, **Verlet integration is not energy-preserving**, and it's more challenging to represent realistic elastic collisions with it, or other situations where the velocity changes discontinuously. (This is related to Cort Ammon's point that comparing positions is implicitly working with *average* velocity, when many applications want an *instantaneous* velocity)

For some applications, this is actually desirable: the energy leak acts as a damper and improves the stability of the simulation, reducing jitter or spontaneous launching-to-infinity glitches you might see in other setups.

Myself, I like using Verlet integration when I need some simple dynamic/reactive movement with constraints for visual effects, where physically correct collision response isn't a big deal and I can afford some leakage, like particle systems or googly / bobblehead effects. Here the simplicity of the code even in the presence of constraints (like springs / limits on the bobble swing range) is a big win, and the stability properties mean I don't need to worry as much about the effect freaking out under varying sim conditions, letting me play with more extremes and not get bogged down in parameter fine-tuning.
> 4 votes

---
Tags: physics, 3d, physics-engine
---


# Question
Title: Cocos2dx - Create the friction of the ground
I'm writing a game, it a pool game. I've read about cocos2dx + physics library, however the document is really poor to understand.

Material has 3 attributes (http://www.cocos2d-x.org/wiki/Physics#) : \- Density (?) \- Friction (?) \- Restitution (scale from 0 to 1)

Execept the restitution has limitation value from 0 to 1. I don't know what's density and the limitation of friction value?

If i want to create a ball and when it collide to the bound/wall, it bounce back, and the ground has friction to slow down the ball during running, how can i do it?

# Answer
> 1 votes
First of all you need to make sure your `Scene` is created with physics enabled. You do this by calling `auto scene = Scene::createWithPhysics();` where relevant in your code. If not, none of the physics you'll try will work.

Next, you shouldn't pay too much attention to the material right now, what you should probably focus on is the `PhysicsBody` class and its methods and variables.

For instance, if I were to make a simple ball physics object I'd do something like this : \`

```
auto sprite = Sprite::create("ball.png");
auto physicsBody = PhysicsBody::createCircle(16.0f); // 16 being the radius of the circle
sprite->setPhysicsBody(physicsBody);
addChild(sprite);
physicsBody->setVelocity(Vec2(100, 20));

```

Repeat this a few times, changing the `setVelocity(Vec2(x, y));` as needed, see if you can get a bunch of balls moving around on the screen. I believe they will bump into each other by default. You could also use `physicsBody->applyForce(Point(x, y));` or `physicsBody->applyImpulse(Point(x, y));`.

More information on both can be find in the class documentation here: http://www.cocos2d-x.org/reference/native-cpp/V3.0alpha0/d7/d7b/classcocos2d\_1\_1\_physics\_body.html#a06169bfab34c574afd767ebf1e1f7058

# Answer
> 1 votes
Old thread but I wanted to put my two cents in since I needed something like this on a project I worked on.

You can create a physics body for a sprite with a specified material. This would look something like. `groundSprite->setPhysicsBody(PhysicsBody::createBox(boxSize, PhysicsMaterial(0.1f, 0.5f, 0.7f)));` where the last parameter is the friction parameter like OP mentioned. Play around with it until your ball comes to a stop where/when you want it to.

You could continuously apply a force or impulse while your ball moves across the table, but I think using the built in physics would be much less work.

---
Tags: c++, physics, cocos2d
---


# Question
Title: Is Time.deltaTime different on various devices?
Can someone say what is wrong with my code. I have custom timer implemented like this:

```
 float timeRemain = 10f;
 void Update(){
 timeRemain -= Time.deltaTime;
 if(timeRemain <= 0){
  ///...code here.
   }
 }

```

On PC it runs like expected but on Android device `timeRemain` variable becomes 0 in less then 10 secs. Who can suggest me what happens when i run it on Android device?

# Answer
> 4 votes
On some platforms the game actually starts running before the splash screen is gone. So this may give the illusion of a defective timer if you test it right at the start.

Another issue on slow devices is that your first frame of timer activation may have a very large `deltaTime` if other things happen at the same time.

For example if it takes 2 seconds to transfer all the textures and meshes to GPU memory on the first frame the timer is activated then the perceived display time will be 8 seconds because whatever was to be shown was invisible for the 2 seconds hang.

The `deltaTime` is the time the **previous** frame took.

Other than these two gotchas, `deltaTime` acts in an identical fashion on all platforms.

---
Tags: unity, c#, timer, timestep, fixed-timestep
---


# Question
Title: Libgdx Texture Sides Are Cropped Automatically for Seemingly No Reason
I'm trying to render some textures using libgdx SpriteBatch. This sounds very easy but I have a serious problem. I'm testing on desktop and depending on the resolution of the app window, textures are automatically cropped. This happens when I configure width and height attributes of LwjglApplicationConfiguration or when I just resize app window manually. Right and bottom sides of some or all of the textures are cropped depending on the resolution (maybe it depends on x,y coordinates of texture rectangles, some are shown good others are buggy). I load textures from atlas. While atlas uses MipMapLinearLinear filter, I also tested with Nearest filter, the problem still persists

Here are important parts of the code (the rest is default things taken from example like creating SpriteBatch, etc.)

```
// I use premultiplied alpha blending
batch.enableBlending();
batch.setBlendFunction(GL20.GL_ONE, GL20.GL_ONE_MINUS_SRC_ALPHA);

myAtlas = new TextureAtlas(Gdx.files.internal("test.atlas"));
textureRegion = myAtlas.findRegion("testtexture");

batch.draw(textureRegion, 100, 100, 40, 40);

```

Here is a image below showing app windows.

# Answer
> 1 votes
This is due to rounding errors in the rendering pipeline all the way to the GPU.

In this case the texture is cropped short, in other cases the texture is rendered a little too far (see: Sprite sheet textures picking up edges of adjacent texture)

One way to alleviate the issue (it is not possible to completely eliminate it due to the variety of GPUs and drivers) is to add a 1 pixel transparent border around your sprites, render that transparent border, while enabling interpolation.

This will push the hard-cut nature of the polygon edge 1 texel away from the important texels of your sprite. The sprite texture may become slightly misaligned and a bit blurry in the problem positions (rounding errors) but wont be harshly cut.

They will remain anti-aliased and avoid the +/- 1 pixel/texel rounding error.

---
Tags: libgdx
---


title: Moving a point on a rotating sprite

text:
# Question
Title: Moving a point on a rotating sprite
I've been trying to get sprites to stay on a set point on another rotating sprite. At the moment, it's very inaccurate, the original position is wrong, and when the rotation is applied the sprite drifts away from the point its intended to stay in. The code I'm currently using is as follows, and I'm pretty sure there's *something* wrong with it, I just don't know what it is.

```
rad = sqrt((x-originx)^2 + (y-originy)^2)
x = originx + cos(cameraangle+asin(x-originx)) * rad)
y = originy + (sin(cameraangle+acos(y-originy)) * rad)

```

# Answer
Based on the notation i'm assuming this is in GameMaker. If you're not using Gamemaker, you could derive a similar solution from this code. Anyways, a much simpler way to do this would be to use lengthdir. I'm not sure about your exact situation, but if obj\_a is your rotating object, then run this code in object b:

var len = 10;//length in pixels

x = obj\_a.x + lengthdir\_x(obj.x,obj.y,len);

y = obh\_a.y + lengthdir\_y(obj.x,obj.y,len);
> 0 votes

---
Tags: mathematics, movement, trigonometry
---


# Question
Title: Activate and Deactivate Mouse Cursor on UI
I have a player with a character controller component.

When the player is generally interacting with the UI I would like to stop the character and camera controller and show the cursor to the player in order to (e.g select a weapon) and when they're done I would like it to switch back.

How do I address this issue?

# Answer
As per my understanding your `player` has a First Person Character controller `Component`. You'd need a script sitting on some `GameObject` of your preference and in that script you should follow this logic:

```
public ui_gameobject; //Attach this in the Inspector

//Check if UI is being displayed and handle the cursor
void DetectUIandHandleCursor(){
     if(ui_gameobject.IsActive()){
         Cursor.visible = true;
         Cursor.lockState = CursorLockMode.None;
     }else{
         Cursor.visible = false;
         Cursor.lockState = CursorLockMode.Locked;
}}

```

I suppose you already have a script managing your `UI` elements (meaning switch them on/off), so the previous snippet should check when you are displaying it and show or hide the cursor accordingly.
> 2 votes

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


# Question
Title: How can I use startcoroutine to change a variable value using while?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Outline : MonoBehaviour
{
    public float width;

    private Renderer rend;
    private float currentWidth;

    private void Start()
    {
        rend = GetComponent<Renderer>();
        currentWidth = rend.material.GetFloat("_Outline");

        StartCoroutine(ChangeOutline());
    }

    private void Update()
    {
        //SetOutLineWidth(width);
    }

    public void SetOutLineWidth(float width)
    {
        rend.material.SetFloat("_Outline", width);
    }

    IEnumerator ChangeOutline()
    {
        float timeToWait = 3f;

        while (currentWidth < width)
        {
            width += 0.01f;
            SetOutLineWidth(width);
            yield return new WaitForSeconds(timeToWait);
        }
    }
}

```

What I want to do is for example if I will set width variable value to 5 then change the value until the currentWidth is 5:

```
SetOutLineWidth(width);

```

If the currentWidth is 7 and I set width to 5 change the value from 7 to 5 slowly. If currentWidth is 7 and I set width to 10 again change it slowly to 10. What I did now is making the width value keep raising and setting the Outline non stop.

What I want to do in general is to make two modes:

1. Change the width value and set the Outline slowly according to the time once on one direction.
2. Like 1 but make it ping pong mode once the outline value reached to width change it back slowly to the first value outline was and then back to width nonstop.

# Answer
I guess what you are trying to do (based, on your description) is to lerp between 2 numbers.

No need for timer, just do this:

```
public float duration = 3f;
float lerp = 0;

public float currentWidth = 4;
public float finalWidth = 10;

private void Update()
{
    lerp += Time.deltaTime / duration;
    currentWidth = Mathf.Lerp(currentWidth, finalWidth, lerp);

    SetOutLineWidth(currentWidth);
}

public void SetOutLineWidth(float w)
{
    rend.material.SetFloat("_Outline", w);
}

```

Unity Lerp documentation: https://docs.unity3d.com/ScriptReference/Mathf.Lerp.html
> 2 votes

# Answer
I don't know what material you are using, so I just changed the script to use the scale of a plane object, but you can attach any shape to it. You should be able to modify the script to make it work with the material property.

```
using UnityEngine;

public enum Mode
{
    Grow,
    Shrink,
    PingPong
}

public class Outline : MonoBehaviour {

public float maxWidth;
public float minWidth;
public float growthRate;
public float timeToWait = 1f;
public Mode Mode;

private float currentWidth;
private bool grow = false;
private float timeToUpdate;

private void Update()
{
    currentWidth = transform.localScale.x;
    if (Time.time + timeToWait > timeToUpdate)
    {
        switch (Mode)
        {
            case Mode.Grow:
                if (currentWidth < maxWidth)
                {
                    currentWidth += growthRate;
                    SetOutLineWidth(currentWidth);
                }

                break;
            case Mode.Shrink:
                if (currentWidth > minWidth)
                {
                    currentWidth -= growthRate;
                    SetOutLineWidth(currentWidth);

                }

                break;
            case Mode.PingPong:

                if (grow)
                {
                    currentWidth += growthRate;
                    SetOutLineWidth(currentWidth);
                   if (currentWidth >= maxWidth)
                       grow = false;
                }
                else
                {
                    currentWidth -= growthRate;
                    SetOutLineWidth(currentWidth);
                   if (currentWidth <= minWidth)
                        grow = true;

                }

                break;
            default:
                break;
        }

        timeToUpdate = Time.time + timeToWait;
    }
}

public void SetOutLineWidth(float width)
{
    transform.localScale = new Vector3(width, 1, 1);
}
}

```
> 1 votes

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


# Question
Title: How can I test if my rage game's hardest levels are achievable?
I love rage games and have made a rage game too, but I always wondered how to test if levels in these types of games are too hard or not, since it's ironically too hard to test.

For example: If I were making a game similar to Super Hexagon or Super Meat Boy, do I need to take all the time and effort to go through and beat the whole game? Or are there some easier, but valid workarounds?

I had this problem in a game I made a few years ago. It has 4 difficulties: easy, normal, hard and insane. Before release I'd only completed easy mode and post-release I completed normal, but I'm not sure if hard and insane are achievable.

Here's the game in case you want to see it:

https://gamejolt.com/games/30-seconds-to-survive/30107

# Answer
> 10 votes
One major strategy that helps is something we call **level design metrics**.

Here you work out what kinds of level design arrangements are navigable, by testing them out in isolation.

We'll often build a "gym" level, with things like passages of varying widths, corners of varying sharpness, pits of varying lengths, etc.

We can try each setup on its own, or in combination, to establish which setups feel good with the game's current 3Cs (character/controls/camera), and where each one sits on our desired difficulty spectrum.

From this we derive a set of metrics: specified sizes of passages, features, and spacings, or modular sequences, which level designers can use to plan their levels and know they're navigable because they follow these conventions.

For non-rage games the focus is usually on comfort and flexibility — ensuring there's enough space that the player, their camera, and AI can move smoothly without getting snagged, that any of the player's abilities can be used without glitching/clipping, and that the player can clearly distinguish "that's a ledge I can jump to" from "that's a wall I can't jump over" without trial & error.

But for a rage game you can tighten the screws further to what's juuuust possible. ;)

---

Another ingredient that can help is **analyzing the trajectory of moves** like a jump.

Say you have a metrics gym where you can just make a 6-tile jump. You can record the trajectory of that jump so you know exactly how much room you have around it for obstacles, or what timing window you need for moving hazards that cross the trajectory.

That lets you take a possible jump and make it even harder without breaking its possibility.

If your mechanics are mathematically tractable, you can work out the equations describing possible moves, and the margin of error if the input is just a little off, to test this for any arbitrary angle/distance.

If they're not so simple, you could rig up a script that tries every combination of inputs in 5-degree increments & 0.016 s durations and records the outcomes, giving you good coverage over the whole space of possible trajectories.

If you want to go really deep, you could conceivably extend this analytical technique to an automated level verifier that uses a pathfinding routine to search the player movement space for possible solutions to a given level. By checking the range of deviation a given solution allows, you can estimate whether it's humanly possible or more likely limited to tool assisted speedruns. ;)

---
Tags: testing, difficulty
---


title: How to do gear physics

text:
# Question
Title: How to do gear physics
I've realized this gear using primitive.

My object is:

* Main cylinder with with a Rigidbody and a script who rotate Y axis
    + All Prism as child who has MeshCollider

I've got also a pivot for each gear.

The problem is that the right gear not rotate when "prism" collide with others. The collision not happen.

Any ideas ?

Thanks

# Answer
> 2 votes
When you have a rigidbody on a game object, you generally should refrain from manipulating its `transform` directly. Doing so confuses the physics engine, because you are literally teleporting the object around.

If you want to manipulate the object, use the methods of `rigidbody` instead. If you want the object to turn, use `rigidbody.AddTorque`.

By the way: If gear physics are a central game mechanic of your game (like in a mechanical puzzle game) you might want to implement them yourself instead of relying on the Unity physics engine. Having so many small physics object in the scene with interactions which matter for the gameplay is going to end in a disaster.

---
Tags: unity, physics
---


# Question
Title: How do you use these kind of rpg ground tileset ?
Searching about some tilesets for a little RPG game, I've often found these kind of tileset :

Their structure are special, there is two upper tile and 4 others for the same material. I understand that, like that, you have all what you need to create more various shapes than simple rectangles of different sizes. But I don't get how they are used in practice. I'm talking about the two little upper tiles that are used to make some corners. for me the 4 corners are stored inside only one tile ? (hard to explain with my bad english but I'm sure you understand what I mean)

Also, do you know if that tilemapping technic has a name ? And do you kown if it is possible to use them directly in Tiled ?

# Answer
> 2 votes
This tileset is famous because it was used in RPG maker VX. It seemingly consists of 6 tiles (2 by 3) and it even outputs tiles in that size, but it actually handles the tileset as if it was 4 by 6:

You can then create every tile combination you need (which is 48 in most cases, source here, see the "The blob" section)

For instance, creating a tile, that has grass on the left and right side would look something like this:

Whether you unpack the tileset at start to a better format or deal with drawing 4 sub-tiles each time depends on your preferences.

However, keep in mind that most great tilesets try to make the grid-like nature of these games invisible to the player, but since you don't have much space to work with in an RPG make VX type tileset, the details will suffer.

# Answer
> 1 votes
These are "Auto Tiles" for the RPGMaker game engine.

While the map editor uses 32x32 tiles as a basic logic unit, the engine actually splits the tiles into 16x16 tiles. The map editor then automatically uses the sub-tiles to generate the fitting transitions. This allows the mapper to draw with just one material while the map editor automatically creates the correct edge- and corner tiles.

Example:

---
Tags: tilemap, rpg, tiled, tiles, tilesets
---


# Question
Title: whats the difference between the two switches in rpg maker mv?
I dont understand what is the difference between the top and bottom set of switches in rpg maker mv. Can someone please explain?

# Answer
> 3 votes
There are no differences between them, there are two because you may need more than just one *switch*-based condition for your map events.

For example, you don't need to use a *switch* and a *variable* when a simple second *switch* would be enough - and there it is.

From the manual (here's an online version), in the *RPG Maker MV \> Events \> Map Event Settings* section:

> ### Conditions
>
> \[...\]
>
> \[...\] If multiple conditions are set, an event will only occur when all conditions are met.

Since you can select any condition you need, you can even pick the second *switch* condition only, it will work as if you chose the first one.

---
Tags: rpg-maker-mv
---


title: Calculate Player Level in PHP

text:
# Question
Title: Calculate Player Level in PHP
So in my program, I currently know how much Experience a player has. I was using this formula to figure out what level the Player was:

```
function calcLevel($XP,$const){
     $L = sqrt($XP)*$const;
     return floor($L+1);
}

```

Then I wanted to figure out what Percentage of the way the player was to the next level, so I needed to figure out how much Experience they needed to get to that point. I thought this would work:

```
function xpNeeded($L,$const){
    $XP = pow($L,2)/$const;
    return $XP;
}

```

I would also need to know how much previous Experience the player had earned in other levels so I could calculate the percentage based on the Experience earned at the current level only:

```
function prevXP($L,$const){
    $XP = 0;
    for($i=1;$i<$L;$i++){
        $XP = $XP + xpNeeded($i,$const);
    }
    return $XP;
}

```

This all made sense to me, but the calculations are a bit off.

For instance, using Level 2, and Constant of .1:

```
$const = .1;
$lvl = 2;
$a = xpNeeded($lvl,$const); //returns 40
$b = prevXP($lvl,$const); //returns 10
$c = $a+$b; //50
calcLevel($c,$const) //returns 1, should return 2

```

I can't really tell where my calculations have gone wrong, obviously, it is in the xpNeeded function, I just do not know what I did wrong.

# Answer
> 0 votes
**Disclaimer**: I went on a tangent from `xpNeeded` and `prevXP` because they were confusing me and they were not working anyway. Instead I focused on how to go from the function to compute the level to know how much progress the player is doing to the next level.

---

## Basic functions

Starting by the function you have for the level:

```
function calcLevel($XP, $const){
     $L = sqrt($XP)*$const;
     return floor($L+1);
}

```

**Note**: I assume that 1 is there because we count level from 1 and not from 0. That is, when a player has 0 XP, that is level 1 instead of level 0.

I will write it like this:

```
function calcLevel($XP, $const){
     $L = floor(1 + sqrt($XP)*$const);
     return $L;
}

```

We should be able to figure out a formula that given the level gives you the XP back. It should be the inverse formula...

So, we have that

```
L = [1 + sqrt(XP)*c]

```

I will ignore the floor function. You can add a floor call to ensure the level is integer. So...

```
L = 1 + sqrt(XP)*c

=>

L - 1 = sqrt(XP)*c

=>

(L - 1) / c = sqrt(XP)

=>

((L - 1) / c)^2 = XP

```

Thus

```
function calcXP($L, $const){
    $XPsqrt = ($L - 1) / $const;
    $XP = $XPsqrt * $XPsqrt;
    return $XP;
}

```

Note that gives you the XP to get from 0 XP to the level you input.

---

## Experience to the next level

If you want to know how much the player needs to get to the next level, having the xp as input, you do this:

```
function xpToNextLevelFromXP($XP, $const){
    $L = calcLevel($XP, $const);
    return calcXP($L + 1, $const) - $XP;
}

```

What we are doing here is computing how much XP the player needs to get from 0 XP to the next level and substract the XP the player already has.

If you want to inline and simplfy the function, it looks like this:

```
function xpToNextLevelFromXP($XP, $const){
    $L = floor(1 + sqrt($XP)*$const);
    $XPsqrt = $L / $const;
    return ($XPsqrt * $XPsqrt) - $XP;
}

```

However, if you have the level instead of the XP, you do this instead:

```
function xpToNextLevelFromLevel($L, $const){
    return calcXP($L + 1, $const) - calcXP($L, $const);
}

```

Or inlined:

```
function xpToNextLevelFromLevel($L, $const){
    $XPNsqrt = ($L) / $const;
    $XPsqrt = ($L - 1) / $const;
    return ($XPNsqrt * $XPNsqrt) - ($XPsqrt * $XPsqrt);
}

```

---

## Progress to the next level

If you want to know how much XP the player has in the current level you can do this:

```
function xpInLevel($XP, $const){
    $L = calcLevel($XP, $const);
    return $XP - calcXP($L, $const);
}

```

That is, we substract from the XP the player has, how much XP is needed to get to the current level. Of course, you can work out the percentage progress to the next level from the current one using the functions above:

```
function progressLevel($XP, $const){
    $total = xpToNextLevel($XP, $const);
    $current = xpInLevel($XP, $const);
    return $current / $total;
}

```

The above function should return a value between 0 and 1 which represent the progress. Multiply by 100 for display as percentage.

We can, inline the functions, and remove the redundant call to `calcLevel`:

```
function progressLevel($XP, $const){
    $L = calcLevel($XP, $const);
    $total = calcXP($L + 1, $const) - $XP;
    $current = $XP - calcXP($L, $const);
    return $current / $total;
}

```

---

## Approaching your example

To be honest. As I said at the start, `xpNeeded` and `prevXP` confuse me. Futhermore, I do not understand your example. Anyway, here is an approximation:

```
function calcXP($L,$const){
    $XPsqrt = ($L - 1) / $const;
    $XP = $XPsqrt * $XPsqrt;
    return $XP;
}

function calcLevel($XP,$const){
    $L = floor(1 + sqrt($XP)*$const);
    return $L;
}

function xpToNextLevelFromLevel($L, $const){
    $XPNsqrt = ($L) / $const;
    $XPsqrt = ($L - 1) / $const;
    return ($XPNsqrt * $XPNsqrt) - ($XPsqrt * $XPsqrt);
}

$const = .1;
$lvl = 2;
$a = xpToNextLevelFromLevel($lvl,$const); // 300
$b = calcXP($lvl,$const); // 100
$c = $a+$b; // 400
$r = calcLevel($c,$const); // 3

```

This tell us that:

* From level 2 to level 3 you need 300 XP.
* To get to level 2 (from level 1, which is the starting point, a.k.a 0 XP) you need 100 XP.
* If you have 300 XP + 100 XP = 400 XP, you are in level 3 (which is the next level after level 2).

---
Tags: php
---


# Question
Title: How can I animate/draw a line renderer over a given period of time
I have created a line renderer using the code below:

```
public class MyLineRenderer : MonoBehaviour {
LineRenderer lineRenderer;

public Vector3 p0, p1;

// Use this for initialization
void Start () {
    lineRenderer = gameObject.GetComponent<LineRenderer>();
    lineRenderer.positionCount = 2;

    lineRenderer.SetPosition(0, p0);
    lineRenderer.SetPosition(1, p1);

    }
}

```

How can I write a coroutine that will animate/draw the line over specific duration, say 2 seconds?

# Answer
> 2 votes
```
LineRenderer lineRenderer;
private float distance;
private float counter;

public Vector3 p0, p1;
public float lineDrawSpeed = 6f;

// Use this for initialization
void Start()
{
    lineRenderer = gameObject.GetComponent<LineRenderer>();
    lineRenderer.positionCount = 2;
    lineRenderer.SetPosition(0, p0);

    distance = Vector3.Distance(p0, p1);

}

void Update()
{

    if (counter < distance)
    {
        counter += .1f / lineDrawSpeed;
        float x = Mathf.Lerp(0, distance, counter);
        var point0 = p0;
        var point1 = p1;

        var pointALongLine= x * Vector3.Normalize(point1 - point0) + point0;

        lineRenderer.SetPosition(1, pointALongLine);
    }

}

```

---
Tags: unity
---


title: Detecting when pathfinding has failed

text:
# Question
Title: Detecting when pathfinding has failed
I have successfully implemented a simple pathfinding routine as described in this Wikipedia article:

https://en.wikipedia.org/wiki/Pathfinding#Sample\_algorithm

I used the "sample algorithm", which starts at the endpoint, words across the grid by hopping to adjacent cells, counting the hops as it goes, and then using the number of hops to track the path back from the start to the end point. It works well, and is fairly fast.

The only problem I have is that the loop for calculating the path never breaks if there is no route to the destination (i.e. if the path is blocked).

I have considered limiting the number of rounds for the calculation; the maximum possible steps on the board will be (rows\*columns)-1, so in a 10\*10 grid, if a path hasn't been found within 99 rounds, there is no path. However, this could be very wasteful, for example if the start point is within a very confined space with only a few possible moves around it.

I'm writing in Cocoa + Objective-C, but I wouldn't have thought that makes a difference, as this seems to be a logical issue rather than one regarding the framework I'm developing in.

# Answer
> 1 votes
And, as is often the case, having typed the problem out and thought for a few seconds, the solution has occurred to me.

The sample pathfinding algorithm ignores un-occupiable positions on the grid, and makes its way across the occupiable positions. It essentially "fills up" the traversable parts of the grid, recording as it goes how many hops away from the destination each cell is.

Once the traversable area has been mapped, no more steps will be possible. When no more steps can be taken, if the destination hasn't been reached, then it is unreachable.

In programming terms, this meant the following. My method for traversing the map was a function which takes as its only parameter an array of grid positions. The first time the function is called, the array contains only one item - the starting position. Each time the function runs through, it looks at all of the positions currently in the array, and for each of them, examines the adjacent cells. Any traversable cells which haven't already been crossed are added to the array, and then the (now larger) array is fed back into the function. The function only returns when one of the found cells is the destination.

I modified this by storing the current number of steps in the array at the beginning of the function. Then, at the end of the function, I compared the number of items now in the array to the number recorded at the beginning.

If the number of steps in the array is the same as before, then no more steps were taken, and the destination must be unreachable.

---
Tags: game-design, game-mechanics, path-finding
---


title: One of my variable won't increase

text:
# Question
Title: One of my variable won't increase
I start learning unity recently and I am using Unity 2017.3.0f3. Now I'm creating a Block Breaker game and I tried to create a way to check win condition and to go to next level. So I write those two variables:

```
public static int BreakableCount = 0;
public int RemindBricks = 0;

```

At start I write this code to count the number of blocks in my scene:

```
 isBreakable = (this.tag == "Breakable");
     if (isBreakable) {
         BreakableCount++;
     }

```

Which works perfectly and after that I set the win condition:

```
void OnCollisionEnter2D (Collision2D col)
     {
         Handlehits ();
         print ("bricks count is= " + BreakableCount);
         print ("remind brick is= " + RemindBricks);
         print ("_______________");
         if (RemindBricks == BreakableCount) {
         SimulateWin();
         }
     }
     void Handlehits ()
     {
         int MaxHit = hitsprites.Length + 1;
         TimeHit++;
         if (TimeHit >= MaxHit) {
             RemindBricks++;
             DestroyObject (gameObject);

   } else {
     LoadSprite();
     }
 }

```

My problem is RemindBricks only increased once and after that it won't increase at all. Here is the result:

And here my entire project to download if you want. So please tell me why my variable won't increase and how to fix it. Thanks.

# Answer
I'm not sure if this is what you were going for but this:

> My problem is RemindBricks only increased once and after that it won't increase at all. Here is the result:

Is solved by making the `RemindBricks` variable static.

After you are increasing the value of RemindBricks, you're deleting the game object and (I think) since your `RemindBricks` is not a static variable, it'll get removed along with the object and will be set to 0 again. Static variables won't be affected.

So in stead of `public int RemindBricks = 0;` try `public static int RemindBricks = 0;`
> 0 votes

---
Tags: unity
---


# Question
Title: Real time lighting in a 2D game with angled camera perspective
The game "Monaco: What is yours is mine", has a nice real time lighting/shading effect as shown in this picture:

Notice how the vision is blocked by obstacles. I would be interested in seeing if this effect could work in a game with angled camera view. There are about a million such games, for example see Stardew Valley:

It is not clear to me if these two graphics styles could be easily combined. I'm looking for examples - either full games or just technical demos, etc. of the Monaco-like lighting effect applied to angled camera perspective (like in Stardew Valley).

# Answer
No, camera methods cannot be *easily* combined, but it is possible. One would have to make a 3d mapping of the area then make a birds view map from the 3d map, then make all of the blocked objects in the 2d bird map be darker in the 3d map, then use the 3d camera like in stardew Valley. BTW, Stardew valley is not actually 3d,it is simply .png's that are made to appear angled.
> 3 votes

---
Tags: 2d, lighting, shading
---


# Question
Title: How to round points to an arbitrary grid on the surface of a cube?
I'm making a PCG game where I have points scattered or projected onto the surface of a cube, which is centered on origin with a "radius" of 1.

That surface is a grid and **I want to associate each point to the center of each proper cell's grid**.

After detecting which face the point is by taking max(x,y,z) I used that formula:

```
halfTileSize * floor (3dpositions * gridDivision)/gridDivision;

```

\[EDIT: everything above work, everything below is useless, the problem was outside influence from obsolete code\]

But it doesn't round the point to the correct grid cell on the surface. There is a problem where front and back don't return the same result, or it skips a row with some condition, and it also rounds to the wrong nearby cells.

I tried to replace the floor with:

```
3dpositions.xyz < 0 ? ceil(3dpositions * gridDivision) : floor(3dpositions * gridDivision)

```

That didn't work either. It seems to work fine on a 2d planes, which I used to conceptualize the formula, but in 3D I'm at loss as to why it wouldn't work, since I basically reduce the problem to 2D anyway...

Any help to create a formula that would round the points properly into the right cell?

# Answer
> 0 votes
There was no problem because the issue was elsewhere, this works perfectly:

> After detecting which face the point is by taking max(x,y,z) I used that formula:

```
halfTileSize * floor (3dpositions * gridDivision)/gridDivision;

```

See the edited Question for more embarrassing details.

---
Tags: procedural-generation
---


# Question
Title: How do I simplify this code with an Array and counting int up in Unity?
I want to simplify my code. I had the idea of making an Array of waypoints\[\] and and int i to count up each time I arrive a new point of waypoint but it should be the same way my code is but instead of waypoint1.position... waypoint3.position I thought it should be like waypoint\[i\].position and it counts up everytime I reach another waypoint this would simplify a lot and would make the code much shorter. The code is for moving an Object from A to B from B to C and so on..

I commented some lines how it would look like but ignore the //MOVE //ROTATE comments

Code:

---

```
public float speed;
public float turnSpeed;

//Starting with these somehow
//public Transform[] waypoints;
//private int i = 0;

public Transform player;
public Transform waypoint;
public Transform waypoint1;
public Transform waypoint2;
public Transform waypoint3;

public bool b0 = true;
public bool b1 = false;
public bool b2 = false;
public bool b3 = false;
public bool b4 = false;

void FixedUpdate ()
{
        if(b0)
        {
            //MOVE
            player.position = Vector3.MoveTowards(player.position, waypoint.position, speed * Time.deltaTime);
            //ROTATE
            var rotation = Quaternion.LookRotation(waypoint.position - player.position);
            player.rotation = Quaternion.Slerp(player.rotation, rotation, turnSpeed * Time.deltaTime);

            float distance = Vector3.Distance(player.position, waypoint.position);
            //Debug.Log (Mathf.Round(distance));
            if(distance <= 1)
            {
                // i++;
                b1 = true;
                b0 = false;
            }
        }

        if(b1)
        {
            //MOVE
            player.position = Vector3.MoveTowards(player.position, waypoint1.position, speed * Time.deltaTime);
            //ROTATE
            var rotation1 = Quaternion.LookRotation(waypoint1.position - player.position);
            player.rotation = Quaternion.Slerp(player.rotation, rotation1, turnSpeed * Time.deltaTime);

            float distance1 = Vector3.Distance(player.position, waypoint1.position);
            //Debug.Log (Mathf.Round(distance1));
            if(distance1 <= 1)
            {
                b1 = false;
                b2 = true;
            }
        }

        if(b2)
        {
            //MOVE
            player.position = Vector3.MoveTowards(player.position, waypoint2.position, speed * Time.deltaTime);
            //ROTATE
            var rotation2 = Quaternion.LookRotation(waypoint2.position - player.position);
            player.rotation = Quaternion.Slerp(player.rotation, rotation2, turnSpeed * Time.deltaTime);

            float distance2 = Vector3.Distance(player.position, waypoint2.position);
            //Debug.Log (Mathf.Round(distance1));
            if(distance2 <= 1)
            {
                b2 = false;
                b3 = true;
            }
        }

        if(b3)
        {
            //MOVE
            player.position = Vector3.MoveTowards(player.position, waypoint3.position, speed * Time.deltaTime);
            //ROTATE
            var rotation3 = Quaternion.LookRotation(waypoint3.position - player.position);
            player.rotation = Quaternion.Slerp(player.rotation, rotation3, turnSpeed * Time.deltaTime);

            float distance3 = Vector3.Distance(player.position, waypoint3.position);
            //Debug.Log (Mathf.Round(distance1));
            if(distance3 <= 1)
            {
                b3 = false;
                b4 = true;
            }
        }
}

```

# Answer
> 1 votes
Hope this helps

```
public float speed;
public float turnSpeed;

public Transform player;

public Transform[] waypoints;
private int currentlyActive = 0;

void FixedUpdate ()
{
    if(waypoints.Length >= currentlyActive)
    {
        return;
    }
    waypoint = waypoints[currentlyActive];
    player.position = Vector3.MoveTowards(player.position, waypoint.position, speed * Time.deltaTime);
    var rotation = Quaternion.LookRotation(waypoint.position - player.position);
    player.rotation = Quaternion.Slerp(player.rotation, rotation, turnSpeed * Time.deltaTime);

    float distance = Vector3.Distance(player.position, waypoint.position);
    if(distance <= 1)
    {
        currentlyActive++;
    }
}

```

Haven't tested it in unity but it should be the transformation you asked for.

I recommend looking at how others have solved this problem. Often you can see APIs or programming techniques you don't know yet.
Also there are many C# or Unity Books :)

---
Tags: unity, c#, rotation, movement, waypoints
---


# Question
Title: NullReferenceException when accessing variables in a 2D array in Unity
I have made a class including variables in Monodevelop which is:

```
public class GridInfo : MonoBehaviour {

    public float initPosX;
    public float initPosY;
    public bool inUse;
    public int f;
    public int g;
    public int h;
    public GridInfo parent;
    public int  y,x;
}

```

Now I am using its class variable in another class, Map.cs which is:

```
public class Map : MonoBehaviour {

    public static GridInfo[,] Tile = new GridInfo[17, 23];

    void Start() {

        Tile[0,0].initPosX = initPosX;  //Line 49
    }
}

```

I am not getting any error on runtime, but when I play in unity it is giving me error

```
NullReferenceException: Object reference not set to an instance of an object
Map.Start () (at Assets/Scripts/Map.cs:49)

```

I am not inserting this script in any gameobject, as Map.cs will make a GridInfo type array, I have also tried using variables using GetComponent, where is the problem ?

# Answer
I dont understand Unity and MonoDevelop, bud I think, you don't have objects in array intialized. You created array, but objects in it are null. You have to call new GridInfo on each of them.

Somethink like:

```
foreach (GridInfo gi in Tile) // I now don't know, if this goes over 2D array too
{
   gi = new Grid();
}

```
> 4 votes

# Answer
To give an alternative to zacharmarz's answer:

The way that I think you intend to use the `GridInfo` is possible, if you change it to a `struct` instead of a `class`. If you do, then you can't inherit from MonoBehaviour, but I think that you might do that unintentionally because Unity automatically inserts that code when creating the script. Since the GridInfo is just a *structure* of multiple public data fields, it is well suited for using a struct.

Note that I'm not sure if it is possible to have a struct of the same type inside the struct, as in the case of the field `parent`.

It would look like this:

```
public struct GridInfo {
    public float initPosX;
    public float initPosY;
    public bool inUse;
    public int f;
    public int g;
    public int h;
    public GridInfo parent;
    public int y,x;
}

```

Then a 2D-array of structs will automatically contain the structs with all their fields. There are no nullpointers of type struct.
> 0 votes

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


# Question
Title: Simulate parallel dimensions / subspaces in Unity without colliding coordinate systems
I've built an online game with Unity with a very large open world. The server (which can be a local player, or run as a standalone application without a local player) simulates everything around players - so for example if there is an object or NPC at coordinates (100,34,20) but there aren't any players nearby then the object is not simulated. Objects are streamed dynamically from a database or generated procedurally depending on the object.

## Problem

I want to enable players to go to other worlds. Of course it is impractical if not impossible to have global coordinates shared across all of these different worlds due to floating point limitations. I'll have to share the limited coordinate system for each simulated world.

The issue is the server would still need to render and handle physics of multiple worlds but could now potentially have conflicts with objects and/or people on one world appearing in other worlds. Essentially I need a way to divide up these "worlds" into parallel dimensions that are executed simultaneously on the same server (in one Unity scene).

## Parallel Dimensions

A partial solution would be to have some sort of indicator, such as an integer (I'll call it "worldIndex") on each object to indicate which "world" that object exists in. This would work for clients since the server would be able to tell the clients only about objects that are on their world.

There would still be a problem on the server itself. Every world needs to be simulated in the same coordinate space. For a local player I could use the "worldIndex" to hide objects that aren't in the local player's current "world". But I still need to simulate physics for every world.

Unity's Layers could be used to mask physics interactions between objects. However I would then need to have at least one layer per world - and I already use multiple layers for various different interactions.

My thoughts are I would need something like a layer I could specify on each GameObject or some way to group a bunch of GameObjects together and instruct the physics system to only allow interactions within the group. But as far as I know no such mechanism exists within Unity.

## Subspace Pockets

Another thought I've had is rather than using the Unity coordinate space directly, I could slice it up into "subspaces" or pockets. Each player would be in their own subspace, unless a player physically enters the same space that is already being simulated by another player, in which case that player would join the same subspace. But then I would have shift around the coordinate systems and it would increase complexity of merging players into and out of these subspaces. I would also have to generate subspaces dynamically as players enter new areas that are not currently being simulated.

Even if each world is extremely large, it is not necessary to use the entire Unity coordinate system around each player - a few thousand kilometers is more than enough.

Overall I think something along these lines is probably the best solution.

## Multiple Servers

I could run one server per "world" and have a hand off process to make it transparent to players. But then I'd have to run multiple server instances and players would not be able to host their own server - at least not without a lot of additional overhead.

## Question

So my question is: what is the best method for essentially running multiple, parallel simulations within a single Unity scene?

# Answer
You want to look into two things:

1. How to make portals in unity
2. Non-Euclidean geometry in video games.

The mathematics is too much to go into here, but the basic idea for alternate dimensions is that you create a *basis matrix* which will allow a mapping of sorts between any point in the main game world, and any point in dimension x. So when someone translates between the real world, their position is transformed into the coordinate system of dimension x.

In order to allow translation, you need *portals*. Portals are artefacts, if you look at the game, Portal, which not only translate to other places, but also provide a view of that other place. That's done by some simple rendering tricks, but is outside the scope of this answer.

The portal itself is nothing more than a triggered event, which the script will get the new world, or dimensions basis matrix, transform the players current position, and then place the game entity into the world at the new location.

In such a way, you could have a world that is considerably smaller, or larger in dimensions than the real world, and use it for say, fast travel (like hyper space).

Non-Euclidean geometry is far too complex a subject to go into here, so on that subject I will simply say go read up on it.
> 2 votes

---
Tags: unity, c#, physics, architecture, mmo
---


# Question
Title: How can I set gl_Position's w component to 1?
In my vertex shader, I'd like to set the w component to 1.

How can this be done, after

```
gl_Position =  MVP * vec4(vertexPosition_modelspace, 1);

```

# Answer
> 4 votes
You can use swizzles to access specific coordinates in the vector.

`gl_Position.w = 1.0;`

---
Tags: opengl
---


# Question
Title: Splitting a character model to ease animations
I've recently been looking into animations within Unity, and came across the idea of splitting my humanoid character's object into two at the waistline. The Idea being that animations used for movement can be applied to the legs, without interfering with general upper body animations/stances (and vice versa). Is this a viable option and would there be any adverse effects from doing this?

Also, is there any real need? I've noticed Unity is quite flexible when it comes to animations, but am unsure whether unity would be able to handle this? My main issue is different weapon types, where I would like the hands in different idle positions, but without having to have 4 or 5 different running forward animations.

# Answer
> Is this a viable option and would there be any adverse effects from doing this?

Yes, it's viable, although in my experience it's usually better done as "full body" and "upper-body only" animations rather than a hard split between independent upper and lower body animations.

The reason (and thus the main disadvantage of this approach) is that a human body doesn't actually have a hard split at the waist, and the physics of the body act to prevent (or make difficult, depending on one's flexibility) certain anatomical configurations that would be trivially constructible in a system you're proposing.

Thus, you often end up wanting to build some kind of blending mechanism to smooth out or otherwise control and prevent the unnatural configurations, and it seems easier and more natural to do that by blending upper-body-only animations over full-body ones using various calculations for weight.
> 2 votes

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


# Question
Title: How can I add up the Transform/GameObjects in the Array of Waypoints in Unity?
I come up with this code and I try to get the waypoint + 1 when I reach the waypoint and it adds up till the last waypoint. I get Array is out of Index error. I guess I need and foreach loop of waypoints ?

Code:

---

```
public float speed;
public float turnSpeed;

public Transform[] waypoints;
private int currentWp = 0;

void FixedUpdate ()
{

    if(waypoints.Length >= currentWp)
    {
        return;
    }

    player.position = Vector3.MoveTowards(player.position, waypoints[currentWp].transform.position, speed * Time.deltaTime);

    var rotation = Quaternion.LookRotation(waypoints[currentWp].transform.position - player.position);
    player.rotation = Quaternion.Slerp (player.rotation, rotation, turnSpeed * Time.deltaTime);

    float distance = Vector3.Distance(player.position, waypoints[currentWp].position);

    if(distance <= 10)
    {
        currentWp++;
    }
}

```

# Answer
> 1 votes
Your test `if(waypoints.Length >= currentWp)` is backwards.

You want `if(currentWp >= waypoints.Length)` (ie. "Bail out if we've already reached the last waypoint")

---
Tags: unity, c#, rotation, movement, waypoints
---