title: Shadow mapping too slow and ugly!

text:
# Question
Title: Shadow mapping too slow and ugly!
As many of you are, I am working on a game.

I have just added my first attempt at shadow mapping (standard variation) and quite frankly I am very disappointed.

I am literally squeezing as much out of this approach as possible and it simply not usable.

Its too slow and too ugly to look at!

So what do people do?

I have bumped into something called "Perspective shadow mapping" but I have not got any working examples of this yet and I don't really want to spend a long time working on this only to find that its too slow to use and not all that much better.

So what I am asking for is some feedback on your experiences and how you overcome all the problems with shadow maps.

Some details are: I have a single light (point light) Standard first person type game The light moves (all the time, but slowly) The draw distance is not very far

If I don't use shadows then the game runs at 500 FPS, and with shadows it drops to 90!

Edit: As I have said, I have put a lot of effort into this so I have already solved: Getting the tightest possible near/far Getting the tightest X/Y (without constant change per frame) I have no peter panning No acne

But, due to the fact that my light moves all the time I get constantly (shaking) shadow pixels.

And the only way I am able to make the shadows look crisp/and stop shaking is to make the shadow map ridiculously high resolution. And this then drops the frame rate too much.

I understand all the problem, but what I want to know is what do people rely do to solve the problem. People cant really be using this in games as its just no good.

I am also looking into cascaded Shadow Mapping. That looks to be the solution. What are people experience with this?

# Answer
> 2 votes
Any other forms of shadow mapping are probably going to be slower.

I would not necessarily say it is too slow if you are getting 90 frames per second, though. When you have nothing going on in a scene it's very common to go from a very high frame rate to a much lower one. Yes, in a sense 4/5 of your power is going to shadows, but it is a relative measure not an absolute one. It doesn't mean that you can't still add all the stuff you need to onto the screen without going under 60 fps.

For talking about quality, it is too vague to just say they look bad. Likely you have something wrong like shadow acne or having too low of a resolution.

It's also possible you have some implementation detail slowing down your results but that is impossible to tell without code to look at.

This tutorial is pretty good for covering basic shadow maps and you can tell the performance is good.

http://mbsoftworks.sk/index.php?page=tutorials&series=1&tutorial=29

It's in opengl but it describes the concepts and pitfalls pretty well.

There's also cascading shadow maps you could look into, but as I said any other kind of shadow map will be even more expensive.

# Answer
> 0 votes
Likely it looks ugly because you have problems like shadow acne and peter panning, it is likely not aliased either. OpenGL-tutorials.org has great tutorials for shadows. Even if you're using DirectX. Here is the link.

---
Tags: directx, shadow-mapping
---


# Question
Title: Do I Need To Purchase a Developer Kit from Sony to deploy from Unity?
I want to make PS Vita games, and starting today, I will sign up as a registered developer with Sony so I can make my indie game for Android available on PS Vita, but i had a question.

I know that Unity can deploy to the Vita as long as I have Sony's SDKs, but would I need to purchase a physical Developer Kit from Sony in order to do this, or can I just deploy and test on my personal PS Vita? I cannot afford the Dev Kit so I really hope that I can just deploy to my own personal Vita.

# Answer
I found an answer on the Unity Forums. When PlayStation Mobile was still alive, you could test on a Retail Vita, but now that is not the case. You are required to use a PS Vita Developer Kit in order for Unity to deploy and test.
> 5 votes

---
Tags: unity, deployment
---


# Question
Title: Collision from the underside of a cylinder (Unity C#)
A quick introduction to my problem at the moment: I am currently having trouble with checking whether or not a cylinder is grounded. I am using a mesh collider (octagonal prism) as my main collider for the object, however I can't seem to get a reliable ground detection beneath it. I have tried using a trigger and raycasting, but neither seem to work correctly.

It would be a great help if you could either provide a method of correctly raycasting the cylinders base, or an alternate method (bearing in mind the object rotates on all axis). Many thanks in advance. (terrible diagram below)

# Answer
> 1 votes
Use a RigidBody SweepTest.

If your cylinder is not already a rigid body, make a duplicate of it for this test. Utilizing the rigidbody component on your object, call the sweep test to detect if moving the body down a very small amount hits ground.

It's essentially a raycast for each point in the rigidbody, as described in the description:

> Tests if a rigidbody would collide with anything, if it was moved through the scene. This is similar to doing a Physics.Raycast for all points contained in any of a Rigidbody's colliders and returning the closest of all hits (if any) reported.

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


# Question
Title: LibGDX: Can i get some useful tips for loading textures?
So basically in my game(completely new to gave dev) I have a level select screen. I have 8 Buttons to select the levels and i use an asset manager to load the textures for the buttons. For example their is a locked button for when you have unlocked the level, an active for when your mouse is over the button and inactive when your mouse is not over it. My problem is that having all these textures keep interchanging is causing memory usage to go off the charts, from as low as 30mb all the way over 1000mb as soon as i go to the level select screen and it keeps rising. Whats a good way to load lots of textures without having to use so much memory? Or should i just figure out a better way to load them without causing so much usage of memory. Im new to this so go easy on me :)

or... Would this amount of memory being sprung be a memory leak somewhere?

Edit: Heres the code snippet where the memory leak i traced to i believe.

I'm calling this method in my handleInput which i then call in the render method.

```
public void levelManager(float rowX, float rowY, Screen setScreen, Texture drawActive, Texture drawInactive,
        float multiplier) {
    if (Gdx.input.getX() / GravitySpikesRevamped.PPM < (rowX + BUTTON_WIDTH) / GravitySpikesRevamped.PPM
            && Gdx.input.getX() / GravitySpikesRevamped.PPM > rowX / GravitySpikesRevamped.PPM
            && (GravitySpikesRevamped.GAME_HEIGHT - Gdx.input.getY())
                    / GravitySpikesRevamped.PPM < (rowY + BUTTON_HEIGHT) / GravitySpikesRevamped.PPM
            && (GravitySpikesRevamped.GAME_HEIGHT - Gdx.input.getY()) / GravitySpikesRevamped.PPM > rowY
                    / GravitySpikesRevamped.PPM) {

        if (multiplier == 1) {
            game.batch.draw(drawActive, BUTTON_WIDTH / 2 / GravitySpikesRevamped.PPM,
                    rowY / GravitySpikesRevamped.PPM, BUTTON_WIDTH / GravitySpikesRevamped.PPM,
                    BUTTON_HEIGHT / GravitySpikesRevamped.PPM);
        } else if (multiplier == 2) {
            game.batch.draw(drawActive, BUTTON_WIDTH * 2 / GravitySpikesRevamped.PPM,
                    rowY / GravitySpikesRevamped.PPM, BUTTON_WIDTH / GravitySpikesRevamped.PPM,
                    BUTTON_HEIGHT / GravitySpikesRevamped.PPM);
        } else if (multiplier == 3) {
            game.batch.draw(drawActive, BUTTON_WIDTH * 3.5f / GravitySpikesRevamped.PPM,
                    rowY / GravitySpikesRevamped.PPM, BUTTON_WIDTH / GravitySpikesRevamped.PPM,
                    BUTTON_HEIGHT / GravitySpikesRevamped.PPM);
        }

        if (Gdx.input.isTouched()) {
            game.setScreen(setScreen);
        }
    } else {

        if (multiplier == 1) {
            game.batch.draw(drawInactive, BUTTON_WIDTH / 2 / GravitySpikesRevamped.PPM,
                    rowY / GravitySpikesRevamped.PPM, BUTTON_WIDTH / GravitySpikesRevamped.PPM,
                    BUTTON_HEIGHT / GravitySpikesRevamped.PPM);
        } else if (multiplier == 2) {
            game.batch.draw(drawInactive, BUTTON_WIDTH * 2 / GravitySpikesRevamped.PPM,
                    rowY / GravitySpikesRevamped.PPM, BUTTON_WIDTH / GravitySpikesRevamped.PPM,
                    BUTTON_HEIGHT / GravitySpikesRevamped.PPM);
        } else if (multiplier == 3) {
            game.batch.draw(drawInactive, BUTTON_WIDTH * 3.5f / GravitySpikesRevamped.PPM,
                    rowY / GravitySpikesRevamped.PPM, BUTTON_WIDTH / GravitySpikesRevamped.PPM,
                    BUTTON_HEIGHT / GravitySpikesRevamped.PPM);
        }
    }

```

Okay i solved it, basically in my method above every time i called it was creating a new screen. So i basically was creating infinite amount screens in memory. I fixed it :\]

# Answer
> 0 votes
Okay, so I had a memory leak. In my method I posted i was calling it in my render so basically a loop of creating new screens over and over again which was destroying away my memory.

```
levelManager(firstX, ROW_FOUR_BUTTON_Y, new LevelSevenScreen(game),
                    game.textureManager.get("LevelSevenButtonActive.png", Texture.class),
                    game.textureManager.get("LevelSevenButtonInactive.png", Texture.class), 1);

```

I was basically doing that everytime i called it which was a no no.

---
Tags: java, libgdx, memory
---


# Question
Title: Unity: How to cut a line (or curve) at a specific point and animate it?
What would be a good approach to cut a line (or curve) at a specific point (let's say we use the mouse pointer to detect the position of the cut).

The curves you see in the image above, are Bezier curve generated using the `LineRenderer` and have a `PolygonCollider2D` attached that covers the entire curve (taking the width set to the `LineRenderer` into consideration).

Imagine a game like Cut the Rope or Fruit Ninja, where you use the mouse pointer to cut the wires. I already implemented the cut detection algorithm, so I know the point where my wire needs to be cut. I would like to know how can I snap the wire in two and add some sort of animation.

# Answer
> 2 votes
I'd instantiate (via an object pool) a GameObject with a RigidBody and SphereCollider attached at each of the points along the line. Then use Rigidbody.AddExplosionForce to the two objects nearest the cut. Create an array of the GameObjects transforms in order from the start of the wires to the cut point & in each update cycle set the corresponding line renderer position to that that transform position. You could tweak the mass of the rigidbodies to suit how you want the wires to fall. Would need some fine tweaking but should get the job done.

---
Tags: 2d, animation, unity, beziers
---


# Question
Title: Three button combination to open next scene
I have thirty (30) buttons in a trivia game, they are laid out in the following configuration with three rows:

```
( A, B, C, D, E, F, G, H, I, J)
( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
(00,01,02,03,04,05,06,07,08,09)

```

Using these combinations of buttons and clicking one and only one from each row I have a thousand (1000) - three (3) button combinations. E.g.: A27 would be one combination of the thousand possibilities. These are not random combinations each opens a very specific scene.

What I am trying to do is create a C# script that when I click any of these three (3) button combinations it will open a new scene. Once that scene is open I’m okay because then have my own scripts attached to the single buttons in the new scene to continue to a further scene.

What I can’t figure out is the syntax, should I use `if` Statements such as - `if (Btn_A) && (Btn_1) && (Btn_01)` then load scene such and such? Then do I attach the script to the canvas then to each of the three button combinations (A 1000 Scripts combinations)?

# Answer
> 4 votes
You should not try to hardcode the combinations. Seems fairly straightforward to name your scenes A207, or F409, and so on. When the button combination is entered, simply load the scene with the name produced.

```
string button1 = selectedButtonA.text;
string button2 = selectedButtonB.text;
string button3 = selectedButtonC.text;
string name = button1 + button2 + button3;

SceneManager.LoadScene(name);

```

This code executes in a script attached to the canvas object or some kind of manager object. Each row of buttons has a script that sets the selected button values. i.e. the first row buttons, when selected, will assign themselves to `selectedButtonA` in the scene loading script.

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


# Question
Title: Maya - How to clean combine mesh history?
I've combined a load of meshes using Mesh \> Combine. Each mesh was already skinned to my rig. The combine worked ok and the rig / skinning is fine. However I'm left with a bunch of transform nodes:

If I delete history on the newly combined object these nodes are deleted but the skin becomes unbound. If I delete them manually the skin also becomes unbound and the materials disappear from the model. If I export (to Unity) all of these transforms are included, even if I just export a selection of the skeleton & mesh.

How can I get rid of these transform nodes and keep my skinned rig? I've searched online & in the help files and have tried various things for two days now without success.

I'm using Maya LT 2016 SP 4 Ext 3.

Many thanks

# Answer
You need to do a selective history wipe. Take a look in one of the node editor (Or hypergraph or hypershade by preference or for older mayas) and graph the history of your object. You should be able to locate merge node(s). If your lucky this goes directly to your shape node or a tweak node. If not you need to create one and connect the merge to in mesh of merges and into rest of your history. Then delete the in history of that container and you should be free to delete the transforms and merge nodes.

Now it is very hard to be specific as I am not in front of your maya and can not see your total history. I admit that this is a bit involved.

A second thing that you may try instead of the wipe, is marking the transforms as intermediate nodes this should hide them from the outliner. Most probably your exporter will also ignore these nodes as part of unbaked history, but you never know Im not so knowledgeable about the unity exporter importer chain. Now that i think of it, this might be the easiest option.

And finally a third option. Detach your bones from the history and bake the weights down. Then delete history and reattach the bones. There are quite many tools to do this floating around as its one of those basic tricks for many rig builders. But obviously if you had some other animation nodes than just bones you would lose those. But again this might be easier than the history wipe altough it is also somewhat involved.
> 0 votes

---
Tags: maya
---


# Question
Title: Modify a character's rotation without altering it's movement
I have a character that moves around using a virtual joystick on screen (mobile game joystick) however the player doesn't face forward to the position the joystick is pointing. Whenever I modify the rotation values on script it goes off the rails and moves erratically. What can I do to achieve this movement without altering it's translation?

Here is my script:

```
     void Update()
{

    horizontal = inputJoystick.horizontal();
    vertical = inputJoystick.vertical();

    moveDirection = new Vector3(horizontal, 0, vertical);
    moveDirection = transform.TransformDirection(moveDirection);
    moveDirection *= speed;

    //rotationDirection = new Vector3(horizontal, 0, vertical);
    //transform.rotation = Quaternion.LookRotation(rotationDirection, Vector3.up);
    controller.Move(moveDirection * Time.deltaTime);

}

```

# Answer
Right now when you rotate the mesh you interfere with the movement because `transform.TransformDirection(moveDirection)` transforms from local to world space, so your move direction ends up depending on more than just the joystick's direction and as you rotate the mesh it will change. You need to keep this transform stable.

You can use a game object hierarchy like:

```
Controller
-- Mesh

```

And attach to the Controller all your movement-related components, including something like `CharacterMovementScript`, and to the Mesh attach the rotating component `CharacterRotateScript`.

```
public class CharacterMovementScript : MonoBehaviour {

    void Update () {
        var horizontal = Input.GetAxis("Horizontal");
        var vertical = Input.GetAxis("Vertical");

        var moveDirection = new Vector3(horizontal, 0, vertical);
        moveDirection = transform.TransformDirection(moveDirection);
        moveDirection *= 1.0f;

        var controller = GetComponent<CharacterController>();
        controller.Move(moveDirection * Time.deltaTime);
    }
}

public class CharacterRotateScript : MonoBehaviour {

    void Update () {
        var horizontal = Input.GetAxis("Horizontal");
        var vertical = Input.GetAxis("Vertical");

        if (horizontal != 0.0f || vertical != 0.0f) {
            var rotationDirection = new Vector3(horizontal, 0, vertical);
            transform.rotation = Quaternion.LookRotation(rotationDirection, Vector3.up);
        }
    }
}

```

Doing this should get you closer to what you're looking for, I think.
> 2 votes

---
Tags: unity, scripting
---


title: Do I really need to use a graphics API?

text:
# Question
Title: Do I really need to use a graphics API?
Is it necessary to use graphics APIs to get hardware acceleration in a 3D game? To what degree is it possible to free of dependencies to graphics-card APIs like OpenGL, DirectX~~, CUDA, OpenCL~~ or whatever else?

Can I make my own graphics API or library for my game? Even if it's hard, is it *theoretically possible* for my 3D application to independently contact the graphics driver and render everything on the GPU?

# Answer
I think a lot of the answers miss an important point: you can write apps that access hardware directly, *but not on modern operating systems*. It's not just a time problem, but a "you don't have a choice" problem.

Windows, Linux, OSX, etc. all ban direct hardware access to arbitrary applications. This is important for security reasons: you don't want any random app to be able to read arbitrary GPU memory for the same reason you don't want any random app to be able to read system memory. Things like the framebuffer for your bank account or whatnot live in GPU memory. You want that stuff isolated and protected and access controlled by your OS.

Only drivers can talk directly to most hardware, and the only way to talk to the driver is via the OS' exposed HAL and each driver's proprietary and incompatible interface. That driver interface will not only be different for each vendor but will even differ between versions of the driver itself, making it near impossible to talk directly to the interface in a consumer application. These layers are often covered by access controls that further restrict the ability for an application to access them.

So no, your game cannot just use the hardware directly, unless of course you're only targeting insecure operating systems like DOS, and your only feasible option for a game on modern consumer operating systems is to target a public API like DirectX, OpenGL or Vulkan.
> 41 votes

# Answer
Practically its necessary, yes. It's necessary because unless you want to spend years writing what is essentially driver code for the multitude of different hardware configurations out there, you need to use an API that unifies against existing drivers written by GPU vendors for all popular operating systems and hardware.

The only realistic alternative is that you don't use 3D acceleration, and instead go for software rendering which, provided it's written in something truly portable like C, will be able to run on just about any system/device. That's fine for smaller games... something like SDL is suited to this purpose... there are others out there as well. But this lacks inherent 3D capabilities so you'd have to build them yourself... which is not a trivial task.

Also remember that CPU rendering is inefficient and suffers poor performance compared to GPUs.
> 28 votes

# Answer
APIs like OpenGL or DirectX are partialy implemented by the operating system and partially implemented by the graphic driver itself.

That means when you would want to create your own low-level API which makes use of the capabilities of modern GPUs, you essentially need to write an own graphic driver. Making sure that your driver works with all common graphic cards would be quite a challenge, especially because the vendors are often not very open with their specifications.
> 8 votes

# Answer
Boot your PC into MS-DOS. Then, using your copy of the PC Game Programmers Encyclopedia, you can write directly into the card's VESA registers and into video memory. I still have the code I wrote 20 years ago to do this and render rudimentary 3D in software.

Alternatively, you can just use DirectX; it's a really thin abstraction layer, and also lets you write directly into video buffers and then swap them to the screen.

There's also the extreme approach of building your own video hardware.
> 6 votes

# Answer
In summary: Theoretically you can, but it's unfeasible, and you won't get any advantage. The limitations APIs have today become less every day, you have CUDA and OpenCL and shaders. So having full control is no more a problem.

---

Fuller explanation:

Answering this is a boring *yes*. The real question is *why*?

I hardly imagine why would you want to do this other than for learning purposes. You have to know that at some point, developers had the freedom to do anything with their CPU rendering implementations, everyone had there own API, they were in control of everything in the "pipeline". With the introduction of fixed pipeline and GPUs, everybody switched..

With GPUs you get "better" performance, but lose a lot of the freedom. Graphics developers are pushing to get that freedom back. Hence, more customization pipeline everyday. You can do almost anything using CUDA/OpenCL and even shaders, without touching the drivers.
> 4 votes

# Answer
The other answers answer your main question quite nicely: technically, it's possible, but in practice, if your goal is to broaden your customer base, you're actually doing the opposite. While wasting a huge amount of work on supporting the thousands of different hardware and OS configurations you need to support.

However, that doesn't mean you have to be 100% dependent on one particular API. You can always code up your own abstraction layer, and then swap the more specific implementations (e.g. a DirectX implementation, an OpenGL implementation, ...) in and out.

Even then, it probably isn't worth it. Just pick something that works well enough for your purposes, and be done with it. You're an indie game maker - you need to keep yourself focused on the things that make the game, not on the minutae. Just make the game!
> 4 votes

# Answer
You want to talk to hardware. You need to use a way to talk to the hardware. That way is the interface to the hardware. That's what OpenGL, DirectX, CUDA, OpenCL and whatever else are.

If you get on a lower level you are just using a lower level interface, but you are still using an interface, only one that doesn't work with as many different cards as the higher level one.
> 1 votes

# Answer
To get **3D Hardware Acceleration** without using a traditional API, you essentially need to write your own code to duplicate the functionality of the graphics driver. So the best way to learn how to do this is to look at the code of the graphics driver.

For NVIDIA cards, you should look at the open source nouveau project. They have a collection of great resources here.

For other brands of graphics cards, you can find similar projects and documentation.

Note that as has been mentioned in other answers, most modern operating systems will prevent user-space programs from directly accessing hardware, so you will need to write your code and install it as an operating system driver. Alternatively, you can use the FreeDOS operating system, which has no such restrictions, and should let you (in theory) directly access the hardware, and allow you to write a regular program that renders 3D hardware accelerated graphics. Note that, even leveraging code from an existing open source graphics driver, this would be a tremendous amount of non-trivial work (and as far as I'm aware, has never been done, and due to various reasons, might actually not be technically possible).
> 1 votes

# Answer
Getting rid of DirectX or OpenGl would not remove dependencies, it would introduce more of them. The other answers already contain several good points why it may not even be possible to talk to the graphics hardware directly (at least it's not feasible), but my first answer would be: If you did in fact write a library that abstracts all common 3d graphics hardwares into a single API you would effectively have rewritten DirectX / OpenGl. If you were to use your code to write a game you would have added your new library as a new dependency, just like you now have DirectX / OpenGl as a dependency.

By using DirectX or OpenGl your dependencies are basically saying "This code depends on a library to provide the code that explains how to run certain commands on different graphics cards". If you went without such a library you would introduce the dependency of "This code depends on graphics hardware that behaves in exactly the same way as hardware that existed when I built the game."

Abstractions like OpenGl or DirectX allow the hardware manufacturers to provide code of their own (drivers) that lead to a common code base, so games are more likely to run on hardware that didn't even exist when the game was written.
> 1 votes

# Answer
First of all, CUDA and OpenCL are not graphics apis. They are compute apis.

The problem with writing your own graphics api is that it is very complex. You could interface with the hardware directly, but there is no guarantee that if it works on a system with X CPU, X GPU, X amount of ram and X operating system it will work on a system with Y CPU, Y GPU, etc. One good point is that DirectX works with kernel-mode drivers. It is rooted into the kernel. Also, graphics apis aren't built to support GPUs. GPUs (and their drivers) are built to support them. So you pretty much can't build a graphics api unless you build your own OS and use x86 provided VGA interrupts. But you still wouldn't be able to properly interface with the GPU and you would be stuck at low resolution.

I understand that you want to build everything yourself and not use an engine or anything like that. But making your own graphics api would just create inconvenience for the user.
> 0 votes

# Answer
You can write your own driver and API, there is nothing to stop you but your ability and knowledge levels. If nothing else it would be a good learning experience, the real problem is that without having lots of previous graphic experience then even if you are a great programmer you will probably be at a loss at to what you need to do...or even to get started.

Yet the interface you make yourself will be easier to use and more stable for you than something updated behind your back constantly. So it is a little surprising to me that more people don't go this route, but the reality is few people have the technical acumen and no one wants to pay someone for years on end to learn how to do all this, then possibly have them leave the company and leave them in the lurch. The good thing to them about standardization is it makes employees much more expendable and reduces risks.
> 0 votes

---
Tags: graphics, hardware
---


# Question
Title: How to create a material that blends textures in Blender to Unity workflow
I'm new to Blender and Unity and trying to figure out the best way to create a material that will use either vertex colors or a texture map to interpolate between other textures on a single mesh. This is the sort of effect you might use when you want to have a big grassy terrain mesh with a dirt path running down the middle of it and patches of rock here and there - and instead of modeling each of those as separate pieces, you create a single shader that takes a grass, dirt and rock texture map and uses a fourth blending map to decide which to sample from.

I come from a Maya background which provides an HLSL material shader that makes this straight forward. It's not as clear to me how to do this in Blender, and in particular the best way to set it up so that it imports into Unity cleanly. I suspect that setting up the shader using Blender's cycles shading network won't create anything Unity can recognize. Blender also has the Open Shading language, but again I'm unsure how well this will work with Unity.

I could also bake all my textures, but this strikes me as wasteful of memory and bandwidth.

I have experience with both HLSL and GLSL. Is trying to do this with custom shaders the best way to do about things? What's the best way to set things up so that both Blender and Unity are happy?

# Answer
> 1 votes
After playing around with things, I've decided to use Blender's stencil map feature (which is a reduced sort of splat map). It allows me to blend between two tileable textures on the same surface using a third as a stencil without having to use huge textures.

I also had to write a custom shader in unity to have my stencil material display, but that wasn't too hard to do.

# Answer
> 0 votes
1. Look for **Vertex Paint** from Unity3D asset store. This allow you to mix texture easily.
2. Have a look at **ShaderForge** too. If you have experience with `HLSL`, once you familiarize yourself with **ShaderForge**, you can do wonders.

---
Tags: unity, shaders, blender, blending
---


# Question
Title: How to use mipmap with TextureAtlas and AssetManager
I searched on the Internet but couldn't find the way to use mipmaps with libGDX `TextureAtlas`. I want atlas instead of normal textures because as far as I know mipmap supports only 2^n width and height and my single textures have other width and height but atlas have 2048x1024.

I can use mipmaps with `Texture` using

```
TextureParameter param = new TextureParameter();
param.minFilter = TextureFilter.Linear;
param.genMipMaps = true;
manager.load("data/mytexture.png", Texture.class, param);

```

but it's not working with `TextureAtlas`, I tried to change `TextureParameter` to `TextureAtlasParameter` but this class don't have `genMipMaps` field and can't be passed to `load` method, too.

# Answer
> 1 votes
If you've a pack file along with the image, like text or json file, there probably is a line that specifies the filter used in that atlas. For example the file may be like this:

```
pack3.png
format: RGBA8888
filter: Linear,Linear
repeat: none
image1
  rotate: false
  xy: 2, 2
  size: 484, 484
  orig: 484, 484
  offset: 0, 0
  index: -1
image2
  rotate: false
  xy: 488, 2
  size: 484, 484
  orig: 484, 484
  offset: 0, 0
  index: -1

```

Just change the filter in there to the one you like (in the order `min,mag`) and save the text/json file.

# Answer
> 0 votes
As far as I am aware, the setting `genMipMap` for TextureAtlas is not available. If you're packing your images using TexturePacker to create your atlas, you can pass it Settings:

```
TexturePacker.Settings settings = new TexturePacker.Settings();

settings.combineSubdirectories = true;

settings.filterMin = Texture.TextureFilter.MipMapNearestLinear;
settings.filterMag = Texture.TextureFilter.Linear;

// Packs all textures inside your "textures" folder into a folder named "pack"
// "pack.atlas" and "pack.png" will be created.
TexturePacker.process(settings, "textures", "packs", "pack");

```

---
Tags: java, libgdx
---


title: Smoother Movement

text:
# Question
Title: Smoother Movement
I have an object in my game that moves pretty slow, a bit under a pixel every second. When the object is moving at this speed, it looks pretty choppy, because it only moves once every second.

Is there any way that I could blend the movement so that it moves at say 1/8th of a pixel every 1/8th of a second through the use of possibly anti-aliasing? Is there a way I could create a smoother transition between the two frames that makes it look like the object is consistently moving rather than moving a pixel every second?

I am currently using a float system for all of my positions and velocities, however I do not know how to render the image using floats. I am currently using `java.awt.Graphics drawImage`, which uses integers, rather than floats.

# Answer
Your question is quite broad, so here's broad answer: Store object position and render it using floats instead of integers.
> 0 votes

---
Tags: java, movement
---


# Question
Title: How to handle different resolutions in SDL2?
What is the easiest way to set different resolutions with SDL2?

I was trying to use the `SDL_RenderSetScale()` function first, but for some reason it alters the physics of the game (jumps are higher or smaller for example). My other guess was to use `SDL_RenderSetLogicalSize()`, since it was mentioned in another similar question here, but I'm not quite sure how it is supposed to work.

What I would simply like to do:

Let's say I have the game world seen in 320x240. Then no matter the resolution of the window, what we see in 320x240 is simply "scaled up". So for example: what is supposed to be 1 pixel in the "original view", becomes 4 pixel in 640x480 and so on, but all the logic still happens in 320x240. So when I move something by 1 pixel, it will move seemingly 4 pixels in 640x480, but only 1 logically.

# Answer
> 8 votes
Yes, in the situation you describe, you want to use `SDL_RenderSetLogicalSize()`.

The function takes in the width and height of the logical viewport, which in your case is the resolution you want to program your game logic in. You would call `SDL_RenderSetLogicalSize(renderer, 320, 240);`, and after that you don't need to worry about resolution scaling. SDL will scale the rendering for you automatically, and you get resolution independence.

Now, there are a couple of downsides to using `SDL_RenderSetLogicalSize`: It will letter box the viewport, meaning that in certain resolutions you will get black boxes either to the top and bottom or left and right of the window. I also had some issues with rounding errors when using `SDL_RenderSetLogicalSize`, which created ugly artifacts between tile borders. Those could however be fixed using `SDL_RenderSetIntegerScale`.

I myself use in my SDL2 game which gets upscaled while rendering custom scaling, meaning that I scale all textures that get rendered using destination rectangles. However, using the SDL scaling pipeline might just do the job for you fine, if you are okay with the limitations it sets. Feel free to ask if you are more interested in implementing scaling yourself.

---
Tags: c++, sdl2, resolution
---


# Question
Title: NPC interaction depending on conditions stored in XML
I am developing a RPG game for Android using LibGDX, at this moment the NPCs in the game have some moving AI (pathfinding), like random directions and stuff. Now I am working on the dialogue system, for that I have the following:

* DialogueManager class that just renders the current dialogue on the screen if any
* A Dialogue class which consists of an ArrayList of Strings which are the lines of the dialogue
* The NPC class holds a Dialogue object, so I can just add(text) to the dialogue.

The result of this is the following

1. The player is near a NPC and presses Action key
2. A window is opened showing the current line of the dialogue
3. When the players touches the screen, the line is replaced by the next one until there is no more lines left and the dialogue window closes and the player can move again
4. If the player talks to the same NPC, the same dialogue lines are presented

It works fine, but that is not what I really want. I need to make the dialogue to be different depending on some conditions the player has. My dialogues are stored in an XML file:

```
<npc>
    <name>Alice</name>
    <interaction>
        <dialogue>
            <line>Hello there!</line>
            <line>This is a simple dialogue</line>
        </dialogue>
    </interaction>
</npc>

```

But I want to have something like this (and I have it in the XML):

```
<npc>
    <name>Alice</name>
    <interaction>
        <dialogue condition="timesTalked" value="0">
            <line>Hello there!</line>
            <line>You are talking to me the first time!</line>
        </dialogue>
        <dialogue condition="timesTalked" value="1">
            <line>Hmmm...I remember you! Have we met before?</line>
        </dialogue>
        <dialogue condition="haveItem" value="Apple">
            <line>Is that an apple? Gimme!</line>
        </dialogue>
    </interaction>
</npc>

```

So for example "timesTalked" is a real variable name and "value" is the condition, so the first condition would say

```
if(timesTalked == 0)
   // do stuff

```

Now the problem, how can I implement that? I know how to parse the XML, but how can I make it so the conditions work? I don't want to have it all hardcoded in Java, also I dont want to use a scripting language, I think it is good to have XML because is lightweight and easy to use. Thankyou!

# Answer
> 0 votes
You would need to have some sort of map structure with all scriptable variables in it. That way your XML scripts could access the variables in a less-hardcoded way. Here's a basic example in pseudo code of a potential solution:

```
class Condition<T>
{
    String Name;
    T Value;

    String dialogLine;

    bool Check(Map<String, T> variables)
    {
        if (variables.keyExists(Name))
        {
            return variables[Name] == Value;
        }

        return false;
    }
}

```

Basically, you would create a class like this for each condition in your script flow. When you want to display a certain dialogue line, you would check the condition attached to that line and see if it returns true. All your variables that are script accessible should be stored in some sort of global map structure, which might be a little tricky (mainly because of the different object types, but there are some shortcuts to take here, such as limiting the conditions to few predefined variable types), but should be doable. Each time you change a variable, you would want to notify the global variable dictionary.

**Edit:** Now, the condition also stores the dialog line, which you could then display if `Check()` returns true.

```
class ScriptVariableManager
{
    static Map<String, int> IntValues;
    static Map<String, String> StringValues;

    static void IntValueChanged(String name, Int value)
    {
        IntValues[name] = value;
    }
}

```

This class of course doesn't have to be static, but for the sake of an example here it's easier to consider it a static class. So, when you are incrementing your `timesTalked` variable, you would also notify the variable manager that value has changed with `ScriptVariableManager.IntValueChanged("timesTalked", timesTalked);`

The condition checking code would then check the correct `Map` based on the type of the condition value.

This solution requires some hardcoding (the variable names, and letting the manager know their values), but all in all it's a lot cleaner than hardcoded if-statements. This approach is also a lot more extendable due to it's object oriented architecture. You could even allow nested conditional statements and logical operators.

---
Tags: java, libgdx, rpg, xml, npc
---


# Question
Title: Got unexpected results from perlin noise. Wondering what it is doing?
I was just messing around with perlin noise and got this. Wondering if anyone knows what it is or has seen it before.

Here is the code(LUA with love2d engine):

```
function love.load()
    love.window.setMode( 1920, 1080, {fullscreen=false})
    --Assuming you called the module perlin.lua
    newperlin = require("perlin2")
    --newperlin is a function that generates Perlin noise objects:

    myperlin = newperlin()
    --333 is seed
    myperlin = newperlin(333)
    mapHeight = 400
    mapWidth = 400

    --then, to create noise:
    scale = 0.007
    map = {}
    for x = 0, mapWidth - 1 do
        map[x] = {}
        for y = 0, mapHeight - 1 do
            map[x][y] = 0
            map[x][y] = --[[map[x][y] + --]](myperlin:noise(x * scale, y
              * scale) + 1) / 2.0 * 255.0
            --The following lines change it from a cloud to a weird image
            smin=0; smax=255
            map[x][y] =  math.floor(( map[x][y] - (-0.5) ) * 255 / ( 0.5
              - (-0.5) ) + 0)
        end
    end
end
function love.draw()
    for x = 0, mapWidth - 1 do
        for y = 0, mapHeight - 1 do
        love.graphics.setColor(map[x][y], map[x][y], map[x][y], 255)
        love.graphics.point(x,y)
        end
    end
end

function love.update()

end

function love.keyreleased(key)
    if key == "escape" then
        love.event.quit()
    end
end

```

and here is perlin.lua:

# Answer
> 2 votes
You are going outside the 0..255 range. That's why you see these color bands, since you are goint the whole range of values between 0..255 for every integer.

You are multiplying by 255 twice. This has nothing to do with perlin noise.

---
Tags: lua, image, love2d, noise
---


# Question
Title: Unwanted line between chunks in heightmap infinite terrain
I can't figure out what is causing the line between my two chunks. They are completely aligned. It must be something to do with the algorithm. I am using lua with the love2d game engine. Here is a pic:

Here is the code:

```
seed = 257
local canvas = love.graphics.newCanvas()

function Interpolate(a, b, x)
    ft = x * 3.1415927
    f = (1 - math.cos(ft)) * 0.5

    return  a*(1-f) + b*f
end

function Noise(x, y)
    n = x + y * seed
    n = bit.bxor((bit.lshift(n,13)),n)
    return ( 1.0 - ( bit.band((n * (n * n * 15731 + 789221) +
      1376312589), 0x7fffffff) / 1073741824.0))
end

function SmoothedNoise1(x, y)
    corners = ( Noise(x-1, y-1)+Noise(x+1, y-1)+Noise(x-1,
      y+1)+Noise(x+1, y+1) ) / 16
    sides   = ( Noise(x-1, y)  +Noise(x+1, y)  +Noise(x, y-1)  +Noise(x,
      y+1) ) /  8
    center  =  Noise(x, y) / 4
    return corners + sides + center
end

function InterpolatedNoise_1(x, y)
    integer_X, fractional_X = math.modf(x)
    integer_Y, fractional_Y = math.modf(y)

    v1 = SmoothedNoise1(integer_X,     integer_Y)
    v2 = SmoothedNoise1(integer_X + 1, integer_Y)
    v3 = SmoothedNoise1(integer_X,     integer_Y + 1)
    v4 = SmoothedNoise1(integer_X + 1, integer_Y + 1)

    i1 = Interpolate(v1 , v2 , fractional_X)
    i2 = Interpolate(v3 , v4 , fractional_X)

    return Interpolate(i1 , i2 , fractional_Y)
end

function getExampleMap()
    mapWidth = 400
    mapHeight = 400
    mapMin = InterpolatedNoise_1(0, 0)
    mapMax = mapMin
    map = {}
    amp = 128
    freq =32
    octaves = 6
    for x = 0, mapWidth - 1 do
        map[x] = {}
        for y = 0, mapHeight - 1 do
            map[x][y] = 0
            for i = 1, octaves do
                map[x][y] = map[x][y] + getNoiseValue(x, y, freq / i,
                  amp / i)
            end
            mapMin = math.min(mapMin, map[x][y])
            mapMax = math.max(mapMax, map[x][y])
        end
    end
    -- /*scale the values between 0 and 255 for rendering in grey
      scale.*/
    mapMultiplier = 255 / (mapMax - mapMin)
    for x = 0, mapWidth - 1 do
        for y = 0, mapHeight - 1 do
            map[x][y] = map[x][y] * mapMultiplier
        end
    end
end

function getExampleMap2()
    mapWidth = 400
    mapHeight = 400
    mapMin = InterpolatedNoise_1(0, 0)
    mapMax = mapMin
    map2 = {}
    amp = 128
    freq =32
    octaves = 6
    for x = 400, (mapWidth + 400) do
        map2[x] = {}
        for y = 0, mapHeight - 1 do
            map2[x][y] = 0
            for i = 1, octaves do
                map2[x][y] = map2[x][y] + getNoiseValue(x, y, freq / i,
                  amp / i)

            end
            mapMin = math.min(mapMin, map2[x][y])
            mapMax = math.max(mapMax, map2[x][y])
        end
    end
    -- /*scale the values between 0 and 255 for rendering in grey
      scale.*/
    mapMultiplier = 255 / (mapMax - mapMin)
    for x = 400, (mapWidth + 400) do
        for y = 0, mapHeight - 1 do
            map2[x][y] = map2[x][y] * mapMultiplier
        end
    end
end

function getNoiseValue(x, y, freq, amp)
    return InterpolatedNoise_1(x / freq, y / freq) * amp
end

function love.load()
    love.window.setMode( 1920, 1080, {fullscreen=false})
    getExampleMap()
    getExampleMap2()
end

function love.draw()

    for x = 0, mapWidth - 1 do
        for y = 0, mapHeight - 1 do
            love.graphics.setColor(map[x][y], map[x][y], map[x][y], 255)
            love.graphics.point(x,y)
        end
    end
    for x = 400, (mapWidth + 400) do
        for y = 0, mapHeight - 1 do
            love.graphics.setColor(map2[x][y], map2[x][y], map2[x][y],
              255)
            love.graphics.point(x,y)
        end
    end

end

function love.update()

end

function love.keyreleased(key)
    if key == "escape" then
        love.event.quit()
    end
end

```

If I use seed 345 there is no line.

# Answer
It's due to you scaling the map by your map multiplier. If the difference between the min and max values is different you will scale one sector higher and one lower causing the same noise value to end up as a different actual value. Instead you should have a global scaling factor that ensures you only ever map stuff to the 0..255 range.
> 1 votes

---
Tags: lua, heightmap, love2d, noise
---


title: How to simulate waves in Unity?

text:
# Question
Title: How to simulate waves in Unity?
How is it possible to simulate water in our game?

I want to make rivers and lakes for my game but I don't know how to make the waves and make the water look like it's moving.

How would I do it?

# Answer
https://docs.unity3d.com/ScriptReference/Mesh-vertices.html

> Returns a copy of the vertex positions or assigns a new vertex positions array. The number of vertices in the mesh is changed by assigning a vertex array with a different number of vertices. Note that if you resize the vertex array then all other vertex attributes (normals, colors, tangents, UVs) will be automatically resized too. RecalculateBounds will automatically be invoked if no vertices have been assigned to the mesh when setting the vertices.

this is sample wave simulate by using Mesh vertices

```
using UnityEngine;
using System.Collections;

public class WaveGen : MonoBehaviour
{
  public float scale = 0.1f;
  public float speed = 1.0f;
  public float noiseStrength = 1f;
  public float noiseWalk = 1f;

  private Vector3[] baseHeight;

  void Update () {
    Mesh mesh = GetComponent<MeshFilter> ().mesh;

    if (baseHeight == null)
      baseHeight = mesh.vertices;

    Vector3[] vertices = new Vector3[baseHeight.Length];
    for (int i=0;i<vertices.Length;i++)
    {
      Vector3 vertex = baseHeight[i];
      vertex.y += Mathf.Sin(Time.time * speed+ baseHeight[i].x + baseHeight[i].y + baseHeight[i].z) * scale;
      vertex.y += Mathf.PerlinNoise(baseHeight[i].x + noiseWalk, baseHeight[i].y + Mathf.Sin(Time.time * 0.1f)    ) * noiseStrength;
      vertices[i] = vertex;
    }
    mesh.vertices = vertices;
    mesh.RecalculateNormals();
  }
}

```

when somebody swim in water he create wave in water you should follow two link for more information about it:

1.wave in 2D game

you can easily create wave based on this gif in 3D

2.wave in 3d game

Unfortunately you can not simulate water because at any moment millions of particle to be simulated because game is Realtime(while you can do it for animations by simulating likeRealflow because there is enough time to calculate rendering). It will create lag in your game ,I prefer you use shader in your game.

> Shaders are small scripts that contain the mathematical calculations and algorithms for calculating the colour of each pixel rendered, based on the lighting input and the Material configuration. https://docs.unity3d.com/Manual/Shaders.html

Scrolling textures by modifying UV values

Water surface ripple effect for Unity
> 6 votes

---
Tags: unity
---


# Question
Title: How to make the bullet stop accurately when destination is reached?
In the below code, is the method I use to move a bullet to its destination and stop when bullet is near to destination. But the problem is the bullet is stopping not accurately, sometimes there's a small offset or span or sometimes is accurate depends on the angle.

```
public Vector2 getVelocity(Vector2 currentPosition, Vector2 targetPosition) {
    Vector2 targetDirection = targetPosition.cpy().sub(currentPosition);
    return targetDirection
            .nor();
}

final float SPEED = 6;
float pos = bulletPosition.len();
float des = bullet.destination.len();
float tol = Constants.TIME_STEP * SPEED;

if(MathUtils.isEqual(pos,des, tol)) {
    body.setLinearVelocity(0,0);
} else {
    body.setLinearVelocity(getVelocity(bulletPosition, destination).scl(SPEED));
}

```

**\[SOLVED\]**

```
if(MathUtils.isEqual(pos, des, tol)) {
     // quick & dirty way
     body.setTransform(destination, angle);
     // better way
     ...
}

```

# Answer
**Quick & Dirty Way:**
You can simply teleport the bullet to location you want after it stops.

**Long & Better Way:**
For the last moments of movement, you can disable the physics and control the movement yourself by lerp'ing *(or any other way, lerp is my favorite)* towards the target. This way, you can stop the bullet whenever you want.

---

**Edit**
I would solve the situation like this in Unity, and actually this might be a better way than the two above:

```
float minDisableDistance, minStopDistance, bulletSpeed;
Transform target;

// I'm skipping the parts that you create the bullet, and simply do the job on these:
GameObject bullet; //Assuming this is the bullet.
Rigidbody bulletRigidbody; //Assuming this is the rigidbody of bullet.

void Update()
{
    Vector3 relPos = target.position - bullet.postion;
    float distance = relPos.magnitude;

    if(distance > minDisableDistance)
    {
        //use physics.
    }
    else
    {
        bulletRigidbody.velocity = 0;

        if(distance > minStopDistance)
        {
            bullet.position += bulletSpeed * relPos.normalized * time.deltaTime;
        }
        else
        {
            bullet.position = target.position;
        }
    }
}

```
> 2 votes

# Answer
I found out the best way! I just use the Vector2 dst method to get the distance between the destination. And hooray!! it was accurate!

```
float distance = bulletPosition.cpy().dst(destination);

float tol = (Constants.TIME_STEP * SPEED) / 2;

if(distance <= tol) {

     body.setLinearVelocity(0, 0);

}

```
> 0 votes

---
Tags: libgdx, box2d
---


# Question
Title: How to create a projectile motion of a cannonball in top down view?
**Objective**

* To move the bullet with projectile motion to specific destination by touch point.

In the below image is an example of a bullet which has a projectile motion. On my observation, the bullet speed and angle is calculated base on distance.

<sub>(source: pixwerk.net)</sub>

**Where I'm at?** *(How do I move the bullet to its destination?)*

In the below code, is the method I use *to move a bullet to its destination*. But the problem is I want to create a cannonball bullet which it has a projectile motion. How do I create these tricks to make a cannon ball projectile motion like the image below.

```
public Vector2 getVelocity(Vector2 currentPosition, Vector2 targetPosition) {
    Vector2 targetDirection = targetPosition.cpy().sub(currentPosition);
    return targetDirection
            .nor();
}

```

**What I have done?** *(Currently I could move the bullet straight to its destination.)*

* Bullet is moving straight *(It's not problem)*.

**\[EDIT\]**

**Drawing a projected trajectory**

To get the trajectory point, base on iforced example. I've already have the libgdx box2d version of this.

```
b2Vec2 getTrajectoryPoint( b2Vec2& startingPosition, b2Vec2& startingVelocity, float n )
  {
      //velocity and gravity are given per second but we want time step values here
      float t = 1 / 60.0f; // seconds per time step (at 60fps)
      b2Vec2 stepVelocity = t * startingVelocity; // m/s
      b2Vec2 stepGravity = t * t * m_world->GetGravity(); // m/s/s

      return startingPosition + n * stepVelocity + 0.5f * (n*n+n) * stepGravity;
  }

```

Rendering the trajectory point

```
glColor3f(1,1,0);
  glBegin(GL_LINES);
  for (int i = 0; i < 180; i++) { // three seconds at 60fps
      b2Vec2 trajectoryPosition = getTrajectoryPoint( startingPosition, startingVelocity, i );
      glVertex2f(trajectoryPosition.x, trajectoryPosition.y );
  }
  glEnd();

```

**\[Solve\]**

The answer is to find the angle and speed by the distance by s.tarik.cetin

**Another issue encountered** *(this must be move to another question)*

This is the problem, I don't know how do I set the starting velocity. Currently in the below code, to set the `startingVelocity` and `startingPosition` where the underlined code is the part that I'm not sure.

```
    touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0);
    camera.unproject(touchPoint);

    Vector2 touch = new Vector2(touchPoint.x, touchPoint.y);
    Vector2 touchDirection = touch.cpy().sub(bulletPosition).nor(); // get the the direction from bullet position to touch point and normalize the value.

    float distance = touchDirection.dst(startingPosition);
    float angle = touch.angle();
    float speed = 6.0f; // currently the speed is fixed. I need to know the speed base on distance

    startingPosition.set(bulletPosition); // current position of the bullet
    startingVelocity.set(touchDirection.scl(speed)); // where the bullet should be

```

# Answer
> 6 votes
From wikipedia:

$$d=\frac{v\_0^2}{g}sin(2\theta)$$

When you reverse the formula to find the angle from the distance and initial speed, it becomes:

$$\eqalign{ d&=\frac{v\_0^2}{g}sin(2\theta) \\ sin(2\theta)&=\frac{dg}{v\_0^2} \\ arcsin(sin(2\theta))&=arcsin(\frac{dg}{v\_0^2}) \\ 2\theta&=arcsin(\frac{dg}{v\_0^2}) \\ \theta&=(arcsin(\frac{dg}{v\_0^2}))/2 \\ }$$

So you can define this method:

```
double gravity; //Assuming you preset this.

double GetLaunchAngle (double distance, double initialSpeed)
{
    double sineValue = distance * gravity / Math.Pow(initialSpeed, 2);

    if(sineValue < -1 || sineValue > 1)
    {
        throw new Exception("There is no possible way of reaching the given distance with given initial speed.");
    }

    return Math.Asin(sineValue) /2;
}

```

Now, you can use the launch angle to launch your projectile, so it would draw a parabola in the air, just like the image you posted.

For the explanation of why we have an exception in method, check this section of the wikipedia article about projectile movement.

---

**Edit:**
If the intial velocity is not an essential part of your game, we can eliminate the exception by letting the game decide a suitable speed by fixing the launch angle:

```
double gravity; //Assuming you preset this.
double fixedLaunchAngle = 45; //This can be any angle, but you get the most distance with least speed if your launch angle is 45 degrees.

double GetInitialSpeed (double distance)
{
    double sine = Math.Sin(2 * fixedLaunchAngle); //You can cache or even hardcode this value to avoid calculating over and over again.
    double squaredSpeed = distance * gravity / sine;
    return Math.Sqrt(squaredSpeed);
}

```

And here is a more generic version that allows you to also specify the launch angle:

```
double gravity; //Assuming you preset this.

double GetInitialSpeed (double distance, double launchAngle)
{
    double sine = Math.Sin(2 * launchAngle); //You can *not* cache this, since it is a parameter now.
    double squaredSpeed = distance * gravity / sine;
    return Math.Sqrt(squaredSpeed);
}

```

---
Tags: java, libgdx, box2d, projectile-physics
---


title: LibGDX on Android TV

text:
# Question
Title: LibGDX on Android TV
Anybody wrote games for Android TV using LibGDX?

What is the mapping of the remote control?

Can we use the game controller with LibGDX?

Thanks!

# Answer
Android TV remotes use the Dpad controls:

```
android.view.KeyEvent.KEYCODE_DPAD_UP

android.view.KeyEvent.KEYCODE_DPAD_CENTER

```

You can find the full list here: https://developer.android.com/reference/android/view/KeyEvent.html#KEYCODE\_DPAD\_CENTER
> 1 votes

---
Tags: android, libgdx
---


# Question
Title: What component should hold the character movements in ecs and fsm?
In the below code, there's a FSM for `CharacterState` that will be handled also in `CharacterSystem`. The problem was, I don't know what component should hold movements data to process in `CharacterState` or `CharacterSystem`

```
public class CharacterState implements State<Entity> {
    STANDING,
    WALKING,
    RUNNING,
    IN_PAIN,
    DEAD
}

public enum Movements {
    STAND_STILL,
    MOVE_UP,
    MOVE_DOWN,
    MOVE_LEFT,
    MOVE_RIGHT,
    MOVE_UP_RIGHT,
    MOVE_UP_LEFT,
    MOVE_DOWN_RIGHT,
    MOVE_DOWN_LEFT;
}

CharacterComponent implements Component {
    Movements movement
}

MovementComponent implements Component {
    Movements movement
}

AnimationComponent implements Component {
    IntMap<Animation> map = new IntMap<Animation>();
}

animation.map.put(Movements.MOVE_UP.order, ASSET.CHAR_MOVE_UP);

```

# Answer
I would suggest creating a new class just for holding the data if you are sure that the data belongs to multiple classes. Otherwise you can face tight coupling issues.
> 1 votes

---
Tags: java, libgdx, entity-system, state, fsm
---


# Question
Title: Problem with LAN multiplayer game in Unity
I'm trying to learn how to make an offline LAN multiplayer game in Unity.

So for example, I make something that can send a text message and make a cube XD

Now this is my problem:

(When I send a message, try connecting to the server, or when I try to create a cube I should first click on the other window!)

StartServer:

```
    using UnityEngine;
using System.Collections;

public class StartServer : MonoBehaviour {
    public Transform Taghsimobj;
    public Transform Makan;
    public Transform CubeOBJ;

    public string MSG;
    public string ResMsg;

    void Ress (string inres) {
        ResMsg = inres;

    }

    void OnGUI () {

        if (Network.peerType == NetworkPeerType.Disconnected)
        {
            if (GUILayout.Button ("StartServer"))
            {
                Network.InitializeServer(10, 25000);
            }
            if (GUILayout.Button ("Connect"))
            {
                Network.Connect ("192.168.1.101", 25000);
            }

        }
        else
        {
            if (GUILayout.Button ("CreatCube"))
            {
                Network.Instantiate (CubeOBJ, Makan.transform.position, Makan.transform.rotation, 0);
            }
            if (GUILayout.Button ("CreatChat"))
            {
                Network.Instantiate (Taghsimobj, this.transform.position, this.transform.rotation, 0);
            }
            if (GUILayout.Button ("SendMessage"))
            {
                GameObject.Find ("GameObject(Clone)").GetComponent<NetworkView>().RPC ("ResText", RPCMode.All, MSG);
            }
            MSG=GUILayout.TextField(MSG);
            GUILayout.Box (ResMsg);
        }

    }
}

```

taghsim:

```
    using UnityEngine;
using System.Collections;

public class Taghsim : MonoBehaviour {

    void Start () {
    }

    [RPC]
    void ResText (string ResIn) {
        GameObject.Find ("Main Camera").SendMessage ("Ress", ResIn);

    }
}

```

# Answer
> 4 votes
As far as I can see when you are not focusing a game instance, it goes to paused state

You must use: https://docs.unity3d.com/ScriptReference/Application-runInBackground.html

---
Tags: unity
---


# Question
Title: How can I use a 3x3 matrix within a 4x4 matrix representation?
In XNA there is only one Matrix class which is actually 4x4 matrix. How to use it to represent a 3x3 matrix?

I am trying to represent the inertia tensor of a body which is a 3x3 matrix, so I have data for only a 3x3 matrix. How can I store that in a 4x4 matrix and still have operations on it be valid?

# Answer
Put zeros in the last column and row, except for the lower-left value which should be 1. Like this:

```
V  V  V  0
V  V  V  0
V  V  V  0
0  0  0  1

```

Where `V` are the actual values you use.
> 14 votes

# Answer
This is an old post, but it lists first in google search, and the accepted answer is incorrect. Correct answer is:

```
V V 0 V
V V 0 V
0 0 1 0
V V 0 v

```

PS In context of the question my answer is not correct. Sorry for that. I had to read question more carefully and clarify that this solution is correct when using 3x3 matrix for 2d homogeneous vector (x,y,w) and 4x4 for 3d homogeneous vector (x,y,z,w).
> -1 votes

---
Tags: xna, matrix
---


# Question
Title: Draw circle around gameobject to indicate radius
I have a tower in my tower defense game im making with an upgradable radius and i would like when the user clicks the tower to show the radius as a circle around the tower

My original thought was to create a cylinder gameobject and place it flat below the tower but when enemies come torwards the tower they "trip" and start spiraling everywhere(yep had a blonde moment)

Then I took the collider off the cylinder but this caused some really wierd things to happen between the ground and the cylinder(major graphical glitches)

So is there anyway for me to draw a circle that is just kinda there as a visual?

The tower is stationary and never moves and the radius of the tower can be accessed through `radius`

Also the camera is also stationary below is a screenshot of the game view please disregard it saying "new text" those are set at runtime

# Answer
# Solution 1

> The Line Renderer takes an array of two or more points in 3D space and draws a straight line between each one. A single Line Renderer Component can thus be used to draw anything from a simple straight line, to a complex spiral. The line is always continuous; if you need to draw two or more completely separate lines, you should use multiple GameObjects, each with its own Line Renderer.
>
> https://docs.unity3d.com/Manual/class-LineRenderer.html

Great little script for Unity that makes a LineRenderer component shape into a circle or ellipse, given the number of line segments along with x and y radius.

Example 1:

```
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(LineRenderer))]
public class example : MonoBehaviour {
    [Range(0,50)]
    public int segments = 50;
    [Range(0,5)]
    public float xradius = 5;
    [Range(0,5)]
    public float yradius = 5;
    LineRenderer line;

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

        line.SetVertexCount (segments + 1);
        line.useWorldSpace = false;
        CreatePoints ();
    }

    void CreatePoints ()
    {
        float x;
        float y;
        float z;

        float angle = 20f;

        for (int i = 0; i < (segments + 1); i++)
        {
            x = Mathf.Sin (Mathf.Deg2Rad * angle) * xradius;
            y = Mathf.Cos (Mathf.Deg2Rad * angle) * yradius;

            line.SetPosition (i,new Vector3(x,y,0) );

            angle += (360f / segments);
        }
    }
}

```

Example2:

```
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(LineRenderer))]
public class example : MonoBehaviour {

        [Range(0.1f, 100f)]
        public float radius = 1.0f;

        [Range(3, 256)]
         public int numSegments = 128;

        void Start ( ) {
            DoRenderer();
        }

        public void DoRenderer ( ) {
            LineRenderer lineRenderer = gameObject.GetComponent<LineRenderer>();
            Color c1 = new Color(0.5f, 0.5f, 0.5f, 1);
        lineRenderer.material = new Material(Shader.Find("Particles/Additive"));
           lineRenderer.SetColors(c1, c1);
            lineRenderer.SetWidth(0.5f, 0.5f);
            lineRenderer.SetVertexCount(numSegments + 1);
            lineRenderer.useWorldSpace = false;

         float deltaTheta = (float) (2.0 * Mathf.PI) / numSegments;
            float theta = 0f;

            for (int i = 0 ; i < numSegments + 1 ; i++) {
                float x = radius * Mathf.Cos(theta);
                float z = radius * Mathf.Sin(theta);
            Vector3 pos = new Vector3(x, 0, z);
                lineRenderer.SetPosition(i, pos);
                theta += deltaTheta;
        }
    }
}

```

# Solution 2

thanks `@Savlon` with this comment:

> While the above answer may work, I think your end goal could be achieved much easier with a little math and a circle outline Sprite with transparency. An extra script on every object that needs only a visual representation of a radius IMO is a little overkill.

# Solution 3

Using Projector:

```
Shader "Projector/AdditiveTint" {
    Properties {
        _Color ("Tint Color", Color) = (1,1,1,1)
        _Attenuation ("Falloff", Range(0.0, 1.0)) = 1.0
        _ShadowTex ("Cookie", 2D) = "gray" {}
    }
    Subshader {
        Tags {"Queue"="Transparent"}
        Pass {
            ZWrite Off
            ColorMask RGB
            Blend SrcAlpha One // Additive blending
            Offset -1, -1

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            struct v2f {
                float4 uvShadow : TEXCOORD0;
                float4 pos : SV_POSITION;
            };

            float4x4 _Projector;
            float4x4 _ProjectorClip;

            v2f vert (float4 vertex : POSITION)
            {
                v2f o;
                o.pos = mul (UNITY_MATRIX_MVP, vertex);
                o.uvShadow = mul (_Projector, vertex);
                return o;
            }

            sampler2D _ShadowTex;
            fixed4 _Color;
            float _Attenuation;

            fixed4 frag (v2f i) : SV_Target
            {
                // Apply alpha mask
                fixed4 texCookie = tex2Dproj (_ShadowTex, UNITY_PROJ_COORD(i.uvShadow));
                fixed4 outColor = _Color * texCookie.a;
                // Attenuation
                float depth = i.uvShadow.z; // [-1 (near), 1 (far)]
                return outColor * clamp(1.0 - abs(depth) + _Attenuation, 0.0, 1.0);
            }
            ENDCG
        }
    }
}

```

Rts style unit selection in unity

# Solution 4

Using Shader:

```
Shader "Custom/RTSCircle" {
    Properties {
        _CirclePosition ("CirclePosition", Vector) = (0,0,0,0)
        _Length ("Length", Float ) = 2
        _Thickness ("Thickness", Float ) = 2
    }
    SubShader {
        Tags {
            "RenderType"="Opaque"
        }
        LOD 200
        Pass {
            Name "FORWARD"
            Tags {
                "LightMode"="ForwardBase"
            }

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #define UNITY_PASS_FORWARDBASE
            #include "UnityCG.cginc"
            #pragma multi_compile_fwdbase_fullshadows
            #pragma multi_compile_fog
            #pragma only_renderers d3d9 d3d11 glcore gles
            #pragma target 3.0
            uniform float4 _CirclePosition;
            uniform float _Length;
            uniform float _Thickness;
            struct VertexInput {
                float4 vertex : POSITION;
            };
            struct VertexOutput {
                float4 pos : SV_POSITION;
                float4 posWorld : TEXCOORD0;
                UNITY_FOG_COORDS(1)
            };
            VertexOutput vert (VertexInput v) {
                VertexOutput o = (VertexOutput)0;
                o.posWorld = mul(unity_ObjectToWorld, v.vertex);
                o.pos = UnityObjectToClipPos( v.vertex );
                UNITY_TRANSFER_FOG(o,o.pos);
                return o;
            }
            float4 frag(VertexOutput i) : COLOR {
////// Lighting:
////// Emissive:
                float node_1386 = distance(i.posWorld.rgb,_CirclePosition.rgb);
                float node_8493 = (step((node_1386-_Thickness),_Length)-step(node_1386,_Length));
                float3 emissive = float3(node_8493,node_8493,node_8493);
                float3 finalColor = emissive;
                fixed4 finalRGBA = fixed4(finalColor,1);
                UNITY_APPLY_FOG(i.fogCoord, finalRGBA);
                return finalRGBA;
            }
            ENDCG
        }
    }
    FallBack "Diffuse"
    CustomEditor "ShaderForgeMaterialInspector"
}

```

Creating a circle around your terrain
> 25 votes

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


title: C++ - Lua Preventing malicious lua code

text:
# Question
Title: C++ - Lua Preventing malicious lua code
Im working on a "game" that uses lua for scripting and i plan on making it very mod-able. However, malicious code can be written without much difficulty in lua... So how can i go about stopping that? I could block certain functions, but that wouldn't be nice for the modders and those who **really** want to will find another way.

# Answer
> could block certain functions, but that wouldn't be nice for the modders

It's perfectly nice for modders and is basically what everyone does. The only ones you need to restrict are the IO functions, of course, since Lua doesn't really include anything else out of the box.

You can instead of "blocking" them replace them with your own versions that do extra checks such as ensuring that all paths are contained within your game's script data folder (be sure to protect against `..` and funky versions of `/` vs `\`).

> and those who really want to will find another way.

Yes. Yes they will. They'll find a way to break the sandbox, or just abuse a bug in your code; a bug that might even be exploitable with a properly crafted texture file, because software is hard.

Which is why you should *never ever **never** never* auto-download mod packs for the player. That is, don't ever have the idea that you should auto-install required mods for a server that the player doesn't have. Instead have a mod repository where users can search, rate, and comment upon mods and from which any mod found to be malicious can be removed and the author banned and reported to authorities.

Miscreants still intent on abusing your players via your game will do so in so very many more stupid ways than trying to hack your script integration, even if you *do* allow unsafe scripts. The most common is still just good old social engineering: convincing players to download random malware in the guise of mods ("see $character$ in teh nudez!! jus download dis exe!!!~").
> 4 votes

---
Tags: c++, lua, modding
---


# Question
Title: Is it possible to embed a chatbot AI in a game?
Is it possible to embed the AI used in evie cleverbot into a game? For example GTA5 or Sims, to enabe conversations and mood that is if you type something and the game characters will react to what you said and respond back. Is it possible to do this?

# Answer
> 2 votes
**Is it possible?**

Sure. Natural language processing AI is a very well-researched topic. You can find lots of descriptions of the algorithms used. It's also a very popular topic for computer science dissertations, so when you don't feel like diving into this topic yourself you can likely hire someone right out of university for cheap who is familiar with the topic. You can also contact one of the companies which work in that area and license their technology.

**Is it feasible?**

A natural language AI must be trained to be able to create the illusion of conversations about certain topics. Most of the well-known chatbots like Cleverbot are crowdsourced. The developers just put the AI online and have it learn by having millions of internet users interact with them. The AI copies the users and adopts their manners of speech. That can backfire colossally like the Microsoft Twitter AI which the Internet turned into a nazi.

When you want to train a chat AI, you need to train it in the context where you want it to behave. So when you want an AI to emulate the personality of a gang member or knight or space pirate in your game, then you need to train them by interacting with them in-character and reply like you would expect them to. A lot! This is a very long and tedious process you can not easily crowdsource or automatize.

**Is it user-friendly?**

Back in the 80s, text parsers were very popular. Many adventure games were just text and the player was typing what they wanted to do ("go west", "take broom", "talk to bob", "give broom to bob"...). But such interfaces were soon replaced by point-and-click interfaces. Why? Because they were just annoying to use. Ask yourself what's more convenient to the player: Typing out the sentence "I feel honored to take on this great quest and rescue the princess from the evil wizard" or to just click on it.

With today's voice recognition technology you could maybe replace that by having the player speak into the microphone and parse their speech. I am not aware of any games which really tried to use this seriously beyond some little gimmicks.

**But if you can make it work, would it be useful for game development?**

When you design a game, NPCs usually have a certain purpose. Either mechanically (they sell the player items they need, they open doors for them) or narrative (they tell them where the next mission is, why they need to do it and make them emotionally invested). Some NPCs are just background, like the pedestrians in GTA. The player can usually only interact with them in very simple ways. But it needs to be simple to not distract the player from your actual game.

When you automatize NPC behavior with an AI, you lose control and can no longer ensure that the NPCs do what they are supposed to do when they are supposed to do it.

This can be dangerous. Imagine the player befriends GLaDOS in Portal, alienates Elizabeth in Bioshock Infinite and gets Commander Shepard in Mass Effect dishonorably discharged within the first minutes of the game. Then there would be no game to play and no story to tell anymore. Sure, you could have all of that as a failure condition resulting in instant game-over, but social interactions are just too unpredictable to estimate what conditions will break the game and what conditions won't.

A good example where too good AI can fail is Bethesda and their "Radiant AI". The developers kept experimenting with completely unscripted NPCs throughout the Elder Scrolls and 3d Fallout series. But it just wouldn't work. NPCs were killing each other over a loaf of bread, break critical quests by solving them on their own and completely ignored the player-character. In the end every game ended up using almost completely scripted NPCs and left the totally AI-controlled NPCs to the next version.

---
Tags: game-design, ai, software-engineering
---


# Question
Title: How to get connected tiles in hexagonal grid system
I've been developing a game where a number of tiles can drag into a hexagonal grid background.

For some purpose I need to find the location of same tiles into an array and merge them.

Data Layer:

Presentation Layer:

I need to find the location of all the tiles those who have same value and connected with each other.

So I need a basic idea, how can I do that or if exists any algorithm.

Note: As3 related code will help.

# Answer
Amit's Game Programming Information extensively covers many different topics, including hexagonal grids. It is possibly the best free resource available, and I wholeheartedly recommend it.

For your particular problem, I imagine you would only need to traverse the data structure containing your hex tiles by probing the tiles around your starting tile. You could use a variation of the flood fill algorithm and perform the checks recursively.
> 1 votes

---
Tags: mathematics, algorithm, path-finding, actionscript-3, hexagonal-grid
---


# Question
Title: Is a game's world-wide visibility in app stores affected by the publisher's country of residence?
I've noticed on Apple Store (and I assume on Google Playstore too) I find different games and apps in France than in the US. Does this mean if my company resides in a small country and I register my game in this country, it'll only be shown to users of my country? Or is it just a matter of some settings and I can decide to be shown all around the world, for instance for American users (which is a larger market than my country), same as game producers living there?

Does a game developer's country of residence influence how many downloads world-wide he can reach at all?

My question is about Apple Store and Google Playstore, but answers for other platforms are welcome too.

# Answer
> 2 votes
Turns out you can just set in the PlayStore and Apple Store settings in which countries you want it to be available so it doesn't matter where your company is registered, it'll potentially reach the same audience if you set world-wide visibility. Or that's how I understand.

# Answer
> 0 votes
Brand value is local. In most places, when people hear "Ghirardelli" they think nothing of it, or they guess it's a pizza place, yet in very few places of the world people will think of chocolate.

App stores rank popular apps highly, and popularity is local. A French developer can indeed launch a game that becomes a huge hit in the US, and has no success in France.

You can also compare it to music, which shows us a peculiarity: Some countries are better than average at exporting their brands to other countries, due to language, the way media works, etc. So if you launch from such a country you have better chances to become popular worldwide.

---
Tags: marketing, sales
---


title: JVM voxel game engine lag spikes

text:
# Question
Title: JVM voxel game engine lag spikes
I'm experiencing short lag spikes after some voxel chunks have been created while not moving the camera around. I profiled the application: the JVM implementation uses a lot more memory, about 2.5 times more, compared to c++ exact implementation. Also, according to the profiler, the cause of the lag is the garbage collector. But there is nothing to collect ! All voxel data is static, references are kept, nothing gets allocated while profiling. I also turned off all the rendering to make sure that native memory is not leaking. Still lagging.

What could be it ? If you need any code, I'll add it here. (Writing in scala)

# Answer
Ahh. I've been struggling with this problem for a few days. Java 8 update 92 and still parallel garbage collector as default ( . Switching to the newest G1 collector made it all nice and smooth. JVM option: `-XX:+UseG1GC`.
> 1 votes

---
Tags: performance, voxels, lag, profiling
---


title: UNITY 3D - Saving last scene

text:
# Question
Title: UNITY 3D - Saving last scene
I can't find working solution for this problem anywhere. Here is what I'm trying to do:

My Android game contains 10+ levels, user quits game on level 2. Next time user starts game it load level 2 automatically. Thats all I want, no need to save objects, just load last scene. I prefer simple javascript, but examples on the unity tutorials confuse me. Thanks for answers.

# Answer
> 1 votes
When player quit from game you should save current level number so when player will come again in game should load last current level.

when player finish current level save next level number so when player quit and run game again loaded next level.

```
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class LevelManager : MonoBehaviour {
    public enum Situation{None,Exit,Lose,Win
    };
    public Situation mycase;

    // Use this for initialization
    void Start () {
        Application.LoadLevel (PlayerPrefs.GetInt("Level"));
    }

    // Update is called once per frame
    void Update () {
        int LevelNumber = SceneManager.GetActiveScene ().buildIndex;
        switch(mycase){
        case Situation.Exit:
            PlayerPrefs.SetInt ("Level", LevelNumber); //Save Level number
            Application.Quit ();
            mycase = Situtation.None;
            break;
        case Situation.Lose:
            Application.LoadLevel(Application.loadedLevel);//Reset Level
            mycase = Situtation.None;
            break;
        case Situation.Win:
            PlayerPrefs.SetInt ("Level", LevelNumber + 1); //Save Level next number
            Application.LoadLevel (LevelNumber + 1); //Load NextLevel
            mycase = Situtation.None;
            break;
        }
    }
}

```

# Answer
> 0 votes
In your case you need just one interger value be saved and loaded.

In your scene load method, use these lines. Put your first game scene index instead of 2.

```
if (PlayerPrefs.GetInt ("current_level") == null)
{
PlayerPrefs.SetInt ("current_level", 2);//assuming level 0 is splash screen, level 1 is main menu and level 2 is first scene. Change as your need
}
Application.LoadLevel(PlayerPrefs.GetInt ("current_level"));

```

On every scene use the below method in an active object.

```
void OnApplicationQuit()
{
PlayerPrefs.SetInt ("current_level", Application.loadedLevel);
}

```

`PlayerPrefs` is not suggested in large scale data handling. Use binaryformatter, xmlserializer etc for that purposes. You will get more control over data.

If you are not using `Application.Quit ()` for game exit then use it. Or you can put the line in `OnApplicationQuit ()` to `Start ()` on an active object in all scene. That way even if you don't quit the game, just going into the scene will be saved.

Switch to JS to see how to write JS function which is written in C#

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


# Question
Title: Techniques for building out a game idea and mechanics
I've been finding that many of my projects fall into the abyss of my "game mechanic tests". That is, they aren't really "games", but rather sandboxes where I try out various things and find some mechanics that would be fun.

Now, I'd like to actually create a game out of some these ideas. Since so many of my "games" end up turning into additional sandboxes when I get distracted by a new idea(*"whoa, that's cool", and suddenly the whole game completely changes.. twenty times.. sometimes back and forth between several competing ideas*), I'd like to actually plan out the mechanics, how they will fit together, and altogether how the game will work as a whole, even though I know I still need to be semi-flexible for when things play-test differently than expected.

This is compared to my usual strategy of, "*Let's just get started and then I will build a game out of whatever I create*" mindset.

What techniques are used for planning out a game idea (*even if just roughly*), before actually just jumping in? Is there specific software which helps? How do I go about managing the planning phase in general and keeping things up-to-date if things start to change?

See this great answer on a separate question for the type of actual design I would like to work on for my game, opposed to the programming focus I generally approach things with.

# Answer
> 2 votes
A successful voyage requires four things:

(1) - A destination, (a goal)
(2) - a map, (plan)
(3) - a capable ship & crew, (skills)
(4) - and a stead-fast captain. (perseverance)

You need to clearly state a goal, preferably a small one to begin with. Outline how you will go about achieving your goal. Make sure you have the skills to do it. And promise that once you start you'll keep going.

Then begin.

You must stick to your plan, do not add a single extra thing. **NOT A SINGLE THING!** If you think of a cool thing to add to your game. Write it down, file it away, and leave it **UNTIL YOU HAVE FINISHED**. This is really important. This is the hardest part about making anything. You earn those extra cool features by completing what you set out to do in your plan. Even if the thing you are making is crap, and your specification needs extra work. **DON'T CHANGE IT** just get it finished, and you incorporate the improvements into your next project.

Once done you have to mentally affirm that the thing you just made is it's own complete stand-alone thing, and this it is finished and you will not touch it any more.

Now that you are finished, repeat the process again. If you are unhappy with the finished product you just made, make the necessary changes to your plan. Outline once again how you are going to do it. Make sure you have the skills to proceed. And start afresh.

If you can learn to set a goal, and stick to it, the rest will fall into place. I promise.

---
Tags: game-design, process
---


# Question
Title: Alternate approach to generating rivers in a procedurally generated world creates very boring rivers
I promise, I have read through the 100 other posts concerning "adding rivers to procedurally generated terrain" but I have a different problem than they typically address.

I've been reading through some literature on the subject of generating watercourses such as rivers, particularly this:

http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.18.8451&rep=rep1&type=pdf

(If you can't view the link, it isn't that important to the question, but it helps you see where I'm starting)

I've developed the following method of generating rivers:

1. Create a height map (standard x-y coordinates with a (double) z-height.
2. Generate a moisture map (this is just done through noise with a bit of tweaking).
3. Create "drip paths":
    * A drip path of tile "t" is the path a drop of water will flow when it is placed on "t". This is a pretty typical way people generate procedural rivers.
    * Water flows from a tile to its lowest neighbor.
    * A drip path ends at water or a local minimum.
4. Create a (double) variable for each tile called "watershed".
    * For each point in the landmass, iterate through its drip path, adding the moisture level of the beginning tile to each tile in the path. This ensures that rivers won't ever spawn in deserts, but can certainly run through them.
5. Rivers can be generated using these watershed values.

The last step is the step I'm struggling with. The only method I've been able to think of to use these values is to just define a river as anything with a watershed greater than X, where X can be a number I define. This works, but creates very straight, boring rivers. It also occasionally generates big blocky patches on things like cliffs, where the watershed is large because every point on the cliff is included in each watershed value.

Below, I will (try) to post two images I have created. The first is a generated world with rivers in black corresponding to tiles with sufficiently high watershed values. The second is a gradient map of (normalized) watershed values, where "black" is high values and "white" is low values. You will notice that it is mostly white, because a few tiles have extremely large watershed values (which I hope I can attribute to wider rivers).

My specific question is how, if it is possible, can I generate realistic rivers from these values? I'm pretty sure it can be done, but if there is some fundamental problem with the way I'm proceeding, let me know. Additionally, I have posted the code to my GenRiver class, which contains all the basics of the generation process described above. My actual world generation class is probably too large and complicated to post here, which I know is probably bad programming on my part. If you want any of that code I will gladly try to share it.

My final concern is that the way I'm actually generating terrain is what's accounting for these boring rivers (the terrain isn't bumpy enough). If this is the case, can someone recommend a way I add small detail to my terrain without changing the overall map shape? I'm using a basic 3D Perlin noise generator for the height map, with a frequency of 0.8, persistence of 0.5, lacunarity of 2.0, and I believe 6 or 8 octaves. Additionally, it is tiled along the x-axis.

Thank you for taking the time to read through my question. If you need more clarification, feel free to ask.

GenRiver.java

```
public class GenRiver extends Generator {

@Override
public String getName() {
    return "River";
}

@Override
public void generate() {

    MapGenerator.landGroups.stream().forEach((TileGroup tg) -> {
        tg.tiles.stream().forEach((t) -> {
            Watershed.drip(t);
        });
    });

    MapGenerator.landGroups.stream().forEach((TileGroup tg) -> {
        tg.tiles.stream().forEach((Tile t) -> {
            if (t.watershed > 20) {
                GenRiver.this.tiles.put(t, new BiomeRiver(0)); //Ignore the BiomeRiver part, it's just putting the tiles in a list for now.
            }
        });
    });
}

public static class Watershed {

    public static void drip(Tile t) {
        boolean minimum = false;
        double m = t.moisture;
        do {
            t.watershed += m;
            int i = getRiverDirection(t);
            switch(i) {
                case 0:
                    minimum = true;
                    break;
                case 1:
                    t = t.Right;
                    break;
                case 2:
                    t = t.Top;
                    break;
                case 3:
                    t = t.Left;
                    break;
                case 4:
                    t = t.Bottom;
                    break;
                default:
                    break;
            }
        } while(!t.isWater && !minimum);
    }

    private static int getRiverDirection(Tile t) {
        double a = t.z-t.Right.z;
        double b = t.z-t.Top.z;
        double c = t.z-t.Left.z;
        double d = t.z-t.Bottom.z;
        //Higher positive numbers mean a sharper drop
        double e = Math.max(Math.max(a, b), Math.max(c, d));
        if(e < 0) { return 0; }
        if(e == a) { return 1; }
        if(e == b) { return 2; }
        if(e == c) { return 3; }
        if(e == d) { return 4; }
        else { System.out.println("PROBLEM CHILD"); return 5; }
    }

}}

```

Pictures:

Note: The thicker dark lines are just topographical separations

UPDATE:

I have multiplied my height map by a ridged multi-fractal (Frequency 0.8 with 8 octaves) and achieved the following image. As it turns out, what I technically want is shorter river blocks, since that means my terrain has more variation. I believe my question has been answered, but for anyone who sees this post and wants to know what my plan is, I will be generating rivers by finding the biggest watershed values and eroding paths that take me to a specified height level. The artificial erosion will be based on the moisture of the area (its watershed value). I will essentially be following a path until it reaches a minimum, determine if that minimum should end in a lake, and if it does/doesn't, if that river should continue past the lake, at which point I will erode a path that leads me to the highest watershed. I believe that by doing this I can generate lakes above sea level that will either hold (if they are in landlocked or mountainous terrain) or break into another river.

I will continue to play with the distortion values until I get pretty terrain, but for now this will do quite well.

# Answer
I think your problem is mostly a matter of scale. Your height maps are way too undetailed to do anything but shoot straight out to sea. They are more like small islands than entire vast continents.

You would have to make them many times more detailed, then use some noise to distort them a bit more, to get some interesting rivers.

Then I would take the final result and also distort that. IE artificially add in more bends and intentionally raise a few terrain areas to force the river around.

I think if have a good start you just need to have more data and more code tweaking to get results that make sense for vast tracts of land.
> 3 votes

---
Tags: java, procedural-generation, heightmap
---


# Question
Title: Why is this orthographic projection matrix not showing my textured quad?
I've been following tutorials, mainly this one, and I am still not quite sure why my textured quad is not showing inside the frustum that I've rendered before. I can see it if and only if I don't multiply `gl_Position` with `OrthoProjMatrix * vertexmodelspace`, and instead, multiply `gl_position` with `vertexmodelspace`.

---

Here is some of my code; my Main.CPP is also available via PasteBin.

**Orthographic Projection Matrix Setup Code:**

```
void OpenGL_Engine::OrthoProjectionSetup(GLuint program)
{
    GLfloat Right = 100.0;
    GLfloat Left = 50.0;
    GLfloat Top = 100.0;
    GLfloat Bottom = 50.0;
    GLfloat zFar = 1.0;
    GLfloat zNear = -1.0;

    GLfloat LeftAndRight = 2.0f / (Right - Left);
    GLfloat TopAndBottom = 2.0f / (Top - Bottom);
    GLfloat ZFarAndZNear = - 2.0f / (zFar - zNear);

    GLfloat orthographicprojmatrix[] = {
    //XX XY XZ XW
    LeftAndRight,
    0.0, 0.0,
    - (Right + Left) / (Right - Left),

    //YX YY YZ YW
    0.0,
    TopAndBottom,
    0.0 ,
    - (Top + Bottom) / (Top - Bottom),

    //ZX ZY ZZ ZW
    0.0,
    0.0 ,
    ZFarAndZNear,

    //WX WY WZ WW
    - (zFar + zNear ) / (zFar - zNear),
    0.0,
    1.0
    };

    GLint orthographicmatrixloc = glGetUniformLocation(program, "OrthoProjMatrix");
    glUniformMatrix4fv(orthographicmatrixloc, 1, GL_TRUE,
        &orthographicprojmatrix[0]);
}

```

**Vertex Shader Code :**

```
#version 330 core

layout(location = 0) in vec4 vertexposition_modelspace;
layout(location = 1) in vec2 vertexUV;
out vec2 UV;
uniform mat4 OrthoProjMatrix;

void main()
{
    gl_Position =  OrthoProjMatrix * vertexposition_modelspace;
    UV = vertexUV;
}

```

---

I'm having problems with the orthographic projection matrix; either it is not being done correctly, not setup correctly, my shader is not setup correctly or it's the textured quad that is not in view. Please note that I do not want to use a library for this. What am I doing wrong?

# Answer
> 1 votes
In your code `orthographicprojmatrix` does not define a 4x4 orthographic projection matrix, you list an array of 14 floats, not 16, in your last two rows you missed some elements, it should be:

```
GLfloat orthographicprojmatrix[] = {
    //XX XY XZ XW
    LeftAndRight,
    0.0,
    0.0,
    -(Right + Left) / (Right - Left),

    //YX YY YZ YW
    0.0,
    TopAndBottom,
    0.0,
    -(Top + Bottom) / (Top - Bottom),

    //ZX ZY ZZ ZW
    0.0,
    0.0,
    ZFarAndZNear,
    -(zFar + zNear ) / (zFar - zNear),

    //WX WY WZ WW
    0.0,
    0.0,
    0.0,
    1.0
};

```

---
Tags: opengl
---


# Question
Title: Raycasting tutorial / vector math question
I'm checking out this nice raycasting tutorial at http://lodev.org/cgtutor/raycasting.html and have a probably very simple math question.

In the DDA algorithm I'm having trouble understanding the calcuation of the deltaDistX and deltaDistY variables, which are the distances that the ray has to travel from 1 x-side to the next x-side, or from 1 y-side to the next y-side, in the square grid that makes up the world map (see below screenshot).

In the tutorial they are calculated as follows, but without much explanation:

```
//length of ray from one x or y-side to next x or y-side
double deltaDistX = sqrt(1 + (rayDirY * rayDirY) / (rayDirX * rayDirX));
double deltaDistY = sqrt(1 + (rayDirX * rayDirX) / (rayDirY * rayDirY));

```

rayDirY and rayDirX are the direction of a ray that has been cast.

How do you get these formulas? It looks like pythagorean theorem is part of it, but somehow there's division involved here. Can anyone clue me in as to what mathematical knowledge I'm missing here, or "prove" the formula by showing how it's derived?

# Answer
> 8 votes
Ahh yes. I threw my math at it and I think I hit it. You're correct it does involve the Pythagorean theorem and some scaling.

You start with your normalized vector that represents your ray.

It has an `x` component and a `y` component. First we want to see how long it is when it travels one unit in the `x` direction. So what do we do? We want to scale the entire vector so that the `x` component equals `1`. To figure out what to scale it by, we do the following:

```
scaleFactor = 1/rayDirX;

```

Writing that out in math it's really just

```
scaledX = rayDirX * (1/rayDirX) = 1

```

So we can just call that `1`.

Then for the `y` component:

```
scaledY = rayDirY * (1/rayDirX) = rayDirY/rayDirX

```

So now we have our scaled components as `(1, rayDirY/rayDirX)`

Now, we want to know the length. Now Pythagorean comes into play. Which is

```
length = sqrt((x * x) + (y * y))

```

So plugging in our scaled components we get:

```
length = sqrt((1 * 1 ) + (rayDirY / rayDirX) * (rayDirY / rayDirX))

```

Apply some algebra and simplify and we get:

```
length = sqrt(1 + (rayDirY * rayDirY) / (rayDirX * rayDirX))

```

Same goes for the length when the `y` component travels one unit, except we'll have `(rayDirX/rayDirY, 1)` which results in

```
length = sqrt(1 + (rayDirX * rayDirX) / (rayDirY * rayDirY))

```

There we have your two equations from your question. Pretty neat. Thanks for the algebra exercise.

# Answer
> 1 votes
Assuming the unit length of each grid distance is 1.

The triangle (Triangle 1) in the posted diagram (OP question) consisting of `deltaDistX` as the hypotenuse, has the same cosine value of it's angle as cosine value of angle formed in the triangle formed by the constituents of the `rayDir# Vector` (Triangle 2)

So the following can be equated (**vector magnitudes below**), and simplified (1-3)

**Remember : cos = Base/Hypotenuse**

```
0. cosine_triangle_2                   = cosine_triangle_1
1. rayDirX/sqrt(rayDirX^2 + rayDirY^2) = 1/deltaDistX
2. (rayDirX*deltaDistX)^2              = rayDirX^2 + rayDirY^2
3. deltaDistX                          = sqrt(1+ rayDirY^2/rayDirX^2)

```

Similarly the equation for `deltaDistY` can be derived.

---
Tags: vector, raycasting, linear-algebra
---