# Question
Title: Unity: Change the type of a Texture2D to "Normal map" through script
I am making procedural terrains through c# script, and while I achieve to produce a *texture*, a *heightmap* and a *normalmap* to `Texture2D`, it seems they are not being applied correctly to the material.

* the texture (albedo) is applied
* the noise map is applied (but as a "default" texture, I think?)
* the heightmap is not even selected

The trick I currently use is to also save the Texture2D to files. After generation I manually affect the file normalMap and it goes fine. But you'll understand this is not satisfactory, I want the script to set the normal map correctly.

I suspect this is because the file's `texture type` is force to *normal map*. But I cannot see how I can change the type of an in-memory Texture2D through code.

Researches gave nothing fitting my concerns, any help will be appreciated. Thanks:)

\[EDIT\] I tricked by passing a pre-made normal map as parameter, to use instead of the one I generate. Guess what? It works instantly.

# Answer
Nevermind, the fact is you have to apply with a different name:

```
material.SetTexture("_BumpMap", normalMap);
material.SetTexture("_ParallaxMap", heightMap);

```

Why, would you ask? No sé, gringo. Anyway, I could have the full list of properties by switching the inspector to debug mode.
> 1 votes

---
Tags: unity, procedural-generation, procedural, normal-mapping, bump-map
---


# Question
Title: Midpoint displacement generating unsatisfactory terrain
Following this lesson for implementing mid-point displacement algorithm for terrain generation. I aim at generating a wavefront(obj) file of the terrain

I have an array of dimension (2^n + 1) x (2^n + 1). The corners of the 2d array is initialized with random numbers.

```
n = plug_in_n
arr = Array.new(2**n + 1) { Array.new(2**n +1) { 0 } }
n_augmented = 2**n

arr[0][0] = rand(10 + 1)
arr[0][n_augmented] = rand(10 + 1)
arr[n_augmented][0] = rand(10 + 1)
arr[n_augmented][n_augmented] = rand(10 + 1)

```

This is the script I have written for generating a terrain.

```
a = arr
n_augmented_copy = n_augmented
while n_augmented > 1

puts "n_augmented = " + n_augmented.to_s
i = 0
while(i < n_augmented_copy)
    j = 0
    while(j < n_augmented_copy)
        a[i][j+(n_augmented)/2] = (a[i][j] + a[i][j+n_augmented]) / 2.0  + (rand 0.0..1.0)
        a[i + (n_augmented) / 2][j + n_augmented] = (a[i][j + n_augmented] + a[i + n_augmented][j + n_augmented]) / 2.0 + (rand 0.0..1.0)
        a[i + n_augmented][j +( n_augmented) / 2] = (a[i + n_augmented][j] + a[i + n_augmented][j + n_augmented] )/ 2.0 + (rand 0.0..1.0)
        a[i + (n_augmented) / 2][j]  = (a[i + n_augmented][j] + a[i][j] )/ 2.0 + (rand 0.0..1.0)
        a[i + (n_augmented) / 2][j +( n_augmented) / 2] = ((a[i][j+(n_augmented)/2] + a[i + (n_augmented) / 2][j + n_augmented] + a[i + n_augmented][j +( n_augmented) / 2]  + a[i + (n_augmented) / 2][j]))/ 4.0  + (rand 0.0..1.0)
        j = j + n_augmented
    end
    i = i + n_augmented
end
# binding.pry
# p_arr(a)
n_augmented = n_augmented / 2

```

end

Demonstrating a case for n = 2: I have omitted the random-displacement `rand 0.0..1.0`to check if the heightmap chucks are getting calculated fine.

Here is how the iterations look like

```
n_augmented = 4
    9     0   5.5     0     2
    0     0     0     0     0
  6.5     0   5.5     0   4.5
    0     0     0     0     0
    4     0   5.5     0     7
n_augmented = 2
    9  7.25   5.5  3.75     2
 7.75 6.625   5.5 4.375  3.25
  6.5   6.0   5.5   5.0   4.5
 5.25 5.375   5.5 5.625  5.75
    4  4.75   5.5  6.25     7

```

If I form a mesh using this alone, it results in a plane like:

Considering the random displacement for this case, it results in :

For n = 5, It looks like :

This is not desirable since I cannot see any peaks and slopes.

Here is the ruby script : CODE

# Answer
> What you probably want to do is to start with a random value between 0 and 10, and then cut the range in half on each iteration. So on the 2nd iteration, the range of random values would only be between 0 and 5. On the 3rd iteration it would be between 0 and 2.5, etc. That should get you something with peaks and valleys.

Thanks for this step. Here is my updated source if it helps anyone and here is the result:

```
def p_arr(arr)
    width = arr.flatten.max.to_s.size+2
    for i in (0..arr.length - 1)
        for j in (0..arr.length - 1)
            print arr[i][j].to_s.rjust(width + 2) + " "
        end
        puts ""
    end
end
def getrnd(range)
    rand -range.to_f..range.to_f
end

n = 8
arr = Array.new(2**n + 1) { Array.new(2**n +1) { 0 } }
n_augmented = 2**n
arr[0][0] = rand(10 + 1)
arr[0][n_augmented] = rand(10 + 1)
arr[n_augmented][0] = rand(10 + 1)
arr[n_augmented][n_augmented] = rand(10 + 1)

a = arr
n_augmented_copy = n_augmented
range = 50.0
while n_augmented > 1
    i = 0
    while(i < n_augmented_copy)
        j = 0
        while(j < n_augmented_copy)
            a[i][j+(n_augmented)/2] = (a[i][j] + a[i][j+n_augmented]) / 2.0  + getrnd(range)
            a[i + (n_augmented) / 2][j + n_augmented] = (a[i][j + n_augmented] + a[i + n_augmented][j + n_augmented]) / 2.0 + getrnd(range)
            a[i + n_augmented][j +( n_augmented) / 2] = (a[i + n_augmented][j] + a[i + n_augmented][j + n_augmented] )/ 2.0 + getrnd(range)
            a[i + (n_augmented) / 2][j]  = (a[i + n_augmented][j] + a[i][j] )/ 2.0 + getrnd(range)
            a[i + (n_augmented) / 2][j +( n_augmented) / 2] = ((a[i][j+(n_augmented)/2] + a[i + (n_augmented) / 2][j + n_augmented] + a[i + n_augmented][j +( n_augmented) / 2]  + a[i + (n_augmented) / 2][j]))/ 4.0  + getrnd(range)
            j = j + n_augmented
        end
        i = i + n_augmented
    end
    range = range / 2
    n_augmented = n_augmented / 2
end

board = n_augmented_copy + 1
c = 0
k = board + 1
#Print vertices
File.open("mountain.obj", 'w') { |file|
    for i in 0..a.length - 1
        for j in 0..a.length - 1
            file.write("v " + j.to_f.to_s + " " + a[i][j].to_f.to_s + " " + i.to_f.to_s+ "\n")
        end
    end

    for i in 0..a.length - 2
        for i in 0..a.length - 2
            file.write("f " + (c + i + 1).to_s  + " " + k.to_s + " " + (c + i + 2).to_s + "\n")
            file.write("f " + (c + i + 2).to_s + " "  + (k).to_s + " " + (k+1).to_s  + "\n")
            k=k+1
        end
        k = k +1
        c += board
    end
}

```
> 1 votes

# Answer
The magnitude of your random displacement is not changing appropriately. For your initial points, you're using a random value between 0 and 10. But for the subdivisions you're only using a random value between 0 and 1.

What you probably want to do is to start with a random value between 0 and 10, and then cut the range in half on each iteration. So on the 2nd iteration, the range of random values would only be between 0 and 5. On the 3rd iteration it would be between 0 and 2.5, etc. That should get you something with peaks and valleys.

Once you have that, you can increase the Y scale to make the peaks taller or valleys deeper, or decrease it to reduce the range.
> 3 votes

---
Tags: mathematics, graphics, terrain, graphics-programming, terrain-rendering
---


# Question
Title: How is background of 2.5d games developed
When I say 2.5d games, I mean like this:

Bloodstained Ritual of the Night DEMO gameplay

My question is, I know the characters and platforms are 3d but are the backgrounds all 3d as well? Even if its not interacted on in any way? Like for example, at 10:45, did the developer(s) make models of the cannons at the background? Or 48:30, did they model the houses?

For context, I'm starting a hobby project game in 2.5d and I'm trying to get an idea on how I would develop the backgrounds.

# Answer
> 3 votes
Yes, both of these seem to be 3d models rendered in real-time. If they were pre-rendered or hand-drawn 2d textures, then it wouldn't be possible to see the cannons from different angles while the camera moves. And if the house was just a static background texture, then it wouldn't be possible to cast dynamic perspective shadows onto it.

Objects which are so far in the background that the perspective doesn't change and that they do not have any light or shadow interactions with dynamic objects *might* be pre-rendered. For example, the wooden mast in the center of this section seems to be a pre-rendered 2d object. But it's hard to tell from video alone what background details are actual geometry and what details are just painted onto flat textures.

In general, the further something is away, the less it moves and the less light/shadow interactions you have with it, the more cheating you can get away with.

---
Tags: 3d, platformer, 2.5d
---


# Question
Title: How can I use pan gestures to zoom a camera in and out
I have the following scene tree for my player:

They have a `Camera2D` as a child, which has a script attached to it. How can I make the camera zoom in and out as I pan on e.g. a MacBook trackpad?

# Answer
You can zoom a camera in and out by handling the `InputEventPanGesture` input event:

```
extends Camera2D

var maximum_zoom_in = 0.15
var minimum_zoom_out = 4
var zoom_sensitivity = 0.01

func _unhandled_input(event):
    if event is InputEventPanGesture:
        var zoom_amount = event.delta.y * zoom_sensitivity
        var new_zoom = zoom.y + zoom_amount
        if (new_zoom < maximum_zoom_in):
            new_zoom = maximum_zoom_in
        elif (new_zoom > minimum_zoom_out):
            new_zoom = minimum_zoom_out
        zoom = Vector2(new_zoom, new_zoom)

```
> 1 votes

---
Tags: 2d, camera, godot
---


# Question
Title: For creating a distant moon in a 3D game, is it better to use a model or texture?
I'm working on my indie game and I want to create a moon (it's a 3D game) however I am unsure if I should create a model and put it far away, or if I should use a texture on a plane and have it constantly move so the face of the plane is facing the player.

The problem I had last time I tried a model is the render view, as the model was really far away (as when I did it very small, you could sort of tell it was a tiny model rather then a far-away moon) and with the texture I'm not sure if it comes across as tacky.

I'd really like to hear the pros and cons of each, since I'm planning to use the 'render objects only when in view' method and basically want advice on which I should go with.

# Answer
> 2 votes
At moon distance/scale, you're unlikely to be able to see any benefit from a 3D model. Especially if the moon is tidally locked like ours is (only one side visible from the ground)

A textured polygon may give you some advantages even, because it makes it easier to antialias the edges, or add a glow/halo.

The moon's phases might be easier to tackle with a 3D object illuminated from different angles, but you can accomplish the same effect with a normal map.

If your moon does rotate, then a 3D object could be worthwhile, so you can simply spin it rather than faking it with a scrolling masked texture or more complicated sampling logic.

To ensure you don't hit draw distance problems with either version, keep it fairly close to the camera in reality, but use a shader to always draw it at max depth. In the same shader, you can neutralize the camera's translation, so the object shows no parallax as you move the camera that might make it look closer than optical infinity.

---
Tags: unity, textures, 3d-modeling
---


# Question
Title: Player fly's off of canvas when key pressed
I am fairly new to game development. I am programming a basic JavaScript canvas game. Whenever I press a key my player goes flying off of the canvas. Here is the controller code

```
document.onkeydown = function(event){
    if(event.keyCode === 87){
        player.up = true;
    }
    else if(event.keyCode === 83){
        player.down = true;
    }
    else if(event.keyCode === 65){
        player.left = true;
    }
    else if(event.keyCode === 68){
        player.right = true;
    }
}

document.onkeyup = function(e){
    if(e.keyCode === 87){
        player.up = false;
    }
    else if(e.keyCode === 83){
        player.down = false;
    }
    else if(e.keyCode === 65){
        player.left = false;
    }
    else if(e.keyCode === 68){
        player.right = false;
    }
}

if(game.keys && game.keys[87]){
        player.speedY += -0.4;
        if(player.speedY > player.maxSpeed){
            player.speedY = player.maxSpeed;
        }
    }
    if(game.keys && game.keys[83]){
        player.speedY += 0.4;
        if(player.speedY > player.maxSpeed){
            player.speedY = player.maxSpeed;
        }
    }
    if(game.keys && game.keys[65]){
        player.speedX += -0.4;
        if(player.speedX > player.maxSpeed){
            player.speedX = player.maxSpeed;
        }
    }
    if(game.keys && game.keys[68]){
        player.speedX += 0.4;
        if(player.speedX > player.maxSpeed){
            player.speedX = player.maxSpeed;
        }
    }

```

The above is the controller code... What improvements should be made on the above code.

*edit* I realize you may need to see the entity creation code

```
function square(width, height, color, x, y) {
  this.width = width;
  this.height = height;
  this.x = x;
  this.y = y;
  this.speedX = 0;
  this.speedY = 0;
  this.right = false;
  this.left = false;
  this.up = false;
  this.down = false;
  this.rend = function(){
    ctx = game.context;
    ctx.fillStyle = color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
  this.movement = function() {
    this.x += this.speedX;
    this.y += this.speedY;
  }
}

```

*edit* max speed integration.

```
  var now = Date.now();
  var delta = now - lastUpdate;
  lastUpdate = now;
  this.width = width;
  this.height = height;
  this.x = x;
  this.y = y;
  this.angle = 0;
  this.maxSpeed = 3;
  this.speedX = 0;
  this.speedY = 0;
  this.rend = function(){
    ctx = game.context;
    ctx.fillStyle = color;
    ctx.globalAlpha = 1;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
  this.movement = function() {
    this.x += this.speedX;
    this.y += this.speedY;
}
}

```

*edit*added player making function.

# Answer
After a couple of hours of trying to solve this issue I came up with this

```
function moving() {
     if(game.keys && game.keys[87]){
        player.speedY = -2;
    }
    else if(game.keys && game.keys[83]){
        player.speedY = 2;
    }
    else if(game.keys && game.keys[65]){
        player.speedX = -2;
    }
    else if(game.keys && game.keys[68]){
        player.speedX = 2
    }else{
        player.stop();
    }
}

this.stop = function(){
    this.speedX = 0;
    this.speedY = 0;
  }

```

Basically, I check that none of those keys were pressed then say player speed X is 0 and speed Y is 0.

Thank you to all the commentators who helped!
> 1 votes

# Answer
I'm pretty sure I know what's wrong with your code. (Now I really hope I didn't make some stupid mistake myself).

You properly check whether the control buttons are pressed and you store that info. However! In the "movement" part of the code, you add speed in the same direction... plenty of times. (once each frame, which might be 60 or more times per second). You can imagine how quickly that scales up. You do the same thing in the later part of the code. You modify position by speed, but you do it every frame.

Imagine this: you want your player to move 10 meters per second. So you set up the speed to 10 - and then you move him, also by 10 in a method. But the code doesn't care about seconds that much, it will try to move whole 10 meters in one frame, which at 60fps is 600 meters per second!

What you would like to do is somehow check something called delta time. I don't know how to do it in javascript, but every game engine has something like that built in. You might look it up or experiment with checking the framerate?

```
deltaTime = 1 / framerate;

```

Then do this:

```
this.movement = function() {
    this.x += this.speedX * deltaTime;
    this.y += this.speedY * deltaTime;
  }

```

that should help with the biggest issue. I see a smaller problems that can emerge in your game.

```
 if(player.up == true){
    player.speedY += -1;
}

```

The way you add speed here is a good idea, but in the long run you might encounter some issues.

You are not checking for max speed. You are not using delta time, so again your acceleration might go crazy (also it will be too framerate dependant, so players with faster computers can have unfair advantage!).

And if you could add "decay". In other words, if the player isn't actively adding speed, you might want to slow down a bit. Otherwise, you will never really "stop". Your speed will go to some number like 15, so you press the opposite direction, but you will never hit exactly 15, so you will end up with speed of -2... you know what I mean?
> 1 votes

---
Tags: 2d, javascript, html-canvas
---


# Question
Title: How to change the version code in application created by the GameMaker?
Code that I can not change:

Image of the error:

Inside the red square is written: `Upload failed You already have an APK or Android App Bundle with version code 1000000. Use another code.`

It turns out that I do not know how to change. At least not by GameMaker. I've been in the settings, preferences, but I do not think so at all. This tutorial below Google itself is useless. I already contacted, I sent an email to the support for more than 1 week and no response.

https://support.google.com/googleplay/android-developer/answer/7159011?hl=pt-BR

# Answer
> 2 votes
In Global Game Settings, inside the Android/Fire tab within the General section, there is a 3-components field to set the version of the apk. Google Play detects automatically this setting to recognize a version from another.

Each field corresponds to version, subversion and revision number, respectively.

---
Tags: game-maker, google-play
---


# Question
Title: How to make texture for text displaying using SDL ttf with good performance?
In my game, there are many units and for each units there's an information widget attached next to them. I use SDL as the game rendering engine.

I currently want to display their ID for debugging purposes.

However, for each unit, I create a texture with their ID, I render it, then I destroy it.

Needless to say that when there are about 40 units on my screen, the game gets pretty laggy (if its any indication, my game currenly weights 25 MB)

How can I get over this?

# Answer
There are a few ways to do this.

You could render a texture with SDL\_TTF that contains all the characters you want to be able to display, and then use that texture as a spritesheet, and pick characters from there using source rectangles, rendering them next to each other. This is a bit more work since you need to calculate correct character offsets etc.

Another alternative would be to simply cache the textures you render with SDL\_TTF. Something like an LRU-cache with enough space to fit everything rendered during a single frame would do the job. So you would render your texture, save it in the cache, and if it's needed every frame, it won't be destroyed from the cache, until the text is not rendered anymore, and other textures take its place.

I have personally used both approaches, and while the latter one is simpler to implement, the first one has better performance.
> 1 votes

---
Tags: sdl, ttf
---


# Question
Title: How can I get sensor data on iPhone onto a Windows PC? For use as a steering wheel
I am making a Unity game. I want to be able to allow the phone to be used as a steering wheel, as input into the PC game.

Technically, How can I achieve this? Can this be done through bluetooth?

Thanks

# Answer
> 1 votes
You just need to create a server on the computer and a client on the phone. Although this can be done through Bluetooth, in my opinion it's better to use a local connection, since most households have WiFi, but not every computer has a Bluetooth adapter (e.g. desktop computers).

After this it's just basic client-server communication and sensor reading, look up a tutorial in the language you are using.

---
Tags: unity, ios, input, joystick
---


# Question
Title: Why do I get these weird errors when using pow() for my game?
```
/usr/bin/ld: /tmp/ccfm5eKc.o: undefined reference to symbol 'pow@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libm.so.6: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

```

I get this error when trying to use `pow()`. Why?

# Answer
> 2 votes
According to this, you need to add `-lm` to the flags.

This was supposedly fixed in a newer version.

---
Tags: mathematics, c
---


# Question
Title: JavaFX AnimationTimer VS Swing Game Loop
After looking at some code sources out there I noticed Java Swing Games usually create a class implementing Runnable, create a `new Thread` and set up the game loop in the `run()` call.

But JavaFX games seem to simply extend from `Application` and run the game loop in a `new AnimationTimer() { ... public void handle() ... }`

What gives?

# Answer
> 1 votes
`Application` is part of JavaFX and therefore can't be used without it and since a JavaFX app relies on the lifecycle of this class and JavaFX requires a class that extends Application, it would be impossible to not use it when creating programs with the library.

---
Tags: game-loop, javafx
---


# Question
Title: jumping and movement with rigidbody2d.velocity, gravity problem
i'm making a 2d platformer and i move my character with rigidbody2d.velocity swiping up to jump and moving while holding the left or right side of the screen.

the problem is that when i jump and i try to move left or right in the air, my character falls very slowly. i've read that the reason why that happens is because rb.velocity overrides gravity at every frame, is there a way to move left or right in the air with normal gravity?

my full code is

```
{
 Rigidbody2D rb;
public float speed = 1f;
public float jumpforce = 3.5f;
private Vector3 mouseDownPos;
private float startTime = 0f;
public float holdTime = 0.15f;

void Start()
{
    rb = GetComponent<Rigidbody2D >();
}

void Update()
{

 if (Input.GetMouseButtonDown(0))
    {

        mouseDownPos = Input.mousePosition;
        startTime = Time.time;
    }

    if (Input.GetMouseButtonUp(0))
    {

        if ( startTime + holdTime > Time.time & Input.mousePosition == mouseDownPos)// tap
        { Debug.Log("T A P");}

    if (Input.mousePosition.y > mouseDownPos.y + 100 )//jump
        {

            rb.velocity = new Vector2(rb.velocity.x, jumpforce);
        }

    }

    if (Input.GetMouseButton(0) & startTime + holdTime <= Time.time)///move while grounded
    {
        if (Input.mousePosition.x < Screen.width / 2)
        {
            Debug.Log("Left click");
            rb.velocity = transform.right * speed;

        }
        else if (Input.mousePosition.x > Screen.width / 2)
        {
            Debug.Log("Right click");
            rb.velocity = transform.right * speed;

        }

        if (Input.mousePosition.x < Screen.width / 2)/// move while in the air
        {
            Debug.Log("Left click");

            rb.velocity = new Vector2(-speed, rb.velocity.y);

        }
        else if (Input.mousePosition.x > Screen.width / 2)
        {
            Debug.Log("Right click");

            rb.velocity = new Vector2(speed, rb.velocity.y);

        }

    }

}

```

the rigidbody2d of my character is

# Answer
> I've read that the reason why that happens is because rb.velocity overrides gravity at every frame, is there a way to move left or right in the air with normal gravity?

Did you try something simple like preserving the current vertical velocity, and overriding only the part you want to change?

```
// Cache the current velocity to modify it.
Vector3 newVelocity = rb.velocity;

// For left/right input, modify only the x part of the velocity.
if (Input.mousePosition.x < Screen.width / 2)
{
    newVelocity.x = speed;
}
else if (Input.mousePosition.x > Screen.width / 2)
{
    newVelocity.x = -speed;
}

// Apply the modified velocity to our body.
// (If no modification happened, then this just preserves the existing velocity)
rb.velocity = newVelocity;

```
> 1 votes

---
Tags: unity, movement
---


# Question
Title: Camera that pivots in the direction that the player is moving
I'm trying to recreate Rocket League's freeform (non ball-locked) camera, which basically is a camera that follows the player but pivots to allows face the direction the player is moving in (not necessarily facing). Here's a video of Rocket League's implementation for reference: https://www.youtube.com/watch?v=RSpB6ocrIX8&t=37s

What are the main things needed to accomplish this?

# Answer
In UE4 i think you could create this quite easily using either a camera that is independent from the player (in that case you would use LERPs to rotate and move the camera). Spawn the camera in a fixed spot behind the player (but do not parent it to the player) and then rotate it at the player over time with a slight lag. Do the same with position.

Another way would be to use "Boom" to connect it to the player. The first solution you could translate to Unity quite easily, I don't know about the Boom part.
> 0 votes

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


# Question
Title: How can I create the graphical concept for a game?
I don't even know the right formulation for this, but basically, I have got a gameplay idea for a mobile game and now I need to create/develop/decide:

1. The theme of my game (e.g is it space, fantasy, abstract)
2. Color palette for my game.
3. The overall graphical style.

What could be the creative process to figure this out?

p.s. Is the stuff that I've described called graphical concept or art concept or something else?

# Answer
> 4 votes
Just to make it clear, this is no *Tutorial* on how to do it. This is just a way me and a friend went for a game idea he had. It was a long and kind of self invented way to go, but it worked for us. We had some inspiration from the internet, but the creative process was mostly developed by our self. I also try to give an example, in short of course. Second, at first this doesnt seem to answer your question, but later on you might see, that you try to go from step 0.5 to step 4. I just want to help you organize your steps you need to take from the start to the graphic concept.

So before you start going ham on your graphic ideas, you should start out with a general concept of your game. If you only got a good gameplay idea, how do you know what to draw?

Basically write up one page with the general description of your game, the platform, the gapic style, the story, mechanics, scenario etc whatever you can decide on right now. Give it a WIP titel, draw some explanatory pictures if necessary and so on. What is the general setting of your game? Serious, dark, dramatic, funny, silly... and keep it to one page. What genre should it be? Whats the target audience (this was the hardest part for myself).
If you have no idea what to write down for some of these topics, dont mind it. Leave it out for now.

**Example:** *Titel: Vehicular Battles*
*You have control over a vehicle and its crew. You Command your crew by typing commands, send them to their positions or weapons. If an enemy reaches your commander/captain or your vehicle gets destroyed, you loose. The game should be silly and colorful. Also its a mobile game.*

Now, read it and think about it. Does it seem interesting to play? Are there concepts that are contradicting or problematic to each other? You still got plenty of time to change things. You could (and should) ask a friend, what he thinks of it so far. What does he like or dislike so far.

***For Vehicular Combat:*** *Typing on a phone for playing could be problematic, as the keyboard could block most of the screen, also it could be slow or with autocorrect problematic or to easy. We could change it and instead command the crew RTS-Style with tapping and sending them to their places.*

If you think that everything is to your liking, choose one thing you are still missing, like in your example the scenario. Write down a list of every thing you can think off, even if at first its seems impossible to fit to your existing ideas. Think of cool books, films or tv series you like. Sometimes crossing two elements might also be interesting, just because no one has ever thought about it.
Write a list for every aspect your are missing. Then pick one aspect, either by personal preference or at random, and pick something from that corresponding list.
For example you are still missing a scenario, so take the scenario list. Then again pick something interesting or something at random. Would that scenario contradict your already Chosen elements? Or maybe you could cross some scenarios to make it even better.

**Vehicular Battle:** *A fitting scenario could be near-future militaristic combat. Giant tanks battle like ships on land. This would be a problem for a colorful and silly game play. Even a Post-Apocalyptic scenario seems blend, if you think of colors, although possible silly game ideas. But what about prehistoric dino battles, where your cavemen crew rides on bases strapped to dinosaurs. Silly and colorful. Or Steampunk Space Battle with wizards as weapons?*

Did you find one or more of those interesting, mark them, maybe rank them and choose one for the next step. Continue with the next list and do the same. If you cant find a fitting entry in those list, go back to a list before and change it.

I must admit, this was a very strenuous work. Working with a friend helped here, as even if at first something doesnt seem to fit, maybe your friend got an idea that could work out.

So, after you got all this done. Read your updated general concept again. You still can change elements, as long as the new element doesnt contradict an other element.

**Vehicular Combat:** (new Titel: Dinossal Combat)
*Story: You are the mightiest and strongest man of a prehistoric tribes. You tamed dinosaurs to work for you and hunt for you. Your tribe is in constant conflict with other tribes, you so mount giant dinosaurs with wooden fortresses and fight other tribes with their fortress, battle for food or capture* **the females.**.
*Gameplay: Vehicular Combat is a singleplayer game. You build a fortress fitting on a giant dinosaur, you add tribesman as crew and other smaller dinosaurs as weapons. After that you can choose missions with different objectives: Fortress Battle, Food Hunt or Capture the womans. While on mission, you change to a top-down view of the battlefield and you can control your crew in rts style. You can order your crew by clicking (or touching) them and send them to a certain place, weapon or station. Your crew can do some tasks: order the beast to move to a certain point (Dino handler)(insert picture of battle field), your crew can mount weapons or if close enough battle in hand to hand combat. Dinosaur weapons can have different effects, like throwing stones or tribesmen, or grabbing enemy tribesman or something from the ground in close range. Dinosaurs can be damaged and destroyed (freed and in panic). Combat itself is kind of slow at the beginning, but starts to get hectic as enemies get closer, your base dinosaur gets faster in a straight line. After the Mission, you can upgrade your crew, add weapons or train your already added weapon dinosaurs.
You loose a mission, if everyone of your tribesmen die or your fortress dinosaur.
Style: Everything should look super bright, dinos are colorful, you hear cheering drums from off screen, 'uga Buga' when you command your crew and posh dinosaurs talking english. Everything should look super round with few hard edges. Characters should seem vague and with few details, while dinosaurs should have many funny details, like giant tails wrapped around their body (grabber dino) or posing like body builders with one big and one small arm (tosser dinos)*

NOW, you can do your concepts for graphic, gameplay, story etc. You are no longer bound to the one page restriction, but you should keep your page and start a new chapter. Start with the topic you find the most important, then work on the next one and try to keep everything you have already done consistent with what comes next.
Here you should add your concept arts under graphics or style or story or what seems the most fitting, even an own section.. Depending on the style of the game start with drawings of example (concept arts) or add 3D models in T-Pose or other interesting poses.

This is where your second question is answered. Start with the colors, as you already know what your game should become. Cheerful, depressing, stern... these with the addition of the scenario should be enough to work out a color palette.

On addition to the graphic style: Many games combine a certain game play mechanic with the graphic style. Twinstick shooters and side scrollers have mostly giant red blinking bullets to make them noticable and aid the player what to keep track off (imagine a bullet hell game with tiny baryle noticable bullets) On of the best examples is Ikaruga (you can absorb bullets of one color, but not of the other). Ego-shooters need well defined objects and enemies (imagine pixel art enemies on pixel art background without motion). Some games also need color coding for better gameplay, Baba is you and Beat Saber are two good and essential different examples.

---
Tags: game-design, graphics-design
---


# Question
Title: What is causing my 3rd person camera to lose rotation on the z axis?
I've been working on a 3rd person camera on unity for a couple weeks, but I've pretty much hit a wall, specifically to do with my camera's rotation. When I rotate it on its x and y axis it won't have a problem, but when it gets to the z axis (180 degree's on the x axis), it loses the ability to rotate at all. This is the code I've been using:

```
void Start()
{
    //controlls camera relevent to player position
    offset = new Vector3(Player.position.x - 3.0f, Player.position.y + 2.0f, 0);
    offset = transform.position - Player.position;
    localtoworldY = transform.TransformPoint(Vector3.left);

}

void Update()
{
    //need to give proper rotation of the camera around the player
    offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * offset;
    offset = Quaternion.AngleAxis(Input.GetAxis("Mouse Y") * turnSpeed, localtoworldY) * offset;
    transform.rotation = Quaternion.LookRotation(offset, Vector3.up);

    transform.position = Player.position + offset;
    transform.LookAt(Player.position);

    print(transform.rotation);

    // If the y axis go to 6.4 positive, it should stop but not stop working, same as if the camera hits a mesh or terrain.

    // If the camera changes in any direction regardless of x or y axis,player should be able to move relative to
    // the direction that the player is pressing (IE when the player press left, the Homicida malorum will move left regardless of
    // the angle of the camera).

}

```

} Any advice or an explanation as to why this is happening would be much appreciated.

# Answer
> 0 votes
There are several things wrong with this line:

```
localtoworldY = transform.TransformPoint(Vector3.left);

```
1. `TransformPoint` applies the object's translation, so the result of this call will be different depending on where your object is in the scene. To transform a direction (sensitive to rotation but ignoring translation & scale), use `TransformDirection` instead.
2. You're performing it only once, in `Start()`, so it's not updating the direction as the rotation changes. Imagine you've turned around 180 degrees - what was once on your left is now on your right, but your axis of rotation does not reflect this change.
3. The vector it looks like you're trying to get is already available to you as a built-in: `-transform.right`

So you can skip this entirely, and correct the line in `Update()` to:

```
offset = Quaternion.AngleAxis(
             Input.GetAxis("Mouse Y") * turnSpeed,
             -transform.right
         ) * offset;

```

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


# Question
Title: Best C# technique to pass variable from Instantiated object to GameObject
There are lots of instantiated prefabs. Info from it is transmitted while it crosses a trigger zone. Some of these are calculated custom variables.

I can print the custom variables from the instantiated prefabs.

I can get the trigger zone to report standard things like "...transform.position" or "...transform.localEulerAngles", but not stuff I make up. Intellisense seems to see everything I am trying to get, and everything compiles.

What's the best manner to perform this? Here's what I've tried:

Prefabs' Script:

```
public float infoToSend;
 void Update(){
 float infoToSend = 10f //...actually, there's some math here, but it's a float.
}
print("Sender: " + infoToSend); //Works.

```

Receiver Script on Trigger Zone:

```
void OnTriggerStay2D(Collider2D other){

print("Receiver: " + other.transform.position);  //Works Fine.
print("Receiver: " + other.transform.localRotation);  //Works Fine.

float infoReceived = other.GetComponent<PrefabsScript>().infoToSend;
print("Receiver: " + infoReceived);  //Does not work!
}

```

Any help, either fixing this arrangement or directing me to a different method, would be appreciated. Thanks.

Edit to display the solution:

**Corrected Prefabs' Script** *(changed third line down)*:

```
public float infoToSend;
 void Update(){
 this.infoToSend = 10f //...actually, there's some math here, but it's a float.
}
print("Sender: " + infoToSend); //Works.

```

Correct Receiver Script on Trigger Zone:

```
void OnTriggerStay2D(Collider2D other){

print("Receiver: " + other.transform.position);  //Works Fine.
print("Receiver: " + other.transform.localRotation);  //Works Fine.

float infoReceived = other.GetComponent<PrefabsScript>().infoToSend;
print("Receiver: " + infoReceived);  //Does not work!
}

```

*Many thanks, again! There's so many places to begin with, it's tough to find a "Beginner course" to cover everything.*

# Answer
```
public float infoToSend; // This is a public member variable, also called a field.

void Update(){
    float infoToSend = 10f; // This is a local variable that exists only in this function.
}

```

When you start a variable assignment with a type, like `float`, you're telling the compiler, "hey, I'm defining a *new* variable of type `float` here. So, forget about any member variables I might have defined with that name for the time being - as long as we're inside this `Update()` method, the name `infoToSend` will refer to this local variable instead."

(If you did this deliberately, and you *want* to refer to the `infoToSend` at member scope instead of the local `infoToSend` in the method's scope, you can say `this.infoToSend` to specify that you're talking about the member variable)

So, in this case, you've never assigned the value of 10 to your public field. You assigned it only to a local variable, that gets thrown out as soon as the function completes (you'll get a warning from the compiler about this, if you've assigned a variable without ever using it anywhere).

This is called variable shadowing, and it's a fundamental part of the language syntax that's not specific to game development. If you're unfamiliar with the basics of C# syntax, then it might be best to brush up with some introductory tutorials before proceeding.

If you just want to assign a value to a variable you've previously declared, you don't start the line with the type - the compiler already knows the type from its original declaration. So you can just say:

```
infoToSend = 10f;

```

This says "assign the value of 10 to my *existing* variable `infoToSend`, without declaring a new variable at this scope."

---

The foregoing fixes the particular code you wrote, but it's generally considered poor programming practice to expose everything as public variables. When they're public, any code anywhere could modify them, so if you get a bug from the variable holding the wrong value, it's more challenging to track down where it came from. We say techniques like this "increase the surface area for bugs."

So, if you have a strict relationship where your prefab object publishes this data, and other scripts consume it, you should enforce that relationship in your code.

A classic way is to make a getter function:

```
float infoToSend;
public float GetInfo() { return infoToSend; }

```

Now only this script can change `infoToSend`'s value, while anyone can read it. This is so popular, C# has a shorcut for writing this kind of relationship, through what are called "auto properties":

```
public float infoToSend {get; private set;}

```

This makes a publicly readable variable that only the local script can set. It's really just syntactic sugar on a private setter / public getter method, but it's short to type and makes your intention clear.

You could also use Events to send this type of information when it's updated - a push relationship instead of a pull - adding or removing subscribers as needed.
> 1 votes

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


title: Issues with AABB on a platformer game

text:
# Question
Title: Issues with AABB on a platformer game
i'm facing an issue at the moment in my javascript/html platformer game that despite searching for this issue i can't solve. The problem is this:

When i place two platforms next to each other and the player moves between them, the algorithm believes the player is colliding with the side (left or right) face of the next platform. This is because all my bounding boxes are placed in an array and iterated through, the algorithm doesn't care if the player has to pass through one collider to get to another, it just thinks it has collided with both.

One solution is of course to make it consider what it has collided with first, another is simply not to place two platforms together. My solution would be to implement a kind of occlusion culling with collides, which if the player collides with a top face it can't collide with a side face if that side face's top face is higher or equal to top first that was being collided in.

That was hard enough to explain let alone implement and i just feel like there is a better work around that wouldn't be too difficult to implement and would be efficient.

My solution:

Another solution is to disable gravity if the player is in contact with the ground, this must be done carefully not to trigger an oscillation effect and also means that two iterations need to be made, one for collision in the y (done first) and the other for collisions in the x (done second).

# Answer
Try splitting your collision/response into two separate phases; first for the Y axis and then a second pass for the X axis. This will ensure that the character is already pushed "up" according to whatever is under the character's feet before wall collisions are applied and stop momentum.

You'll want to apply a threshold/limit to how much vertical separation is applied, otherwise the character will be able to "walk over" any wall. The threshold should be a fraction of the character's height, typically; usually between a quarter and an eighth, maybe even less.

This approach not only avoids ghost collisions between adjacent tiles, it also helps address minor discrepancies in position (e.g. if the new platform is `0.0073f` units higher than the current platform, the character will still be able to walk onto it smoothly). As an added bonus, the character will now be able to "walk up" shallow steps! In pseudo code:

```
for each tile/platform:
  if character intersects:
    find Y overlap
    if overlap < threshold:
      character Y position -= Y overlap

for each tile/platform:
  if character intersects:
    find X overlap
    character X position -= X overlap

```

You might want to invert the order of axis checking when the character is falling or jumping so that the character will slide on the sides of any tiles/platforms.

This approach is not perfect; there are still "edge" cases (sorry) where you'll get ghost collisions, but it works for a good number of games.

I also highly recommend that you read and then re-read http://higherorderfun.com/blog/2012/05/20/the-guide-to-implementing-2d-platformers/. It doesn't answer your specific scenario, but it might answer some other questions you don't know you have yet. :)
> 1 votes

---
Tags: collision-detection, javascript, html-canvas, collision-resolution, browser-based-games
---


# Question
Title: How can I get multiple players play my multiplayer game at launch?
Lets take a example of Apex Legends, it was release in February 4, 2019 and got 25 millions users in after a week (Source: The Verge). I know EA is the publisher so its easy for them to market and have huge user base but what if Im new in the industry and have been funded or invested to make huge game like that but could not get million of user in such short period of time?

How could I achieve something like this? How can I get a lot of players to play my game when I launch it? I thought of adding AI/bots to keep the real players in until my player mass is good enough, but is that just it? Are there other options?

# Answer
> 3 votes
Softlaunch and marketing.

*Softlaunch* is quietly launching your game. Once you're confident enough in the quality of your game, you release it to a small market (e.g. to only a particular region of the world). You start to build your user base while fixing some newly found issues, either those related to technical aspects of your game (server load balancing, etc.), or those related to monetization. Once your softlaunch is going well, you can expect to be ready for the official launch in your final target regions.

*Marketing* is having your game seen by your target audience. There are multiple ways to achieve this, either via internet ads, physical ads in your target region, having your game in the hands of reviewers, let's-players, etc.

This means that you have limited funds, you need to *plan ahead* and save some development time and some money for these aspects.

# Answer
> 2 votes
First and foremost comes marketing.Release trailers and initially launch demo version of the game.Record the user feedback and improve the main game accordingly.Once you feel satisfied launch the main game and you will have enough players playing it.Try to release new patches in a short period of time to improve players experience.BUT MOST IMPORTANTLY Content matters.

# Answer
> 1 votes
I would advise against relying on bots. Developing a good AI for a multiplayer game is a lot of work and players will still notice. I have seen some MMO games which started to use bots to reinforce teams when their playerbase started to decline (like Planetside 2), but this was usually considered a controversial move by their communities. Playing with other humans is the whole purpose of an MMO game, after all.

If you want to make sure that you have a large playerbase, then pre-launch marketing is important, especially for a multiplayer game where the size of the community directly impacts the game experience of the individual player.

If you "have been funded or invested to make huge game like that", then you should also assign a considerable part of these funds to your marketing budget.

I don't necessarily mean mass advertisement. Advertisement is great for AAA studios who got the budget to saturate the advertising space in order to make everyone and their grandma aware of their game launch. It is also great for the kind of game experience which wants to maintain a slow but steady influx of new players. But it's not really that great to get people hyped for a launch.

The best way to get people hyped is by building a fan community before your game is released.

* Create a community hub for your game where your community can interact with each other and with you. There are different opinions about how to create such a hub. Forums are the classical solution, but seem to fall out of fashion. Options which seem more popular right now are an own community on reddit ("subreddit") or a Discord server. Feed them regulary with small bits of information to keep them interested.
* Feed the gaming press with regular press releases.
* Get into contact with streamers on Twitch and let's players on YouTube and organize public tests with them.
* Announce your release long in advance. Not just the day, announce the exact time when the servers are open.

Promoting a game during the month leading up to release is a full-time job. If you are a solo developer, expect to spend more time on promoting than you spend on development during that time. When you are a small team, consider to hire someone who does nothing but promotion. Larger game companies usually have whole marketing departments.

---
Tags: marketing, publishing
---


title: pass by reference a transformation

text:
# Question
Title: pass by reference a transformation
I create a C # script in which I declare a transformation: public Transform Origin;

When I put this script on an object of the hierarchy, in the Inspector a field Origin appears at the level of the script in which I have to drag and drop a transformation of a GameObject or a GameObject.

How does the Origin transformation deal with the GameObject transformation to move in this field?

Thank you for your help

# Answer
A `Transform` component is always bound to one specific game object. You can't have a `Transform` object which exists separately without one.

If you want to pass transformation *information* around, then you might want to use separate variables `Vector3 originalPosition`, `Quaternion originalRotation` and `Vector3 originalScale`.

Another possible option might be to place an invisible game object at your origin and reference that game object. This can be more convenient for you as the developer because you can see and move the origin-point in the scene view. If you want to visualize a `Vector3` inspector property, you need to program an editor extension.
> 2 votes

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


# Question
Title: How can I draw lines and curves on a canvas that's not rendered?
I need to draw lines and curves on a canvas that is not rendered on the screen but just updates the array of pixels that would otherwise be rendered. I need this to separate my game engine from my renderer.

This has proven rather difficult for my case because I don't use sprites that are loaded, but I draw lines and curves on a canvas.

I have used the p5.js library to accomplish my game, but p5 doesn't let you work without a "setup()" and "draw()" function. I don't want any draw loop or something because that beats the purpose of separating my game engine from my rendering.

I want to use p5 to render after I have all my game logic separate and I can just call nextFrame() or something from my game logic inside draw() in a constant 60 fps.

In p5 it is possible to createGraphics() which works outside of the canvas and doesn't have to render but again, p5 needs a draw() loop to work.

Does anyone know how I can accomplish this?

# Answer
This is something which can actually be accomplished very easily with the regular canvas API without any additional libraries.

1. Create a new canvas with `var backgroundCanvas = document.createElement('canvas')` but don't add it to the DOM tree. You now have an in-memory canvas which doesn't apper on the screen.
2. Obtain the drawing context from it with `var context = backgroundCanvas.getContext('2d')`. The drawing context contains all the methods you need to draw on that canvas.
3. Begin a path with the context method `beginPath`
4. Add lines and curves to the current path with the context methods `moveTo`, `lineTo`, `arc`, `arcTo`, `bezierCurveTo` or `quadraticCurveTo`
5. Draw the path as a line with `stroke` or as a filled shape with `fill`.
6. To show the user what you have drawn, insert the canvas into the DOM tree or copy the content to a canvas which is already visible using `context.drawImage` on the destiantion canvas with the source canvas as the source image (not the context of the background canvas. Use the canvas object itself).
> 1 votes

---
Tags: javascript, rendering, html-canvas
---


# Question
Title: Even tiles wide pathfinding on square based tilemaps?
By editing my **A\* algorithm** as such that:

* a tile is valid if all of its neighbours are valid (checking this N-1 deep)

I can find N wide paths, where **N is odd**, and my unit just follow the "center" tiles.

But what if my unit is **even tiles wide?**

Yes, I generate a 2 tiles wide path, and then traverse it with an offset, so my unit will walk on the overlapping edge between the 2 tiles. (maybe there is a better solution, suggestions are welcome)

**But how do I find even wide paths?**

(Or my whole approach is bad?)

# Answer
> 1 votes
instead of pathfinding on the centers of the tiles, pathfind along the corners and edges of the tiles.

A corner is valid if all the neighbouring tiles are valid according to your existing algorithm(n-1)

# Answer
> 0 votes
Draw an NxN square with the tile in the corner. The tile is only valid if every tile in the square is valid.

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


# Question
Title: What is the alternative (new) 3d projection called that solves the stretching / zooming at sides of monitor?
I understand about camera's and projections etc, such that we have distortion and zooming when at the sides of the screen (exacerbated on 21:9 monitors), however a few years ago, in a Unity forum thread, someone explained that it's entirely possible to fix this, it's just that games devs have to do a different projection matrix - and most don't because they're lazy or don't think to.

However I can't recall where I saw this, or the name the author gave it - but it worked by breaking up the view into vertical planes / slices and rendering each flat.

Does anyone know what I'm talking about and can help me nail this down to some gfx paper or dev page as I need to implement this.

Thanks

# Answer
> 0 votes
It's very rare for games to implement this, as aspect ratios people use rarely cause this problem, and even if it does, lowering the FOV when stretching is too distracting, can solve the problem.

However, there are groups who like having multiple screens side by side when playin, for instance with simulators (racing and planes), because it's just more realistic to rotate your head than to use some other way to look around. For this reason, many racing games implement a feature, where side views are rendered from a different camera angle. However, it's very hard to set this up correctly, as you need to know the curvature of the screen to get accurate rendering.

Unity has this feature built-in with Multi-display

---
Tags: 3d, camera, projection, perspective
---


# Question
Title: How to move the player while also allowing forces to affect it
For now, that's how I move the player:

```
rb.velocity = Vector2.right * input.x;

```

And I affect him a force while he is damaged by an entity:

```
rb.AddForce(Vector2.right * force);

```

It works fine, until I try to move while I'm damaged by an entity. Since my velocity = input.x while I move, I can't affect any forces to it. I've tried to summarize velocity:

```
rb.velocity+=Vector2.right * input.x;

```

But then I need to clamp the speed and if I clamp it, my force which is affected to player is also clamped.

How can I resolve this problem?

# Answer
You're on the right track! This is something that usually the controller is responsible for. When you jump in a platformer you use a "isGrounded" variable to change how the controls behave while in the air right? You need a similar state for isKnockback. In most games when a player is knocked back, they have control striped from them for a certain amount of time. That or you treat it like being airborn where instead of setting velocity it will just apply a force to adjust the velocity. How you want to implement that control is a design choice, but there is no real physics based answer. The true physics based answer is implementing locomotion in the character's legs and that's not really useful for game physics. Another solution could be instead of applying a force, is to work with knockback at a velocity level like your movement. Apply a velocity, and reduce it by some amount each fixed update to simulate a knockback like effect. This is another common solution in the industry.

Edit: Just to credit the other answers here, they mention making your movement acceleration / force based. This is also an option, depending on the kind of motion you want. This approach is far more intuitive but gives you a lesser degree of control. It all depends on what you want, and it's important you make that decision early (or experiment if you're not sure) because it will impact decisions further down the line. If you want to see how crazy some platforming code can get, Matt released the code for Madeline from Celeste. They use a different engine (framework actually) but you can get the jist of how many variables and pseudo physics were used to achieve that feel. https://github.com/NoelFB/Celeste/blob/master/Source/Player/Player.cs
> 7 votes

# Answer
I created a little demo game a few days ago which demonstrates different ways to move a player-character. It might help you to better understand which way of moving is the right one for your particular game.

In general, you should use `rigidbody.AddForce` whenever feasible. It automatically takes care of managing multiple overlapping forces and ensures that the transfer of momentum on collisions is physically correct.

If you don't want your character to be able to accelerate indefinitely, increase the "Linear Drag" value of the rigidbody. The drag force increases quadratically with the velocity, so at some point it will cancel out the acceleration and effectively limit the maximum speed. A larger drag value will result in shorter acceleration and deceleration times, making the controls feel more "tight", but also greatly limit the effect of collisions.

If you want the character to have tight controls but also be affected by collisions, you could handle this the way the answer by gjh33 suggests. Have two different states in your player-controller. A regular state where the rigidbody has high drag and the player has full control force, and a "just got hit" state where you reduce the drag and the control force temporarily in order to make the character fly around in a temporary state of uncontrolled helplessness.

I am looking forward to playing your game.
> 10 votes

# Answer
Myself, I like to solve this by thinking of all player movement as acceleration-based.

I choose a target velocity using whatever complicated control logic I like, then ask the player avatar to accelerate toward that target, while respecting maximum acceleration rates I set.

Then, depending on the avatar's state (on ground, on ice, in the air, in a knockback state), I can change those acceleration rates to make the control input have a sharper or less pronounced impact.

```
Rigidbody2D body;

void AccelerateTowards(Vector2 targetVelocity, float maxAccel, float maxDecel) {
    // Compute desired velocity change.
    var velocity = body.velocity;
    var deltaV = targetVelocity - velocity;

    // In 3D, you might want to apply movement only horizontally:
    // deltaV.y = 0;

    // Convert our velocity change to a desired acceleration,
    // aiming to complete the change in a single time step.

    // (For best consistency, call this in FixedUpdate,
    //  and deltaTime will automatically give fixedDeltaTime)
    var accel = deltaV / Time.deltaTime;

    // Choose an acceleration limit depending on whether we're
    // accelerating further in a similar direction, or braking.
    var limit = Vector2.Dot(deltaV, velocity) > 0f ? maxAccel : maxDecel;

    // Enforce our acceleration limit, so we never exceed it.
    var force = body.mass * Vector2.ClampMagnitude(accel, limit);

    // Apply the computed force to our body.
    body.AddForce(force, ForceMode2D.Force);
}

```

Separating acceleration & deceleration rates like this lets me give a sharper braking force, which tends to help the controls feel tight & responsive when stopping or changing directions, while keeping a smooth acceleration for getting up to speed. It also lets you penalize braking specifically when on ice or being knocked back.

We can make a control state parameters object to hold the max speed, acceleration, and deceleration rates for our air, ground, ice, knockback states etc. and use this to adjust our control handling very flexibly:

```
// Choose our current speed / acceleration parameters based on our state.
var controlState = GetCurrentControlState();

// Compute desired velocity.
var velocity = GetDesiredVelocityFromInput(controlState.maxSpeed);

// Try our best to reach that velocity, with our current parameters.
AccelerateTowards(
     velocity,
     controlState.maxAccel,
     controlState.maxDecel
);

```
> 4 votes

---
Tags: unity, 2d, physics, rigidbody
---


# Question
Title: How can I add different colliders to each body part of a character in Unity?
I have been using unity game engine for about two weeks now. And I'm very interested in 3D game development. I have been learning basics of Unity and third person games. I saw many tutorials about creating a 3D third person player. They just drag the character into unity and create a capsule collider around the character and freeze the rotation around x and z axis.

So my question is: is it possible to add different colliders to each body part of the character and if so how do I do accomplish that?

# Answer
It's entirely possible. Preferably you just attach them to the game object representing that part of the body. If your mesh didn't import into different game objects then you should look into how to do that with import settings, as the alternative is to make gameobjects that are invisible with the colliders you want, then animate them with your model to match. But that is VERY tedious.

It's also important to know that a parent rigidbody acts like a vacuum for collision messages. Any colliders will belong to the nearest parent rigidbody, and work together as such. Make sure you have a rigidbody on your character, and the colliders are on child gameobjects of that rigidbody. They will also however collide with eachother, so you should put them on a collision layer and use the Collision Matrix to make them avoid self collision.

Lastly, the reason we use a capsule collider is because it avoids a lot of edge cases to simplify our collision geometry. A common thing to do is seperate our physical body collier from our damage/hitbox. Our physical collider should be simple, round, and aproximate. Thus a capsule collider is perfect. However for say, first person shooters, we want precise boundaries for bullet detection. Here we can go and add a seperate set of colliders, and again put them on a layer that only colliders with things that damage it. These colliders are more precise but don't handle physics, merely collision / hit detection. You should probably even make them triggers.
> 2 votes

---
Tags: unity, collider
---


title: Unresolved external symbol _glad_XXX

text:
# Question
Title: Unresolved external symbol _glad_XXX
I am relatively new to C++ but I have a few years of java experience. I decided to try to make a game with C++, In contrast with the handful of games i have written in Java with lwjgl.
I am having a linker issue with GLAD. I used to have an issue with GLFW as well, but after trying hours of setting changes it finally worked (not sure what fixed it).
Now I am only having the GLAD linker errors.

```
1>------ Build started: Project: OpenGlTesting, Configuration: Debug Win32 - -----
1>Source.obj : error LNK2019: unresolved external symbol _gladLoadGLLoader
referenced in function _main
1>Source.obj : error LNK2001: unresolved external symbol _glad_glClear
1>Source.obj : error LNK2001: unresolved external symbol _glad_glClearColor
1>Source.obj : error LNK2001: unresolved external symbol _glad_glViewport
1>C:\Users\Andrew Neeley\source\repos\OpenGlTesting\Debug\OpenGlTesting.exe :
fatal error LNK1120: 4 unresolved externals
1>Done building project "OpenGlTesting.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

```

I have (to my knowledge) successfully linked the GLAD files with my project.
Here's the code (and yes, this code is copied from a tutorial):

```
#include <glad/glad.h>
#include <GLFW/glfw3.h>

#include <iostream>

void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);

// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;

int main()
{
    // glfw: initialize and configure
    // ------------------------------
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X
#endif

    // glfw window creation
    // --------------------
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    // glad: load all OpenGL function pointers
    // ---------------------------------------
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }

    // render loop
    // -----------
    while (!glfwWindowShouldClose(window))
    {
        // input
        // -----
        processInput(window);

        // render
        // ------
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
        // -------------------------------------------------------------------------------
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    return 0;
}

// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window)
{
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);
}

// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    // make sure the viewport matches the new window dimensions; note that width and
    // height will be significantly larger than specified on retina displays.
    glViewport(0, 0, width, height);
}

```

Any help appreciated!

# Answer
> 6 votes
You probably figured this out already, but just in case you haven't - the GLAD library has both a header file and a source file. So you'll need to add that source file (glad.c) to your project as well as referencing the header file (glad.h) from the rest of your code as you've already done. That should fix your linker errors, as the glad\_ symbols you're looking for are in glad.c.

# Answer
> 1 votes
"Unresolved External" is just a fancy way of saying that the linker was not able to find a definition for a function/class declaration.

This usually happens when you are using some third party's header files, but you haven't told the linker *where* to look for the correct \** obj\** files.

I have personally never used Glad, but this may be due to the fact that you forgot to add a **.lib** or **.dll** file in your project.

I have an idea, that should do the trick:
Since you are using OpenGL and you don't have any dll or lib file, you should tell the linke to use **opengl32.lib** (it comes with VC++ by default)

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


# Question
Title: Calculate random points (pixel) within a circle (image)
I have an image that contains a circles at a specific location, and of a specific diameter. What I need to do is to be able to calculate random points within the circle, and then manipulate the pixels said points correlate to. I have the following code already:

```
private Point CalculatePoint()
{
    var angle = _random.NextDouble() * ( Math.PI * 2 );
    var x = _originX + ( _radius * Math.Cos( angle ) );
    var y = _originY + ( _radius * Math.Sin( angle ) );
    return new Point( ( int )x, ( int )y );
}

```

And that works fine for finding all the points at the circumference of the circle, but I need all points from anywhere in the circle. If this doesn't make sense let me know and I will do my best to clarify.

# Answer
If you want a simple solution just randomize the radius too:

```
private Point CalculatePoint()
{
    var angle = _random.NextDouble() * Math.PI * 2;
    var radius = _random.NextDouble() * _radius;
    var x = _originX + radius * Math.Cos(angle);
    var y = _originY + radius * Math.Sin(angle);
    return new Point((int)x,(int)y);
}

```

That however results in your points being more concentrated towards the center of the circle:

In order to get an uniform distribution make the following change to the algorithm:

```
var radius = Math.Sqrt(_random.NextDouble()) * _radius;

```

Which will give the following result:

For more information check the following link: MathWorld - Disk Point Picking.

And finally here's a simple JsFiddle demonstration comparing both version of the algorithm.
> 36 votes

# Answer
DO NOT just use random r and theta! This creates a weighted distribution with more points in the center. This page illustrates it well...

http://mathworld.wolfram.com/DiskPointPicking.html

Here's the method that creates a non-weighted distribution...

```
var r = rand(0,1)
var theta = rand(0,360)

var x = sqrt(r) * cos(theta)
var y = sqrt(r) * sin(theta)

```
> 5 votes

# Answer
You’re halfway there. In addition to generating a random angle, just generate a random distance, less than or equal to the radius, weighted so that you get a uniform distribution:

```
private Point CalculatePoint()
{
    var angle = _random.NextDouble() * Math.PI * 2;
    var distance = Math.Sqrt(_random.NextDouble()) * _radius;
    var x = _originX + (distance * Math.Cos(angle));
    var y = _originY + (distance * Math.Sin(angle));
    return new Point((int)x, (int)y);
}

```

Now you’re thinking with polar.

You can also weight the distance like so to avoid a square root:

```
var distance = _random.NextDouble() + _random.NextDouble();
distance = (distance <= 1 ? distance : 2 - distance) * _radius;

```
> 4 votes

# Answer
If performance is an issue then one alternative solution is to generate a random position in a box with the width/height of your circle and then throw away any points that are not in the area of the circle.

The advantage of this method is that you are doing no cos/sin/sqrt functions, which depending on your platform may be a big speed saving.

```
var x = _random.NextDouble();
var y = _random.NextDouble();
if (x*x + y*y < 1.0f)
{
    // we have a usable point inside a circle
    x = x * diameter - _radius + _OriginX;
    y = y * diameter - _radius + _OriginY;
    // use the point(x,y)
}

```
> 3 votes

# Answer
I have taken the approach of one of the listed comments, and extended the functionality to create a donut shaped point generation system.

```
            private Vector2 CalculatePosition()
            {
                double angle = _rnd.NextDouble() * Math.PI * 2;
                double radius = InnerCircleRadius + (Math.Sqrt(_rnd.NextDouble()) * (OuterCircleRadius - InnerCircleRadius));
                double x = (_context.ScreenLayout.Width * 0.5f) + (radius * Math.Cos(angle));
                double y = (_context.ScreenLayout.Height * 0.5f) + (radius * Math.Sin(angle));
                return new Vector2((int)x, (int)y);
            }

```

It is a similar approach as previously mentioned but provided different results. The inner part of the circle will be left blank with no points.
> 0 votes

---
Tags: c#, algorithm
---


# Question
Title: Destroying copy of DontDestroyOnLoad GameObject?
I have a Main Menu with level selecter up to 5 different scenes on one Map. I also have a MenuManager which doesn't get destroyed between the scenes to gather the bool information of level finished or not. When I start the game and change for example level 1 and move back to the Main Menu again the MenuManager gets copied. I tried this at first:

> public static GameObject \_menuInstance;

```
void Awake()
{
    if (_menuInstance == null)
    {
        _menuInstance = this.gameObject;
    }
    else
        Destroy(gameObject);
}

```

**My problem with that is that the copied GameObject that get's destroyed is the wrong one.**

This is the copy that gets created after I switched the scenes and back to Main Menu.

This is the original MenuManager that should be the \_menuInstance Object and the other one should be destroyed.

How can I not delete the original one and delete the one without the references?

I come up with something but I am not sure if this is the right way to do this.

```
    //I changed the code in the Awake() function to
    void Awake()
{
    if (_menuInstance == null)
    {
        _menuInstance = this.gameObject;
    }
}
//I checked one of the missing references to be null and then destroy the fake copy.
Update()
{
   if(_startTheGame == null)
     Destroy(gameObject);
}

```

# Answer
> 1 votes
Because this is what happens wit your code:

* In the first scene, \_menuInstance is null, therefore the created GameObject is assigned to it.
* Then in the second scene, the same GameObject checks and \_menuInstance is not null, so it gets destroyed.
* Then the copied GameObject evaluates, now \_menuInstance is not null, thus that GameObject is assigned to that reference.

So, you have to add an additional check on the else:

```
void Awake()
{
    if (_menuInstance == null)
    {
        _menuInstance = this.gameObject;
    }
    else if(_menuInstance != this)
        Destroy(gameObject);
}

```

So you only destroy the GameObject if \_menuInstance is not null and if that same \_menuInstance is not the evaluating GameObject. Hope it helps.

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


# Question
Title: How can I hide the touch-screen joysticks in the main menu?
I am a Unity beginner trying to make an app/game. How do I hide the touch-screen joysticks from showing on-screen in the main menu before the game/app actually starts?

# Answer
Have you tried SetActive(false)? Use it while opening main menu. When loading the game scene, use SetActive(true).

Warning - you have to store a reference to the UI element to set it back to active. At least that's how it was when I last used Unity.
> 1 votes

---
Tags: unity
---


# Question
Title: Occupation groups for a country simulation game
I'm trying to create citizen occupation groups or job classes for a country-management game I'm developing. I want it to be inclusionary but also very basic.

I did some research but all job lists I got contains more than 20 job types like farming, mining, education, law but It's too many for my game's setting and It still doesn't include every workforce. I need wider spectrum of jobs but I'm having trouble to categorize them, like labour, public service etc...

Any help is appreciated.

# Answer
> 2 votes
I think you are approaching this problem from the wrong angle.

First, forget about inclusivity and simulationism for a moment. Make up your mind about what experience you want to create from a gameplay perspective. What aspects of country management do you want to simulate? What situations do you want your player to experience? A good tool in this conceptualization phase can be to write **player stories**. Describe the events of a typical game session as you imagine it from the perspective of the player.

Then check what occupational groups you need to create that game experience. You will now see what dividing lines make sense in the context of your particular game and which do not.

When you start prototyping your game, try to keep it as simple as possible. Start out with the bare minimum of groups you need to create the experience you are looking for. Don't worry yet about your game not having enough gameplay breadth - feature creep will set in later anyway.

I am looking forward to playing your game.

---
Tags: game-design
---


# Question
Title: How to invert a Tilemap's coordinate system?
The Tilemap object in Unity uses a coordinate system that grows up-right from (0,0). (ie. with the Origin at the bottom-left of the screen.) I'm trying to represent a mapping system that has the origin at the top-left of the screen and grows down-right instead, but I can't figure out how to do it.

Scaling the tilemap's Y transform by -1 draws everything upside-down. Trying to set the object's Tilemap component to custom orientation and setting its Y scale to -1 appears to have no effect, and the editor doesn't accept it anyway, changing what I entered, setting the Y scale back to 1 and the X scale to -1 instead.

Is there any way to fix the Tilemap so that everything draws like normal, except for Y growing downward instead of upward?

# Answer
It might be smarter to work *with* unity instead of *against* it and just accept how its coordinate system works. Keep in mind that this coordinate system follows the same "y is up" logic as the Unity world-space coordinate system, so this is just consistent.

But if you really want to do this, then one option would be to write a couple of extension methods for the `Tilemap` class which just call the standard methods but with the y-coordinate inverted.

You could also create a completely new class (plain old C# class, not a MonoBehaviour) which works as an adapter for a tilemap. It would have a `private Tilemap tilemap` and a bunch of public methods and properties which call methods / access properties of the wrapped Tilemap object. If you only access your tilemap through this adapter class then you don't need to worry about accidentally mixing your API with the standard API and getting unexpected results.

Unity tilemaps can grow into negative coordinates, so the origin doesn't necessarily need to be in the bottom left. You can also put the origin in the upper left and use increasing negative y-coordinates. So the tile 3 to the right and 5 to the bottom has the coordinates `3 : -5`.
> 3 votes

---
Tags: unity, coordinates
---


# Question
Title: Public variable changed in script isn't stored in playmode
I have a public variable `float x` in script `Foo.cs`. I have a `Bar.cs` script with a function like this:

```
bar() {
    Foo foo = FindObjectOfType<Foo>();
    foo.x = 1f;
}

```

And a custom editor which calls `bar()` when a button is pressed. All of that works fine in the editor, my `float x` is changed to `1`, but when I enter playmode the value changes itself. If I change it manually in the inspector it works fine too. So for example:

* I set `x` manually in the inspector to `10`.
* I enter play mode, `x` is still `10`.
* I exit playmode and call the `bar()` function.
* `x` has changed to `1` in the inspector.
* After hitting "Play" `x` changes back to `10`.

How can I fix this?

# Answer
> 2 votes
Welcome to the rabbit hole of Unity Editor scripting. Whenever you change serialized values, you need to tell unity. The object you are changing at editor time is just a copy of the serialized one. If your editor is acting on the copy object (i.e. you're using the "target" property) then you need to call Undo.RecordObject. Unity recommends working on the SerializedObject. SerializedObject is NOT a representation of your target object. it IS a representation of serialized data stored by the editor that is used to build your target object. This can be complicated to wrap your head around at first. I've also found many unity editor API references to be wrong, or misleading. I can't list all the pitfalls in one answer, so just heed my warning.

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


# Question
Title: Level design - modular vs single project
I'm working in Blender and UE4 for a while now...

I always have the dillema of how to create my levels. My two ideas are: a) modular - like lego blocks. Create a wall, a floor, wall with hole for a window etc inside blender, and then, in UE4 make a level out of them. The advantage here is that I can arrange them however I want. The disadvantage is - I always have a problem getting the elements to fit properly. Even if I scale one element up or down, everything else starts falling apart.

b) single project - make a whole object like a room or house in blender. Then everything connects nicely, but I'm always worried that it will be harder to edit, and I usually end up messing something. For example, whole house looks great, but inside the game a window is way too high, or the doors are too narrow to go through.

My question: What should I do - should I stick to one method and try to fix the disadvantage? If yes, how would I do that? Is one of the methods considered "better" or the "industry standard"?

# Answer
> 1 votes
Almost everything is done modular for a number of reasons. This spans from the reducing polygons on hit boxes too supporting asset recycling to cut down on work. This is no means to say that large or complex assets are bad are shouldn't be used but building things modular then fixing the problems later in an editor is almost always more efficient.

I would also note that on single person projects, in my experience, it is best to make temp assets then later, once levels are built, already modular, make the assets for current and future use.

---
Tags: blender, level-design
---


# Question
Title: Project organization for a multiplayer client-server game
I'm programming a game 100% in Java but I'm having some issues concerning the final games architecture.

I plan on having two separate projects: one that will hold the client side of communication and another, the server side. As for all the rest, the Player Class, the Main Game class, etc. I'm not sure whether they should be in the server project or the client project... any suggestions?

# Answer
In general I would suggest, do what makes sense for you and your project, if that works, then doesn't really matter if it's "correct" or "wrong". If it doesn't work, then it's a learning experience.

In the case of an online game, it's always tricky to decide what belongs on the client and what on the server. I would say it depends from game to game. One idea is to have everything on the server, and clients only handle input. But that could create problems on big games, as the server might struggle with enough amount of players. This way however you can minimise cheating.

Another idea is to handle everything on the client, and send only the state of "shared" objects to the server. This is really light on the server, but what if a player tampers with the sent data?

My advice? Pick something in-between, depending what you envision for your project. If it works, good. If it doesn't, start altering it until it does.
> 1 votes

# Answer
your server can be any java program that is accepting connections ( UDP or TCP ), this server should have a list of all connected clients, and should manage if they send data packages to the client and how can process them. That means the server is the one that is processing all the game ( or the server is the game itself ), when the server receives certain package it will broadcast instructions on how the clients must behave... for example:

we have a server with 4 players,

1.- a client 2 send a message to server like ( move\_on\_x:2 ) 2.- server receive this message and check whether the player 2 have free space to move 2 pixels on X coordinate, if so then the server broadcast a message to all clients saying player2 cordinate is increased by two, that way all 4 clients will see that the player 2 moved 2 pixels on X axis.

and so on, there should be many messages, like jump, die, attack, decrease hp, etc, etc.

this is just one approach. all multiplayers must have some connection handling to check what happens if the player log in into the server, what happens when the connections is suddenly broken, etc, etc.

they are also diferent arquitectures for online games like p2p, client-server, etc,
> 0 votes

---
Tags: java, architecture, multiplayer, server, client
---


# Question
Title: How do I implement bullet spread in three-dimensional space?
How can I shoot a bullet in three-dimensional space in such a way that its path diverges a bit, randomly, from the direction in which the gun is pointed?

I know I have to use the Quaternions, but I don't know how exactly.

Should I convert Quaternion to EulerAngles

```
Quaternion randomRotation = Random.rotation;
Vector3 inEuler = randomRotation.eulerAngles;

```

or is there a fairer / nicer way to do it?

# Answer
> 5 votes
> Should I convert Quaternion to EulerAngles

No, going to EulerAngles makes most things worse.

Try something like this instead:

```
Vector3 PickFiringDirection(Vector3 muzzleForward, float spreadRadius) {
    Vector3 candidate = Random.insideUnitSphere * spreadRadius + muzzleForward;
    return candidate.normalized;
}

```

Here we pick a random vector offset to add to the end of our nominal shooting direction, then normalize it so the result is still a unit vector.

There are more ways to pick a random vector in-line with our shooting direction or only slightly deviating from it than there are to pick a highly perpendicular offset, so this will give a distribution where most shots go toward the middle of the cone, and outliers hitting the edges of the cone are more rare.

Your `spreadRadius` is roughly the radius of the cone 1 unit from the muzzle, or roughly `Mathf.Tan(Mathf.Deg2Rad * angle/2f)` where `angle` is the divergence between opposite sides of the cone.

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


# Question
Title: How to make pathways/corridors in a randomly generated dungeon?
I am trying to make a random dungeon generator using Unity. I have been able to setup the rooms properly and connect them to each other using a minimum spanning tree algorithm. I have attached an image below where you can see what I have so far. The next step will be to create pathways/corridors to connect the rooms together but I am having difficulty understanding how I am supposed to go about it. I want the corridors to be straight or form an 'L' shape when connecting to each other. So I was wondering if anyone could help me out with this. Any help is appreciated.

# Answer
> 1 votes
Ok so I found the solution and it's actually rather simple and elegant. Thanks to this article I was able to find out that the first step is to calculate the midpoint between 2 rooms. If the midpoint falls within the bounds of the rooms, then stretch a path across the midpoint to the bounds. Otherwise, make an 'L' shaped corridor from the center of one room to the center of the other.

Thanks to everyone that commented or posted an answer. Take a look at the images below to see what different generations of the map look like

# Answer
> 2 votes
When the two rooms you want to link have overlap on the x-axis or y-axis, then it is a rather trivial case: Calculate the overlap range and generate a corridor at a random coordinate on that overlap.

The code for the vertical connections would look something like this:

```
// calculate x overlap range
float rangeXfrom = Mathf.max(room1.x1, room2.x1);
float rangeXto = Mathf.min(room1.x2, room2.x2);
// check if there is x overlap
if (rangeXfrom < rangeXto) {
     // generate path position
     float pathPosX = Random.Range(rangeXfrom, rangeXto);
     // check which two y-walls are the two closest ones
     if (room1.y2 < room2.y1) {
         GeneratePathway(pathPosX, room1.y2, pathPosX, room2.y1);
     } else {
         GeneratePathway(pathPosX, room1.y1, pathPosX, room2.y2);
     }
}

```

The code for generating the horizontal connections would look the same, just with the x-axis and y-axis reversed.

The only rooms where that wouldn't work in your example are rooms 8 and 9, because they have no overlap on either axis. Here you need an L-shaped connecting wall. Now you could pick a random point on the x edge of one and the y edge on the other and then draw two corridors extending from those points until they meet. But that might result in these two corridors intersecting a third, unrelated room (like room 0 in this example). The safest solution would be to draw the L-shaped corridor between the closest corners. I am not sure how exactly you calculate your minimum spanning tree, but I find it very likely that it is actually impossible to intersect another room that way. If it is possible, then try one direction and check if there is a collision with another room. If there is, try the other direction. If there is also a collision, then it seems impossible to connect this room and you might have to place it somewhere else or prune it.

Another approach would be to avoid such situations in the first place by modifying your room generation algorithm in a way that neighboring rooms will always have overlapping edges.

# Answer
> 0 votes
My solution might not be perfect, but I think it will be a good compromise between quality and accessibility:

You can make a "corridor" mesh (or few). Also, make a "regular wall" mesh, and a "entrance wall" mesh. The last one will be a normal wall, but with a hole where the corridor would be. Then, you can create the rooms like tiles, using the wall meshes. Wherever you need an entrace, use the wall mesh.

Finally to add the corridors, you could add the corridor mesh right between two entrances, and scale it properly along the length. A good idea is to keep the corridor mesh simple, so it won't look weird due to teh scaling.

---
Tags: unity, procedural-generation
---


# Question
Title: Game communicates with MongoDB in the Editor but not in WebGL build
I was trying to implement MongoDB in my Unity WebGL game and everything is working fine in the editor: I managed to insert and retrieve documents from my Mongo database with no issues.

Everything seemed perfect until I compiled the project and realized that my WebGL build won't communicate with my database at all!

I took a look at the console and I see this error:

> MissingMethodException: Default constructor not found for type MongoDB.Bson.Serialization.BsonClassMap\`1\[\[UserAccount, Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\]\]

I have no clue what's happening. I tried compiling the project for Windows/Linux and I got the same error, then I changed API compatibility level to 4.x and it was working fine on the Windows build, but not on WebGL ( API compatibility level=4.x is checked for WebGL build!)

Can someone lend me a hand with that?

# Answer
> 4 votes
What you are trying to do here unfortunately **can not** work. The MongoDB protocol is based directly on TCP/IP. But a web application running in a web browser can not create raw TCP/IP connections. There is no API in JavaScript for doing that. The closest it gets are HTTP requests ("AJAX") and WebSockets (which are intentionally incompatible with regular sockets). A WebGL build *is* a JavaScript application, so if the JavaScript API can't do something, then Unity won't magically allow you to do it.

If you want to use a MongoDB database from your Unity application running in the browser, then you will have to use a middleware which provides a REST API for MongoDB which you can then access from your game by using the `UnityWebRequest` class.

---
Tags: unity, c#, networking, databases, mongodb
---


# Question
Title: OpenGL Fragment Shader simulate LCD slow response time
I have a very simple OpenGL view rendering 2 triangles with a single texture applied. The minimum setup for rendering a 2d game.

What i do is redraw the texture for every frame and easily get 60fps.

I would like to add an effect simulating LCD slow response by outputting pixels that are the average between the current and the previous frame.

The pseudo code of fragment shader would look like this

```
varying vec2 v_TexCoordinate;
uniform sampler2D u_Texture;

void main() {
    gl_FragColor   = (texture2D(u_Texture, v_TexCoordinate) + PIXEL_PREVIOUS_FRAME) / 2;
    PIXEL_PREVIOUS_FRAME = gl_FragColor;
};

```

Well, i think shaders can't keep a persistent variable like PIXEL\_PREVIOUS\_FRAME, then i really don't know how to tackle this problem.

Any suggestion?

# Answer
> 3 votes
Look up "rendering to textures" in OpenGL. This will let you render your scenes to alternating render targets backed by textures named, say, `A` and `B`. By alternating them, one texture always contains “this frame” and the other the “last frame.”

So every frame, you'd:

1. Swap A and B.
2. Bind A as a render target; render the game as normal to A.
3. Bind A *and* B as textures to read from.
4. Render a single triangle (or quad) that covers the full screen using a fragment shader that samples from both A and B and blends them however you want.

---
Tags: opengl, fragment-shader
---


# Question
Title: Why does iOS packaging fail when I activate Apple ARKit plugins in Unreal Engine?
Steps,

Using Unreal Engine 4.21.2

**1** \- I created new Third Person game from the Unreal Engine template and named it FaceARSample

**2** \- I imported a skeletal mesh with blend shapes
**3** \- I added this to my DefaultEngine.ini:

\[/Script/AppleARKit.AppleARKitSettings\]
bEnableLiveLinkForFaceTracking=true

**4** \- I packaged the project for iOS and it was successful. I was able to deploy it to my iphone.
**5** \- I activated Apple ARKit and Apple ARKit Face Support plugins

**6** \- I packaged the project for iOS and it failed (error log below)

# Answer
This might sound super unrelated - but do you have visual studio installed?

I noticed that on a fresh install, if you change any of the plugin settings in UE4, it will require you to have visual studio for packaging to work. (even if you go back to the default settings).

Try getting that, (to make sure you got the right version, you can try to open and of the built in scripts... it will try to open them in VS).

Try packaging again afterwards.
> 0 votes

---
Tags: ios, unreal-4, unreal, plugin
---


title: Amazon FreeTime Unlimited Monetization

text:
# Question
Title: Amazon FreeTime Unlimited Monetization
So I've recently noticed how great FreeTime Unlimited is for my daughter. There's no ads, no in-app purchases, etc. She can just play the games/apps and I don't have to worry about it.

As a develop I thinking it could an interesting avenue to go down, but there's a few things that I for the life of me can't get Amazon support/forums to answer in any logical manner.

So the idea according to their information is that the apps are highly scrutinized to verify they are child friendly content, which is excellent. Also, you can't use webviews, ads, or in-app purchases.

**My question is**: How do devs monetize these applications? Clearly they're not just giving away their work for free? The only logical answer I can guess at, is that it uses the Amazon Underground scheme of earning $$ based on the amount of time the user spends in the app/game??

Does anyone have and actual experience or information on this? As I said, I've reached out to multiple people at Amazon, and keep getting the runaround with all of them pointing me to the same useless link.

# Answer
While I'm sure your looking for details it doesn't appear that there are many details about how exactly devs are paid (and it might even be obscure the the devs working on the projects) I can give you some speculation.

**1) Time Based** As you guessed it possible that amazon is paying apps based on how successful they are in time. Although this seems somewhat problematic as it promotes bad design practices where the goal is time sunk into the app instead of fun. This means that a usual system used in other subscription mediums would fall apart here.

**2) Commission/Licence** Most likely amazon is paying a set amount for access to each game each month, or commissioning specific studios for amazon exclusive titles. This would put them in line with how Netflix runs their subscription model.

**3) Some Weird Combination** Big tech companies these days *love* their proprietary algorithms so it's totally possible that in addition to base monthly price they reward any number of things. This could include playtime, how often an app is opened, how much a customer comes back to the app, and other data driven methods. While 2 makes the most sense to me from the lack of information on the subject out there it seems very possible that this is the answer.

The real thing to remember here is that Amazon does not need to turn a profit on this venture. This is another one of Amazons "Loss Leaders" where there goal is too get you to subscribe to Amazon prime and then once you are in their system they can start turning the real profit.

We can even run a hypothetical example of the inverse with this very product. So let's say you subscribe to Amazon Music (which is almost certainly losing Amazon money) and to make Amazon Music cheaper you get Amazon Prime. Now that you have prime you say what the heck and get Amazon Free Time, now Amazon is collecting more money from you originally at near no extra cost thanks to the digital nature of Free Time.

**TL;DR:** It's hard to say exactly what Amazon is doing but we can be confident that devs are being well paid whether or not Free Time is independently profitable.
> 1 votes

---
Tags: android, monetization
---