title: Is a bitmap fast enough for a 3d game?

text:
# Question
Title: Is a bitmap fast enough for a 3d game?
I would like to learn how to create some 3d games from scratch, but i need to know what the fastest way to create a frame would be. Would it be converting an array of pixels into a bitmap, or is there some other more advanced way that is faster? I have opengl and I think that there must be some way of using that to fit my needs right?

# Answer
Writing RGB values to a block of memory is "plenty fast enough". I recently wrote a software renderer (no relevance here other than as a benchmark/source of data) and this is how it works.

However this will limit the complexity of the game, GPUs are FAR FAR better at rendering than even the best CPU. For 2d stuff though you may be able to get away with it.

Almost all 3d graphics EVER have been done on discrete hardware (a GPU) because of how much better it is. Even the SNES game Starwing did this (it had a co-processor in the cartridge)

So:

---

Can you? Yes

Should you? No
> 2 votes

# Answer
First things first. While it is a good idea to make things as fast and efficient as possible, make sure you are reasonable about it. You need to consider what your desired FPS is and consider what your targeted hardware is. Then you benchmark your game and see if it is fast enough on that hardware.

Since a large majority of monitors/displays refresh at 60Hz, this means 60FPS is a good target since going any higher will not increase the visual quality of your game. Nowadays, 120Hz monitors are becoming increasingly popular, and would be a good consideration to support, but 60Hz is still sufficient, especially for starting.

---

> Is a bitmap fast enough for a 3d game?

It really depends. There are quite a variety of methods to rendering games, each with its benefits/disadvantages.

By the sounds of what you are asking, you are talking about *software rendering*. This is essentially a hardware-independent method of drawing your frame and is done completely by software (i.e. your program is generating a bitmap which contains the result of your rendered frame, and that bitmap is drawn through your CPU).

A better solution (in terms of speed) is to rely on your GPU (graphics processing unit). This special hardware is designed for graphics operations and has many features which you can utilize to render among the following:

* More advanced (detailed) models.
* Special effects (such as blur & bloom) implemented through shaders.
* Higher-resolution of textures.
* etc...

All of these modern effects are possible because the GPU has the ability to be more efficient with the data given to it (for example, it has its own internal memory bank).

---

### What are some other options?

If you are working with a GPU, you need an interface so your program can communicate to it. OpenGL is a specification that your GPU's chip set must support and it is an interface that you can use. It is a good choice because it is portable (hence being open and not proprietary). There are other API's available, such as DirectX, but I will give you some options pertaining to OpenGL since that is what I know best and it's what you have.

1. Rendering via `glDrawPixels`. This is the closest thing to software rendering if you pass a bitmap for each frame. The difference is that now you are using your GPU to do the rendering instead of your CPU (should be faster nonetheless). The disadvantage to this method is that you are not allowing the GPU to use any of its special features to make rendering more efficient.
2. Rendering in *immediate mode*. This method involves sending drawing commands to the GPU. So, instead of drawing your bitmap on the CPU, you let the GPU draw it in its own memory space. This will allow the GPU to use more of its resources so that the generated image can be made more quickly. In OpenGL, this requires using `glBegin()` & `glEnd()` calls to draw your geometry. It also means you may use `glFlush()` or `glFinish()` to dictate when the drawing commands are executed.
3. Rendering in *retained mode* using display lists. Display lists are basically a list of drawings commands that are grouped together to be executed all at once. A display list can be executed each frame, or they can be compiled and executed later. In OpenGL, this involves these calls: `glGenLists`, `glNewList`, `glEndList`, `glCallList`, and `glDeleteLists`.
4. Using `glDrawArrays()` or `glDrawElements`. These two methods are quite similar and allow you to pass arrays of different types of data to the GPU before rendering. Some types of data could be vertices, indices, textures, colors, normals, among others and even user-defined types, all of which are stored inside *buffer objects*. Using these calls allows the GPU to store all of this data in its local memory for fast access, and you can even optimize where the data is stored based on factors such as how often the data is drawn or updated. The difference between these two calls indicate what data is necessary and how the GPU should use this data for rendering. This goes pretty in-depth, so I'm leaving it out of this post. Regardless, here are some useful links:

So, in short, these are the big four rendering methods, listed by increasing complexity as well as increasing performance gain. There are other, specialized methods of rendering, such as taking advantage of *instanced rendering*, however this is by no means material for a beginner.

---

You can use a combination of these rendering methods in order to suit your needs. You must consider the data (models) that must be drawn, and make your decision on which method(s) are most suitable to your application.

If you are trying to learn OpenGL, I'd recommend working in immediate mode to draw simple geometry. As you progress, you should shift into using `glDrawElements()` for rendering complex models.
> 0 votes

---
Tags: opengl, 3d, pixel
---


# Question
Title: Issue with my script; An object reference is required to access non-static member
I'm having an issue with my script and I don't have a clue what is wrong.

The error I get is:

> Assets/Scripts/BlackBirdDrag.cs(43,41): An object reference is required to access non-static member \`UnityEngine.Rigidbody2D.isKinematic'

Here is the script:

```
using UnityEngine;
using System.Collections;

public class BlackBirdDrag : MonoBehaviour {

  public float maxStreatch = 3.0f;
  public LineRenderer catapultLineFront;
  public LineRenderer catapultLineBack;

  private SpringJoint2D spring;
  private Transform catapult;
  private Ray rayToMouse;
  private Ray leftCatapultToProjectile;
  private float maxStretchSqr;
  private bool clickedOn;
  private float circlRadius;
  private Vector2 prevVelocity;
  //private GameObject circle;

  void Awake () {
    spring = GetComponent <SpringJoint2D> ();
    catapult = spring.connectedBody.transform;
  }

  void Start () {

    LineRendererSetup ();
    rayToMouse = new Ray(catapult.position, Vector3.zero);
    leftCatapultToProjectile = new Ray(catapultLineFront.transform.position, Vector3.zero);
    maxStretchSqr = maxStreatch * maxStreatch;
    CircleCollider2D circle = Collider2D as CircleCollider2D;
    circlRadius = circle.radius;
  }

  void Update () {
    if(clickedOn)
      Dragging ();

    if(spring != null) {
      if(!Rigidbody2D.isKinematic && prevVelocity.sqrMagnitude > Rigidbody2D.velocity.sqrMagnitude) {
        Destroy (spring);
        Rigidbody2D.velocity = prevVelocity;
      }
      if(!clickedOn)
        prevVelocity = Rigidbody2D.velocity;

      LineRendererupdate ();

    }else{
      catapultLineFront.enabled = false;
      catapultLineBack.enabled = false;
    }

  }

  void LineRendererSetup () {
    catapultLineBack.SetPosition(0,catapultLineBack.transform.position);
    catapultLineFront.SetPosition(0,catapultLineFront.transform.position);

    catapultLineBack.sortingLayerName = "foreground";
    catapultLineFront.sortingLayerName = "foreground";

    catapultLineBack.sortingOrder = 1;
    catapultLineFront.sortingOrder = 3;

  }

  void OnMouseDown () {
    spring.enabled = false;
    clickedOn = true;
  }

  void OnMouseUp () {
    spring.enabled = true;
    Rigidbody2D.isKinematic = false;
    clickedOn = false;
  }

  void LineRendererupdate () {
    Vector2 catapultToProjectile = transform.position - catapultLineFront.transform.position;
    leftCatapultToProjectile.direction = catapultToProjectile;
    Vector3 holdpoint = leftCatapultToProjectile.GetPoint(catapultToProjectile.magnitude + circlRadius);
    catapultLineBack.SetPosition(1, holdpoint);
    catapultLineFront.SetPosition(1, holdpoint);
  }

  void Dragging () {
    Vector3 mouseWorldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Vector2 catapultToMouse = mouseWorldPoint - catapult.position;

    if(catapultToMouse.sqrMagnitude > maxStretchSqr) {
      rayToMouse.direction = catapultToMouse;
      mouseWorldPoint = rayToMouse.GetPoint(maxStreatch);
    }

    mouseWorldPoint.z = 0f;
    transform.position = mouseWorldPoint;
  }

}

```

# Answer
> 1 votes
I'm not familiar with Unity.

Your issue is that you try to call methods on a *Class* instead of calling methods on an instance of a Class, i.e. on an *Object*.

Specifically, the issue shows up in two places:

First, in Update()

```
if(spring != null) {
  if(!Rigidbody2D.isKinematic ...

```

and later, in OnMouseUp()

```
  void OnMouseUp () {
    spring.enabled = true;
    Rigidbody2D.isKinematic = false;
    clickedOn = false;
  }

```

RigidBody2D doesn't have a static member called isKinematic. Only instances of it have such a member.

You must fetch the instance of the Rigidbody2D component and call the methods on that instead.

Here is an example (retrieved from here).

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public Rigidbody rb;
    void Start() {
        rb = GetComponent<Rigidbody>();
    }
    void FixedUpdate() {
        rb.AddForce(Vector3.up);
    }
}

```

Then you'll be able to call the functions on the variable `rb` if you follow the example. ie. `rb.isKinematic`

---
Tags: c#
---


# Question
Title: How can I ensure a Unity game continues to run in RAM, even if the disk it loaded from is removed?
I'd like to make a game with Unity, put the build with all the data on a USB key, plug it in another Windows computer, and run the game from the USB drive, then remove the USB drive, but keep the game running flawlessly.

How could I do that?

# Answer
You can accomplish this with a ram drive but at that point you might as well copy it to the host hard drive.
> 1 votes

---
Tags: unity, windows, memory
---


# Question
Title: Is a custom coordinate system possible in Unity
Is it possible to create a custom coordinate system (i.e the one using `double` for coordinates or the one dividing the world into 'chunks' of safe size) not constrained by the floating point precision limitations in Unity, and make systems using the built-in coordinate system use that one instead somehow?

Thanks!

# Answer
> 10 votes
If what you want is to bypass the floating inaccuracy caused by single point precision problem, for the sake of creating bigger environments for your game, then it depends on what you are willing to accept as a solution.

Let's start by making this clear: it is impossible to alter the coordinate system at the inner core of Unity. So, you can't use double-precision inherently for coordinates.

1) Depending on how you need it, however, it is possible to have custom classes in double-precision that might be of help. Of course it sill converts back to float so Unity system can work with, which is not a solution, but in many cases it might be of help even if for implementing other solutions. By the way, someone has already implemented that for Unity: a fake Vector3d, i.e. a fake Vector3 with double precision: https://github.com/sldsmkd/vector3d

And for a discussion on that piece of code, please see: http://forum.unity3d.com/threads/double-precision-vector3.190713/

2) As for the second part of your question, yes, it is possible to divide the world in areas to bypasse the problem for having big environments. But that still uses Unity's usual single precision coordinate system. That trick was first implemented in the game Dungeon Siege. The guy behind that wrote a paper on it:

http://scottbilas.com/files/2003/gdc\_san\_jose/continuous\_world\_paper.pdf

And also gave lectures about it too, from which slides are here:

http://scottbilas.com/files/2003/gdc\_san\_jose/continuous\_world\_slides.pdf

There is a video from a couple of years ago, where people from Unity comment on that solution and even explain a modern implementation of the concept in Unity:

https://www.youtube.com/watch?v=VKWvAuTGVrQ

Also, there was already a similar question in Unity QA, with an user answer that might also enlighten you on the small piece related to coord-conversion:

http://answers.unity3d.com/questions/355721/custom-world-coordinate-system-changing-spaceworld-1.html

3) Also, see this blog entry, with very interesting stuff on the problem and an idea on using multiple cameras to handle it

http://www.davenewson.com/dev/unity-notes-on-rendering-the-big-and-the-small

4) Lastly, there is also the now famous solution implemented by Kerbal Space Program, which was a game made with Unity. It is not a new solution and is sometimes refered to as "Futurma method", being related to a broader solution called "floating origin".

First of all, see this general discussion on your problem with a related idea using offsets from the player position:

http://www.udellgames.com/posts/size-matters-and-precision-too/

Specifically on Kerbal, you can see:

http://forum.kerbalspaceprogram.com/entries/54-Scaled-Space-Now-with-100-more-Floating-Origin

And also: https://www.youtube.com/watch?v=mXTxQko-JH0

For a good (although non-professional) tutorial on how to implement it:

https://www.youtube.com/watch?v=VdkkTHV\_5H8

And for a script implementing Floating Origin in Unity, see:

http://wiki.unity3d.com/index.php/Floating\_Origin

---

Lastly, a definitive must-read is the following paper, which proposed the Float Origin years ago and even describes and compares it to the other solutions such as dividing space into chunks with their own coordinates:

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

# Answer
> 4 votes
I doubt that there's a way to change the coordinate system Unity uses internally for its transforms/physics/etc. Not without recompiling the engine source at least. But that may not be necessary to get both the precision and scales you need.

Kerbal Space Program is made with Unity, and plays out over interplanetary scales. The developers have been great about sharing their process for dealing with these issues:

The basic idea is that the player characters/vehicles are kept near the origin, so that Unity's physics system remains well-behaved for interactions between vehicle parts, characters, and terrain. Similarly, when the player zooms their camera around in the map, the displayed objects are shifted around to keep the camera near the world origin to avoid visible jitter.

All the positioning & movement on planetary and interplanetary scales is done in their own code using double-precision values. Then scaled representations can be arranged in the single-precision scene for display. Since the area closest to the camera has high precision even in the single-precision scene, this downgrade doesn't produce visible errors. More distant content can have rounding errors, but this is hidden by the fact that it's far from the player's view, and is only being used for rendering.

I infer from your other question that you may have multiple simultaneous players or active regions, so you can't rely on a recentering around a single viewpoint. This complicates the floating origin solution, but doesn't rule it out. What you can do is have multiple active chunks each re-centering independently, using Unity's layers to keep them from interfering with each other's rendering or physics. When one chunk's contents are visible from a camera in another, you'll position proxy objects in the viewing chunk's layer, with their positions calculated from their position in their parent chunk and the offset of that chunk from the viewing chunk. This will handle something on the order of tens of simultaneous chunks, depending on how many distinct layers you need within each.

This will break down if you need more like hundreds of chunks actively simulating, but by that point you're well past the bleeding edge of Unity games and closer to theoretical physics simulations. Either aggressive simplification/approximation or a custom engine may be needed to handle fine-scale gameplay so widely distributed.

# Answer
> 1 votes
While I hate one word answers I think this one is a "no". Unity is designed to only use floats as far as I can tell. You'll have to convert doubles to floats yourself when using unity functions which likely defeats the purpose of using doubles to begin with.

---
Tags: unity, c#, architecture, coordinates
---


# Question
Title: Primitives LINESTRIP Closing to the first point?
I'm doing a exercise form the Frank Luna book. It ask to draw a LineStrip that looks like the red line in the picture. I'm using

```
 md3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP);

```

I'm getting the line that is yellow,blue and black and it is looping. How can I make it look like the red line?

My vertex that has the points:

```
 Vertex vertices[] =
{
    { XMFLOAT3(-5.0f, 2.0f, 0.0f) },
    { XMFLOAT3(-4.0f, -2.0f, 0.0f)    },
    { XMFLOAT3(-3.0f, 2.0f,0.0f)      },
    { XMFLOAT3(-2.0f, -2.0f, 0.0f)  },
    { XMFLOAT3(-1.0f, 2.0f, 0.0f) },
    { XMFLOAT3(0.0f, -2.0f, 0.0f)  }

};
 My indices code is:

UINT indices[] = {

    0,1,2,3,4,5

```

# Answer
> 1 votes
Looks like the index count you pass to a draw call could be wrong, that would easily cause buffer overflow, which could lead to "looping".

Also, if your vertex data consists only of a position vector, how come the vertices are colored and the position is wrong?

Either way, there are serious memory usage issues with your code that have nothing to do with the API or the book. I can only suggest you to read more carefully.

# Answer
> 0 votes
Seems I forgot to update DrawIndexed to the right number of indices.

---
Tags: directx11
---


title: Smoothing edges on procedural terrain

text:
# Question
Title: Smoothing edges on procedural terrain
Using perlin noise to create a procedural island for a tile-based game. My map is stored in a 2d array, with each tile having a type (deep water, shallow water, beach, grass, forest, hill, mountain).

What would be the most efficient way to go through my map, after it's generated, and smooth out the edges of the terrain? Using a tileset, we run into issues with a 1x1 tile that sticks out by itself.

# Answer
> 3 votes
I see 2 possibility :

* work on noise function , use less octaves.
* after noise generazion , process your map , if a tile A is surraunded by 80% of tile B, transform tile A in B.

# Answer
> 1 votes
As your map information is basically only height, you can simply convolve the map with a blur filter. There are several, computationally easiest might be a mean filter which assigns to each tile the average of all surrounding tiles:

```
height(x,y) = ROUND( (
    height(x-1,y-1) + height(x-1,y) + height(x-1,y+1) +
    height(x,y-1) + height(x,y) + height(x,y+1) +
    height(x+1,y-1) + height(x+1,y) + height(x+1,y+1)
    ) / 9)

```

# Answer
> 1 votes
You say that you have problems with 1x1 tiles. Why not simply remove them, say by turning them into the same tile as one of its four immediate neighbours?

```
for tile in map:
    if tile != tileAbove and tile != tileBelow and tile != tileLeft and tile != tileRight:
        tile = tileLeft

```

On that note, the practice of transforming tiles based on their neighbours, as a general technique, is known as cellular automata, the most famous example being Conway's Game of Life:

But is also a popular technique for procedurally generating "cave-like" maps:

I would have suggested an iteration or two of cellular automata, certainly if your requirements change, but as it is your requirement is very simple, so only a simple algorithm is required.

---
Tags: tiles, procedural-generation
---


# Question
Title: Indicate key options in a keyboard-only game
I am creating a music-based app for one of the courses I teach at a high school, so it's not for sale in the app store, it's only for my students to use. I decided to make it keyboard only partially because I didn't want to have to create a whole bunch of buttons and then link them to code. What's a good way to indicate on the screen what certain keys do? For example, the escape key will exit the user from the settings menu scene, it is also used to bring up a list of options in-game. Is there a slick way to explain what certain keys do without having some sort of legend on screen in the various scenes? Screens = scenes (I'm using SpriteKit for OS X). Remember, using the mouse is not at all an option.

# Answer
You can add an "implied tutorial" like @Anko suggests, that's a good idea for games where the player will find many type of difficulties within the campaign.

For a simple game, where you always have the same mechanics and those are really simple (for example, a fight game, or an infinite runner) you may use a "help" label (for example, "Press 'H' for Help", always shown on a discrete way either on the game scene (top right corner, for example) or in the "start" scene. When the user presses this "H", it will show an image with all the other possible keys.

I think the second option fits you better (and it is really easier to develop).
> 1 votes

---
Tags: keyboard, macos, spritekit, user-experience, ui-design
---


title: Pseudo 3D Track editor

text:
# Question
Title: Pseudo 3D Track editor
Does anyone know of a pseudo 3D track editor ? I now need one to design my stages, as manually trying to create segments, and position static and movable objects would be too time consuming.

# Answer
> 0 votes
There is Layout https://github.com/djyt/layout/wiki a track editor that works with Outrun.

The biggest issue with a 'generic' track editor would be if the format matches the goal of your game. The above track editor can create Outrun style levels with all the features of the Outrun engine (for example two parallel tracks and scenary works with patterns). IIRC it can export a XML like format, so it may suit your needs, and proxy some of the elements with your own features.

I made my own track editor inspired by this one, to support the features of my own game like this:

---
Tags: 2d
---


title: Centering an animation [libGDX]

text:
# Question
Title: Centering an animation [libGDX]
I have the following class:

```
public class AnimationDemo implements ApplicationListener {
    private SpriteBatch batch;
    private TextureAtlas textureAtlas;
    private Animation animation;
    private float elapsedTime = 0;
    private OrthographicCamera camera;
    private int width;
    private int height;
    private int texturewidth;
    private int textureheight;

    @Override
    public void create() {
        width = Gdx.graphics.getWidth();
        height = Gdx.graphics.getHeight();
        camera = new OrthographicCamera(width, height);
        camera.position.set(width / 2, height / 2, 0);
        camera.update();

        batch = new SpriteBatch();
        textureAtlas = new TextureAtlas(Gdx.files.internal("data/packone.atlas"));

        textureAtlas.getRegions().sort(new Comparator<TextureAtlas.AtlasRegion>() {
            @Override
            public int compare(TextureAtlas.AtlasRegion o1, TextureAtlas.AtlasRegion o2) {
                return Integer.parseInt(o1.name) > Integer.parseInt(o2.name) ? 1 : -1;
            }
        });

        animation = new Animation(1 / 15f, textureAtlas.getRegions());

    }

    @Override
    public void dispose() {
        batch.dispose();
        textureAtlas.dispose();
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);

        batch.begin();
        elapsedTime += Gdx.graphics.getDeltaTime();
        batch.draw(animation.getKeyFrame(elapsedTime, true), 0, 0);
        batch.end();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}

```

In the above I am using the Animation class to simply draw from a texture atlas. I am following an example from another SO question which is here but the co-ordinates don't fit my equation. How should I set these:

```
private int texturewidth;
private int textureheight;

```

Any help would be great :)

# Answer
> 0 votes
TextureRegions have their own width and height properties, as they are subimages of a full Texture. If you want to center your animation for each frame, you're going to have to use the height and width from each frame when rendering

```
@Override
public void render() {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);

    elapsedTime += Gdx.graphics.getDeltaTime();
    TextureRegion frame = animation.getKeyFrame(elapsedTime, true)
    batch.begin();
    batch.draw(frame, -frame.getRegionWidth()/2f, -frame.getRegionHeight()/2f);
    batch.end();
}

```

These values have no need to be stored in a higher scope than the render method.

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


# Question
Title: Will performance suffer if I have a really large depth range but not very many objects?
I don't know where the impression came from, but somehow it got in my head that having too small a "near" and too large a "far" in your projection at the same time would impact performance. In general that seems to hold true if there are many objects in your world like a crowded city where distant things are more likely not to be drawn because they're obstructed by closer objects. But what about fewer objects that don't obstruct each other?

I'm working out a game idea that has an "eye in the sky" camera that is expected to see a large portion of terrain kind of like an RTS (actually the camera is attached to a drone flying at altitude). I tried bringing my camera closer to the terrain and trying to make it behave like it's 50k ft in the air but nothing quite beat the feel of actually putting the camera very far away from the ground and using the field of view to zoom in and out. To make this work, I had to increase my Far plane by an extra order of magnitude.

All objects are on or near the ground in a relatively tight Y range compared to how far my camera is. I'm not drawing an obscene amount of things (at least not yet, it's still early in development) and very few objects are completely obscured by larger/closer objects. Is the large render distance of my camera going to be an issue or have side effects as I progress through development? Or should I re-approach the idea of bringing my camera closer to the world and having it simulate a larger distance (and how exactly would I do that)?

I'm using Unity 5, but I imagine my question won't be too specific to a framework.

# Answer
The issues surrounding depth range (the difference between your far plane and near plane) have more to do with *precision* than *performance*. The larger the range, the more precision you lose at the far extents using the usual non-linear depth mapping.

Performance isn't really impacted all that much, to the point where it's generally not a concern. (When you have a large viewable distance and lots of objects you generally want to be using culling methods that are earlier in the pipeline than the GPU's far-plane-based exclusion; by the time objects get that far they'll already have eaten up a ton of processing time.)
> 2 votes

---
Tags: camera
---


title: Rows of coins in libgdx?

text:
# Question
Title: Rows of coins in libgdx?
I have my coin image in the assetLoader class, then I import it into gameWorld.

**My question is, how can I draw() rows of coins without having to write out 15 different coins?**

i.e., coin1, coin2, coinRect1, coinRect2, coinX1, coinX2, etc. Wouldn't it be more efficient/easier on memory&performance to create a 'coin' class and use a loop somehow?

It's a vertical scroller so the coins should be lined up vertically and disappear individually as the playerRect intersects the coinRect.

The coins should not intersect the obstacles and the randomly generated number of coins in any row (e.g. a row of 6 coins all lined up) should be between 1 and 10. If I used a loop (somehow...) the integer i would be the randomly generated number of coins in any row, so that 1\<=i\<=10, and if coin.position intersected obstacleRect then it i would become i-1 so that the coins stopped right before the obstacle.

# Answer
I'm not familiar with libgdx, but in general:

Yes, you should definitely create a coin class. If all coins use the exact same sprite, you can make the sprite variable `static`, so that it's only created once and shared by all instances of coin. Alternatively, if there is some variance between coins (for example, some coins are red and some coins are blue), you could implement the flyweight design pattern for similar efficiency.

As for creating the coins, you can have the class `Coin` take x and y positions as constructor arguments. Then you can create as many as you like, wherever you like, and store them in some sort of data structure (for example, an ArrayList). To make them generate in a line, offset their y positions by a fixed value multplied by the iteration of the loop they're being created in. Sample code to do this (won't compile, see code comments for details):

```
// Data structure for holding coins
ArrayList<Coin> coins = new ArrayList<Coin>();

// Generate a random number between one and ten (inclusive). You'll
// need to define rand.
int max;
int min;
int randomNumber = rand.nextInt((max - min) + 1) + min;

// Create that number of coins in a line
for (int i = 0; i < randomNumber; i++)
{
    // Position the coin will be created at. You'll need to
    // define distanceBetweenCoins.
    position = Vector2(positionX,
                       positionY + (distanceBetweenCoins * i));

    // Only create a coin here if the position is not inside the
    // obstacle rectangle. You'll need to look up the libgdx method
    // to do this. This looks to be the way to go:
    // https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/math/Intersector.html
    if (!position.Intersects(obstacleRect))
    {
        coins.add(new Coin(position));
    }
}

```

Good luck!
> 2 votes

# Answer
This is a great opportunity for you to learn how to use Stage2D for your game. It already handles the rendering of tons of objects for you, including culling of actors. Actors are capable of having location, rotation, scaling, input, and actions all associated with them and it's all managed for you. Handling collision with them isn't all too difficult either, but does typically require another step.

An example of how you could use a Stage for collision, rendering, and input to do what you're looking for.

```
int score;

Stage stage;
Texture coinTexture;
Texture obstacleTexture;
Group coinLayer;
Group obstacleLayer;
Actor player;

public void create() {
    stage = new Stage();

    coinTexture = new Texture(Gdx.files.internal("data/coin.png"));
    obstacleTexture = new Texture(Gdx.files.internal("data/coin.png"));
    coinLayer = new Group();
    obstacleLayer = new Group();
    player = new Image(new Texture(Gdx.files.internal("data/player.png"));
    stage.addActor(coinLayer);
    stage.addActor(obstacleLayer);
    stage.addActor(player);

    stage.addListener(new InputListener(){
        //input code goes in here
    });

    Gdx.input.setInputProcessor(stage);
}

/**
 * We use this method to add coins, which may be added to our level
 */
private Image createCoin(float x, float y) {
    Image coin = new Image(coinTexture);
    coin.setPosition(x, y);
    return coin;
}

/**
 * We use this method to add obstacles to our level
 */
private Image createObstacle(float x, float y) {
    Image obstacle = new Image(obstacleTexture);
    obstacle.setPosition(x, y);
    obstacleLayer.addActor(obstacle);
    return obstacle;
}

/**
 * Because the layers that we are placing actors into may have unequal
 * local coordinate systems, we need to map their values to where they
 * are in the stage to calculate absolute collision.
 */
private boolean collides(Actor a, Actor b) {
    Vector2 a_coord = a.localToStageCoordinates(new Vector2(0, 0));
    Vector2 b_coord = b.localToStageCoordinates(new Vector2(0, 0));
    Rectangle a_rect = new Rectangle();
    Rectangle b_rect = new Rectangle();

    a_rect.setPosition(a_coord);
    a_rect.setSize(a.getWidth(), a.getHeight());

    b_rect.setPosition(b_coord);
    b_rect.setSize(b.getWidth(), b.getHeight());

    return a_rect.overlaps(b_rect);
}

/**
 * Here we create a line of coins until it overlaps with
 * one of our obstacles.  We generate anywhere between 1 and 10 coins
 */
private void createCoinLine(float x, float y) {
    int amount = MathUtils.random(1, 10);
    boolean done = false;
    for (int i = 0, cy = y; i < amount && !done; i++, cy += coinTexture.getHeight()) {
        Image coin = createCoin(x, cy);
        //check for coin overlapping any obstacles
        SnapshotArray<Actor> obstaclesSnapshot = obstacleLayer.getChildren();
        Actor[] obstacles = obstaclesShapshot.begin();
        for (int n = 0; n < obstacles.length && !done; n++) {
            Actor obstacle = obstacles[n];
            done = collides(coin, obstacle);
        }
        obstaclesSnapshot.end();
        //add the coin to the coin group if we did not overlap any obstacles
        if (!done) {
            coinLayer.addActor(coin);
        }
    }
}

public void render() {
    float delta = Gdx.graphics.getDeltaTime();
    stage.act(delta);

    //game movement and collision logic goes here

    //check for coin collision with player for points
    SnapshotArray<Actor> coinsSnapshot = coinLayer.getChildren();
    Actor[] coins = coinsShapshot.begin();
    for (int i = 0; i < coins.length; i++) {
         Actor coin = coins[i];
         if (collides(coin, player)){
             coin.remove();
             score++;
         }
    }
    coinsSnapshot.end();

    stage.draw();
}

```
> 0 votes

---
Tags: 2d, libgdx, scrolling
---


# Question
Title: How do I specify ARGB format textures in my input declaration?
```
    const D3D11_INPUT_ELEMENT_DESC InputLayoutDesc::Basic32[3] =
{
    {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
    {"NORMAL",   0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0},
    {"TEXCOORD", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0}
};

```

The TEXCOORD, There is no support for a image that is ARGB. Only DXGI\_FORMAT\_R32G32B32A32\_FLOAT

How can I load ARBG?

Or can I convert a ARGB TO A RGBA IMAGE?

# Answer
> 1 votes
> The TEXCOORD, There is no support for a image that is ARGB. Only DXGI\_FORMAT\_R32G32B32A32\_FLOAT

What you are defining here is the *vertex input layout*; this has nothing to do with the format of the textures you will eventually use, and instead everything to do with the format of the texture coordinates used in the vertex data. Generally these are 2D, so you'd only need `DXGI_FORMAT_R32G32_FLOAT`. `DXGI_FORMAT_R32G32B32A32_FLOAT` would be used if you needed 4D texture coordinates, which you probably don't.

Perhaps the use of the `R` and `G` in the format enumeration is just confusing you; in this case the 'name' of those channels is irrelevant, it's the width of those channels (32-bit) and amount (R and G == 2D, R, G, B and A == 4D) that matter.

You can load ARGB textures when you actually load the texture data from the disk.

# Answer
> 0 votes
This looks unusual. Texture coordinates only requires 2 component X and Y, thus you can use DXGI\_FORMAT\_R32G32\_FLOAT or DXGI\_FORMAT\_R16G16\_FLOAT or any other 2 component format. And for texture coordinates, normally you wouldn't store it in an image file anyway.

If you insist on using ARGB data, either you can convert it offline, simply by reading 4 32-bit values at a time, swap their position and write out to a file, or alternatively just read your data as is, and in vertex or pixel shader you can interpret first component as A, second as R and so on. Remember DXGI format is just a convention, your shader has the freedom to interpret data in anyway it wishes to.

By the way, I would suggest reducing floating point accuracy. Instead of using 32 bits per component, you can use 16 bits and most of the time it is pretty good, and you get 50% size reduction. 8 bit normalized can be used for texture coordinates if you know your data will not go out of the \[0,1\] range, for further reduction.

# Answer
> -1 votes
You the data for Normals and TextChords in the each others place, Try switching them like mine below:

```
static D3D11_INPUT_ELEMENT_DESC VertexLayout [ ] =
{
        {"POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D11_INPUT_PER_VERTEX_DATA,0}
        {"NORMAL",0,DXGI_FORMAT_R32G32B32_FLOAT,0, D3D11_APPEND_ALIGNED_ELEMENT,D3D11_INPUT_PER_VERTEX_DATA,0}
        {"TEXTCOORD",0,DXGI_FORMAT_R32G32_FLOAT,0, D3D11_APPEND_ALIGNED_ELEMENT,D3D11_INPUT_PER_VERTEX_DATA,0}
}

```

---
Tags: directx11
---


# Question
Title: Procedurally generate rivers for 2-d heightmap terrain
I created an algorithm to procedurally generate 2d worlds based on a heightmap grid. (I used a 2d simplex noise algorithm mapped on the inverse of the distance of each pixel from the center, to "center" the island and keep it from running off the screen, if you're interested). See below.

Now, I want to create natural-looking rivers which flow "downhill" from random points or artificial lakes to the ocean. I would like the rivers to generally travel downhill, but since you will only ever see then in a 2d view in a small window, they don't have to be 100% realistic. Its ok if they flow uphill over small bumps.

The naive approach of just checking all adjacent squares for one of lower elevation, then moving there gets stuck very easily in small holes/valleys.

My next was to use an A\* star algorithm to find paths from the start point to random points random points in the ocean, using the negative difference in height between too squares as the move cost. This also seemed to get hung up and randomly fails a lot. It's probably just an issue with my code, but I can't find the bug and its also really expensive, so I was wondering if there was any conventional wisdom about how to do this.

# Answer
> The naive approach of just checking all adjacent squares for one of lower elevation, then moving there gets stuck very easily in small holes/valleys.

That happens all the time in real life; they're called endorheic basins of which the Great Basin is an example. What you could do is simply form lakes when this happens, or ignore the rivers that don't end up in the ocean.

amitp has a great example of generating rivers, which can be summarised as:

* Find a random point in the mountains to start the river
* Follow the steepest downhill slope to the next point in your map
* Keep going until you reach the ocean

You can add a bit of noise to make the river look better, and remember to increase the width of the river as you get further away from the source, but that's about it - water flows downhill.
> 4 votes

# Answer
I don't know how it will work, but couldn't you reverse the process, going from the sea and taking a direction where elevation is same or higher. If there is no more such direction, (ie you are at a local apex)
\- if there is a higher point a bit further, then modifiy the height in between
\- or stop the river (depending on the distance from sea ?)
> 0 votes

---
Tags: 2d, procedural-generation, terrain, perlin-noise, roguelikes
---


title: Error calling another class?

text:
# Question
Title: Error calling another class?
I get the following error every time I run the code: `error: error CS0119: Expression denotes a `type', where a `variable', `value' or `method group' was expected`

```
void OnCollisionEnter()
{
  Stick ();
}

```

Can someone offer a solution?

# Answer
Well, it says that `Stick` is actually a type (a class for example), but you treating it as if it was a method. What is `Stick` and what did you intend to do with it?

UPD: As far as I understand, you're trying to make a MonoBehaviour to stick to whatever it touches using a method. It seems like there is already a class called `Stick` which interferes with your code. Calling `this.Stick ()` might solve the issue.
> 0 votes

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


# Question
Title: Finding collision point of moving projectile/bullet with a cube
I am programming a game in the spirit of Wolfenstein 3D (2D grid map, 1 cell = 1 cube) and I wanted to implement shootings. I didn't want the shootings to happen in one frame so, I wanted to see the beams flying everywhere.

So this gets a bit complicated for me to test for impacts. To be fair, I'm not really sure how I'm supposed

This is how I used to do it : I took the position of the beam and checked on the map to see if there is a wall at said position. It works great when the beam is moving very slowly. But when they go extremely fast, naturally, as you would expect, they clip through walls.

Here you can have an idea of what I'm looking for. 2D grid with white cells being air and grey cells being walls. Player is green, beam is red and dotted lines represent the beam on next frames. And orange is the collision

So I'm not exactly sure when and what to test for collisions here, as well as how to find the impact's position. What would be the most optimised way to test for collisions ?

# Answer
The problem is that your bullet is flying so quick that it passes between two game loops the collision check, in particular when it is directed towards a corner. There are a few solutions to that:

Use Matrix algebra if you have a gamemath class in place. See this solution here on stackoverflow (here). As you can see, there are quite some calculations where matrix algebra can help you if you really need a clean solution!

I use a simplified algorithm that uses real time determination for fast projectiles. The idea is to run a pre-check that simulates a slow bullet near the corner in question. This is not a mathematical solution--and could be considered more dirty than my first proposition--but should do the trick if you do not plan to have 10000 bullets to fly around at the same time. Here is how it goes.

1. Determine how much your bullet in general traverses per game loop. Call it r which is simply the length of your bullet's speed vector times delta t (or your framespeed etc.).
2. At each corner of the wall at the time of the bullet getting out, construct around a maximum distance to the bullet's maximum range circles around all corners. See pic.. You can even simplify this by only considering corners that are in direction of the bullet's flight path etc.
3. Determine during the bullet's flight if the bullet hits a circle (=is inside!). Now you know which corner is the one you need to be carefully looking at to start a refined algorithm. Note down the corner's coordinates `<cx,cy>` and where it had a positive collision check `<hitx, hity>`
4. This is the corner you have to zoom into. Construct a mathematical infinite line from the player's position and the speed vector of the bullet. (blue line).
5. Determine the intersection with the circle of this line. To do so, get the get the intersection point within the circle and move in direction to the player by distance r at an angle determined of the (negative) bullet's speed vector `<hitx-cos(angle)*r, hity-sin(angle)*r>`. (Now you calculated the position of the green dot in the pic or a bit prior to that along the flightpath).
6. Here you need to slow down in theoretical pre-test algorithm. Move pixel by pixel in direction of the bullet's speed vector until you reach the other side of the circle. For this, create a loop that moves with very small t or pixel-wise and do a point-in-rectangle-check, that is, you test whether any point along this path is inside the rectangle (wall). You can find an algorithm for this (see post here: How do I efficiently check if a point is inside a rotated rectangle?). The test is very fast, as in reality the circle buffer size around a corner is quite small and the loop could have around 20-30 iterations, which doesn't budge the performance.
> 1 votes

---
Tags: collision-detection, projectile-physics
---


title: Problems with rendering in 3ds Max

text:
# Question
Title: Problems with rendering in 3ds Max
I am working on a project in 3ds Max, but when I render the project it looks very weird. See this picture for an example:

How can I fix this?

# Answer
My guess is that you have some flipped normals. Try viewing them with the Normals/Edit Normals modifiers and see if there are any problems. also, that green cone kind of looks planar - which means when rendered you'd naturally only be able to see one side because the normals can only point in one direction.

try searching the web on ways to make your planes be visible and have normals from/in both directions. some game engines have this functionality built in as an option.
> 1 votes

---
Tags: rendering, 3dsmax
---


# Question
Title: Moving sprites using the accelerometer (Android)
In my previous game, I was moving my sprite like so:

```
float time = 10f;  //Number of seconds to pass a pre-defined area (using the screen width in this example)
float velocity = 1f/time; //work out velocity based on above time
float realX-=velocity*dt; //Move the sprite to the left (where dt is previously defined delta)
x = realX*screenWidth //convert to screen coordinates so it can be rendered

sprite.draw(x, y); //Working out the y position in the same way

```

This all works great when using touch controls. In the above example, the sprite will cross the screen in precisely 10 seconds regardless of the device on which it is running.

However, the game I'm currently developing uses the accelerometer to move the sprite. (I'm only moving the sprite left/right). Currently, what I'm doing is this:

```
@Override
public void onSensorChanged(SensorEvent event){
    tilt = event.values(axis);
}

```

Once I have the value, I apply it to my sprite movement like this:

```
float time = 10f;  //Number of seconds to pass a pre-defined area (using the screen width in this example)
float velocity = 1f/time; //work out velocity based on above time
float realX-=(tilt * velocity)*dt; //Move the sprite to the left **Now using the tilt value*
x = realX*screenWidth //convert to screen coordinates so it can be rendered

```

Although this does work - it gives nice fluid movement of the sprite, when I run it on an old Galaxy Ace, the sprite accelerates way too fast. This changes the feel of the game - note I'm talking only about acceleration here, so if I tilt the phone from left to right repeatedly, the sprite is extremely (too) responsive on the Ace, but 'just right' on my 10" tablet).

I've tried a couple of other available games and they seem to run pretty consistently across devices.

I'm wondering if my code is correct and if so, what can I do to get all devices running more consistently with regards to the accelerometer?

**Edit**

Just to clarify what it is I'm asking. I have a sprite in the middle of the screen sitting on a horizontal platform. When the device is tilted to the left, the sprite moves to the left. The rate of movement should be linked to the angle the device is tilted. So, if the device is vertical there should be no movement. If the device is tilted slowly to the left, further and further the sprite should increase in speed also (up to a limit) ie, accelerate.

The other (real world) way to think of it is sitting a ball bearing inside a vertical box (the box representing the device) and then simply tilting the box to the left and right. The ball accelerates towards to lowest corner. The sprite should act like a real ball. If it's accelerating towards to left corner, and the box is tilted in the opposite direction, then the sprite should start to decelerate to a stop, and then srart accelerating in the opposite direction. Just as the real-world ball bearing would.

My Original code achieves this, however, on some devices it's simply too responsive, it will decelerate and accelerate too quickly. And therefore change the 'feel' of the game - making it too easy for one thing.

So basically when I say the sprite movement feels 'natural' I'm referring to how the ball bearing would act/feel in the real-world.

This is exactly what I'm looking for - hope this helps!

# Answer
If I understand properly, you are approximating your physics calculations perhaps too much. When making non-representative physics calculations, it makes it very challenging to keep things straight, and causes problems down the road if you build off them.

When you compute position in a game, you do so by multiplying velocity by a small increment of time, then add to the current position:

```
float positionX = positionX + velocityX * elapsedTimeMillis;

```

When you begin to introduce acceleration, you now need to compute velocity *before* computing your position. Do this by multiplying your current acceleration by a small increment of time, and then add that to the current velocity.

```
float velocityX = velocityX + accelerationX * elapsedTimeMillis;

```

In the code you provided, you have kept your velocity at a constant, and are not adjusting it based of the accelerometer's acceleration reading.

It is also important to keep your axes consistent. When using these formulas, you still need to adjust your acceleration so that it points in the correct direction (adjust by changing sign).

---

Now, it looks like you are computing the actual screen coordinate by using normalized position and scaling to the screen. This should work very nice for cross-device compatibility. However, if you normalize the position, you also need to normalize the velocity & acceleration.

Make sure that all of your units are consistent.

---

Also, I see that you've said:

> when I run it on an old Galaxy Ace, the sprite accelerates way too fast

This screams out to me it is because of the improper physics computations. It's difficult to tell what the exact cause is from what you've described, but I'd take a look at first fixing your physics computations and see if it changes.

---

So in sum, you must:

* Keep your position, velocity, and acceleration units consistent and all must be normalized it one dimension is normalized. Or otherwise, the values must be scaled to one other (it doesn't have to be normalized between *0 to 1* or *-1 to +1*).
* Make sure you compute velocity depending on acceleration before computing position. Your position variable should be completely unaware that you are accelerating (only velocity should care).
* If you need to have further control, set the default values for velocity & position (and sometimes acceleration). If you need just a smooth glide like in your first game, the acceleration should be held at 0, but the velocity should have an initial speed. That way the acceleration doesn't change the velocity.

```
public void initVariables() {
    accelerationX = 0.0f; //0 units / second / second.
    velocityX = 10.0f; //10 units / second.
    positionX = 50.0f; //50 units.
}

public void mainGameLoop() {
    //... compute delta time

    velocityX = velocityX + accelerationX * elapsedTimeMillis;
    positionX = positionX + velocityX * elapsedTimeMillis;

    //... compute screen position based on positionX
}

@Override
public void onSensorChanged(SensorEvent event){
    //MAKE SURE THIS IS NORMALIZED AND HAS CORRECT DIRECTION.
    //MAKE ADJUSTMENTS AS NEEDED
    accelerationX = event.values(axis) / MAX_ACCELERATION_VALUE;
}

```

## An Example for Choosing Values

Since I have no context for what is valid/invalid for you game, I'll mock up an example.

**Assume:**

* Screen width maps to a *10 meter* game-space.
* Screen height remains proportional (game-space size depends on aspect ratio).
* The objective is to create a starship that moves left & right according to the accelerometer's reading. We will scale/normalize the acceleration values so that they vary between -1 & +1. The units are measured in *meters/second/second*.
* The starship should never move faster than *2m/s*. It also cannot exceed the boundaries of a 10m-wide game-space.
* Let's assume the left edge of the screen is at 0m in game-space, and the right edge is 10m.
* Let's also assume the starship is located in the center (5m game-space).

### Physics Walkthrough

**Trial 1:**

1. At first the velocity is *0*, and the acceleration is *0*.
2. Synchronized with the game-loop, the acceleration changes to *+0.35 m/s^2*
3. It takes *35millis* for the game loop to be re-executed.
4. In game-loop, the velocity games:
*`0m/s + 0.35m/s^2 × 35millis`*
5. The new velocity is *0.01225m/s* just after the first 35 milliseconds.
6. Now, the position must be updated based on the velocity:
*`5m + 0.01225m/s × 35millis`*
7. The new position is *5.00042875m*, just a small nudge.

**Trial 2:**

1. At first the velocity is *0*, and the acceleration is *0*.
2. Synchronized with the game-loop, the acceleration changes to *+1 m/s^2*
3. It takes *1s* for the game loop to be re-executed.
4. In game-loop, the velocity games:
*`0m/s + 1m/s^2 × 1s`*
5. The new velocity is *1m/s* just after the first second.
6. Now, the position must be updated based on the velocity:
*`5m + 1m/s × 1s`*
7. The new position is *6m*, a much more substantial change.

**Trial 3:**

1. At first the velocity is *0*, and the acceleration is *0*.
2. Synchronized with the game-loop, the acceleration changes to *-1 m/s^2*
3. It takes *0.5s* for the game loop to be re-executed.
4. In game-loop, the velocity games:
*`0m/s + -1m/s^2 × 0.5s`*
5. The new velocity is *-0.5m/s* just after the first 0.5 seconds.
6. Now, the position must be updated based on the velocity:
*`5m + -0.5m/s × 0.5s`*
7. The new position is *4.75m*.

**Trial 4:**

1. Now, assume position begins at *10m*
2. At first the velocity is *0*, and the acceleration is *0*.
3. Synchronized with the game-loop, the acceleration changes to *-1 m/s^2*
4. It takes *1s* for the game loop to be re-executed.
5. In game-loop, the velocity games:
*`0m/s + -1m/s^2 × 1s`*
6. The new velocity is *-1m/s* just after the first second.
7. Now, the position must be updated based on the velocity:
*`10m + -1m/s × 1s = 9m`*
8. The next game loop happens 1 second later (acceleration is held to *-1 m/s^2*)
9. Velocity changes to:
*`-1m/s + -1m/s^2 × 1s = -2m/s`*
10. Position changes to:
*`9m + -2m/s * 1s = 7m`*

Now, I assumed that the width of the screen map to 10m in game-sace Lets assume that screen dimensions are 320 x 480 (in pixels), and that the width is the larger dimension (480).

So.. we need to map these numbers:

`0m, 1m, 2m, ..., 10m`

To these numbers:

`0px, 1px, 2px, ..., 480px`

Well, this should be straightforward to compute the screen location because we know that 480px corresponds to 10m, and every other value depends on a linear relationship between game-space & screen-space:

```
screenXPosition = gameXPosition / 10m * 480px

//Re-written looks like:
screenXPosition = gameXPosition * (480px / 10m)

//Where your constant factor for the linear relationship is (480px / 10).

```

If you need to change devices, then you simply change the screen width parameter:

```
screenXPosition = gameXPosition * (screenWidthInPixels / 10m)

```

---

You mentioned you need to place limits on your velocity, that should look like this:

```
float newVelocityX = velocityX + accelerationX * elapsedTimeMillis;
if (Math.abs(newVelocityX) > MAXIMUM_SPEED_X)
{
    //If the new speed exceeds the allowed limit, then we need to make
    //the speed go to the limit, while preserving the direction of the
    //velocity.

    //Direction should be either -1 or 1.
    float direction = Math.abs(newVelocityX) / newVelocityX;

    newVelocityX = MAXIMUM_SPEED_X * direction;
}
velocityX = newVelocityX;

```
> 1 votes

# Answer
By looking at the code, I think all you need to do is to take the sign of the variable `tilt`, instead of taking its actual value, to achieve the equivalent of your touch based code. So change your `onSensorChanged` listener to this

```
@Override
public void onSensorChanged(SensorEvent event){
    tilt = event.values[axis];
    tilt = tilt>=0?1:-1;
}

```

Let me know if this is not what you are looking for.
> 0 votes

---
Tags: android, integration, accelerometer
---


title: OpenGL One Color Per VBO

text:
# Question
Title: OpenGL One Color Per VBO
Recently I have been working with OpenGL and have decided to use colors instead of textures. However, since the project I am working on is going to have a low-poly look, I want each color to stand out, and not be drawn as a gradient like OpenGl usually does.

The problem I am having is with the `flat` modifier. While it does give the nice non-gradient look, it uses a provoking vertex, which is not not good in this case.

### Here is an example of what I got and what I wanted:

(original link)

I tried looking into different solutions, and the one I think would work would be to store one color per face. However, I am not sure how to do that. Any suggestions are appreciated.

Thanks!

# Answer
It seems to me you will need to generate 3 vertices for each triangle. Because you want to use a different color per face (as opposed to per vertex), you cannot share the indices of your vertices. While you still can use an IBO (index buffer object), you will not be able to reuse any of the vertices, rendering it useless while taking up extra memory on the GPU.

With index buffers, you create a vertex and color buffer of the same length. Then each vertex in the vertex buffer corresponds to each color in the same index of the color buffer. When you draw your geometry using `glDrawElements()`, you are picking vertices (and the associated colors) by the indices listed in your IBO.

I suggest instead you use `glDrawArrays` with the mode set to `GL_TRIANGLES`. Then, you must provide your vertex and color buffers. These buffers must have the same length and should look something like this:

```
int NUM_VERTICES = 6;

//I'm explicitly showing dimensions for clarity...
float[] vertices = new float[NUM_VERTICES * 3];
float[] colors = new float[NUM_VERTICES * 3];

//Vertex buffer
vertices = new float[]
{
    -1.0f,  1.0f,  0.0f, //Vertex 1
    -1.0f, -1.0f   0.0f, //Vertex 2
     0.0f,  0.0f,  0.0f, //Vertex 3
     0.0f,  0.0f,  0.0f, //Vertex 4 (shared location with Vertex 3)
     1.0f,  1.0f,  0.0f, //Vertex 5
    -1.0f,  1.0f,  0.0f  //Vertex 6 (shared location with Vertex 1)
};

//Color buffer
colors = new float[]
{
     1.0f,  0.0f,  0.0f, //Make Vertex 1 red.
     1.0f,  0.0f,  0.0f, //Make Vertex 2 red.
     1.0f,  0.0f,  0.0f, //Make Vertex 3 red.
     0.0f,  0.0f,  1.0f, //Make Vertex 4 blue.
     0.0f,  0.0f,  1.0f, //Make Vertex 5 blue.
     0.0f,  0.0f,  1.0f  //Make Vertex 6 blue.
};

```

This creates 2 triangles. The triangles have their own set of vertices. Because each of the 3 vertices for a particular triangle all have the same corresponding color, there will not be the gradient (interpolation) within each face's 3 colors. Despite appearing as a per-face color, the colors are actually per-vertex (and not a single vertex is used for two poly's).

A faster method would be to use a shader program to dictate the color per face. This would allow you to just use a single set of vertices. You would use an IBO as normal, but you would need to send extra data down the graphics pipeline to control the color on a truly per-face basis. This is a tad complicated and left to you as an excercise ;)

I recommend you implement a basic model first. The data provided is simple enough.
> 1 votes

---
Tags: opengl, java, 3d, models, vbo
---


# Question
Title: Directional Light shadow mapping error - opengl
i need some help with shadow mapping (directional light) in opengl 3.3 and GLSL. The problem is that the shadows are not displayed correctly over de 3d models and primitives:

This is the code that generate the shadow matrix an shaders source:

```
void shadow::calculateShadowMatrixFromLightPointOfView(vector3f lightPosition, vector3f lightDirection)
{
//this method, only bind the frame buffer:
//glBindFramebuffer(GL_FRAMEBUFFER, uiFramebuffer);
fboShadowMap.bindFramebuffer();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

//this method only bind the shader
m_shader.bindShader();

float rangeX = globalData::windowWidth;
float rangeY = globalData::windowHeight;

m_ProjectionMatrix =  glm::ortho<float>(-rangeX,rangeX,-rangeY,rangeY, 0.05f,400.0);

m_currentLigthPosition = glm::lookAt(
glm::vec3(lightPosition.x,lightPosition.y,lightPosition.z),
glm::vec3(
lightDirection.x,
lightDirection.y,
lightDirection.z
),
glm::vec3(0,1,0)
);

glm::mat4 biasMatrix(
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0
);

mDepthBiasMVP = biasMatrix * m_ProjectionMatrix * m_currentLigthPosition;

}

```

This creates the frame buffer:

```
bool frameBuffer::createFrameBufferWithTexture(int a_iWidth, int a_iHeight )
{
if(uiFramebuffer != 0)return false;

glGenFramebuffers(1, &uiFramebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, uiFramebuffer);

tFramebufferTex.createEmptyTexture(a_iWidth, a_iHeight, GL_RGB);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tFramebufferTex.getTextureID(), 0);

iWidth = a_iWidth;
iHeight = a_iHeight;

return glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;

}

```

The a\_iWidth and a\_iHeight integers are 1024.

This creates the texture:

```
unsigned int CTexture::createTexture(int w,int h,bool isDepth)
{
glGenTextures(1,&uiTexture);
glBindTexture(GL_TEXTURE_2D,uiTexture);
glTexImage2D(GL_TEXTURE_2D,0,(!isDepth ? GL_RGBA8 : GL_DEPTH_COMPONENT),w,h,0,(isDepth ? GL_DEPTH_COMPONENT : GL_RGBA),GL_FLOAT,NULL);

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

int i;
i=glGetError();
if(i!=0)
{
cout << "Error happened while loading the texture: " << i << "\n";
}
glGenSamplers(1, &uiSampler);
return uiTexture;
}

```

isDepth variable, is true when i use this function to construct de framebuffer.

Then in the shaders i use for shadows:

VERTEX SHADER:

```
#version 330 core

// Input vertex data, different for all executions of this shader.
layout(location = 0) in vec3 inPosition;

// Values that stay constant for the whole mesh.
uniform mat4 depthMVP;

void main(){
gl_Position = depthMVP*vec4(inPosition.xyz,1.0f);
}

```

FRAGMENT SHADER:

# version 330 core

```
// Output data
layout(location = 0) out float fragmentdepth;

void main(){
fragmentdepth = gl_FragCoord.z;
}

```

Finally to render shadow in the "world", i use this shaders:

VERTEX SHADER:

```
#version 330

uniform mat4 projectionMatrix;
uniform mat4 modelViewMatrix;
uniform mat4 normalMatrix;
uniform mat4 modelMatrix;

uniform mat4 DepthBiasMVP;
smooth out vec4 ShadowCoord;

layout (location = 0) in vec3 inPosition;
layout (location = 1) in vec2 inCoord;
layout (location = 2) in vec3 inNormal;

smooth out vec2 texCoord;
smooth out vec3 vNormal;
smooth out vec3 vEyeSpacePos;
smooth out vec3 vWorldPos;

uniform float objOpacity;
smooth out float fObjOpacity;
uniform vec3 objColor;
smooth out vec3 vObjColor;

void main()
{
vec4 vEyeSpacePosVertex = modelViewMatrix*vec4(inPosition, 1.0);
gl_Position = projectionMatrix*vEyeSpacePosVertex;
texCoord = inCoord;
vec4 vRes = normalMatrix*vec4(inNormal, 0.0);
vNormal = vRes.xyz;
vEyeSpacePos = vEyeSpacePosVertex.xyz;
vec4 vWorldPosVertex = modelMatrix*vec4(inPosition, 1.0);
vWorldPos = vWorldPosVertex.xyz;

ShadowCoord = DepthBiasMVP * vWorldPosVertex;

fObjOpacity = objOpacity;
vObjColor = objColor;

}

```

FRAGMENT SHADER

```
#version 330

smooth in vec2 texCoord;
smooth in vec3 vNormal;
smooth in vec3 vEyeSpacePos;
smooth in vec3 vWorldPos;

smooth in vec3 vObjColor;
smooth in float fObjOpacity;
struct material
{
float specularIntensity;
float specularPower;
};
uniform material m_material;

out vec4 outputColor;

uniform sampler2D gSampler;
vec4 totalLight = vec4(0.0,0.0,0.0,0.0);
float visibility = 1.0f;

struct DirectionalLight
{
vec3 vColor;
vec3 vPosition;
vec3 vDirection;
float fAmbientIntensity;
float fStrength;
};

vec4 getDirectionalLightColor(DirectionalLight dirLight, vec3 vNormal)
{
float fDiffuseIntensity = max(0.0, dot(normalize(vNormal), -dirLight.vDirection));
return vec4(dirLight.vColor*(dirLight.fAmbientIntensity+fDiffuseIntensity)*dirLight.fStrength, 1.0);
}

uniform DirectionalLight sunLight;

uniform sampler2D shadowMap;
smooth in vec4 ShadowCoord;
vec2 poissonDisk[16] = vec2[](
vec2( -0.94201624, -0.39906216 ),
vec2( 0.94558609, -0.76890725 ),
vec2( -0.094184101, -0.92938870 ),
vec2( 0.34495938, 0.29387760 ),
vec2( -0.91588581, 0.45771432 ),
vec2( -0.81544232, -0.87912464 ),
vec2( -0.38277543, 0.27676845 ),
vec2( 0.97484398, 0.75648379 ),
vec2( 0.44323325, -0.97511554 ),
vec2( 0.53742981, -0.47373420 ),
vec2( -0.26496911, -0.41893023 ),
vec2( 0.79197514, 0.19090188 ),
vec2( -0.24188840, 0.99706507 ),
vec2( -0.81409955, 0.91437590 ),
vec2( 0.19984126, 0.78641367 ),
vec2( 0.14383161, -0.14100790 )
);

float getVisibility(sampler2D shadowMap, vec4 vShadowCoord)
{
float visibility = 1.0;
float bias = 0.005;

if(vShadowCoord.w > 0.0)
{
vec3 ShadowMapTexCoordProj = vShadowCoord.xyz / vShadowCoord.w;

if(ShadowMapTexCoordProj.x >= 0.0 && ShadowMapTexCoordProj.x < 1.0 &&
ShadowMapTexCoordProj.y >= 0.0 && ShadowMapTexCoordProj.y < 1.0 &&
ShadowMapTexCoordProj.z >= 0.0 && ShadowMapTexCoordProj.z < 1.0)
{
for (int i=0;i<4;i++)
{
int index = i;
vec4 vShadowSmooth = vec4(ShadowMapTexCoordProj.x + poissonDisk[index].x/800.0, ShadowMapTexCoordProj.y + poissonDisk[index].y/600.0, (ShadowMapTexCoordProj.z-bias)/1.0, 1.0);
float fSub = texture(shadowMap, vShadowSmooth.st).r;
visibility -= 0.1*(1.0-fSub);
}
}
}

return visibility;
}

void main()
{
vec3 vNormalized = normalize(vNormal);

totalLight += getDirectionalLightColor(sunLight, vNormal);

visibility =  getVisibility(shadowMap, ShadowCoord);

vec4 vTexColor = texture2D(gSampler, texCoord);
vTexColor.a = fObjOpacity;
vec4 vMixedColor = vTexColor*vec4(vObjColor,1.0);
outputColor = vec4(vMixedColor*totalLight*visibility);

}

```

When i see the scene, i get this results:

https://www.youtube.com/watch?v=6uS-f7qhWMI&feature=youtu.be

As you can see in the video, the objects are not affected for the shadows in the right way. All the objects are dark.

This is the order in wich the scene is rendered:

```
glViewport(0, 0, 1024, 1024);

//this function are described above
m_shadows->calculateShadowMatrixFromLightPointOfView(
dirLight->getPosition(),
dirLight->getDirection()
);

//render objects

glViewport(0, 0, globalData::windowWidth, globalData::windowHeight);

glBindFramebuffer(GL_FRAMEBUFFER, 0);

//render objects

```

i dont know what is wrong, i read a lot of tutorials but the result is always wrong.

thank you for your help.

# Answer
I found the solution: in the fragment shader in the shadow function it should be:

```
if(fSub<vShadowSmooth.z){
          visibility -= 0.1*(1.0-fSub);

          }

```
> 0 votes

---
Tags: opengl, glsl, shadows
---


# Question
Title: OpenGL binding and relations among entities
This is mostly a documentation question. I hope this is the proper place to ask and not, for example, programmers or stackoverflow.

I did not read the OpenGL specification, but from books (Red Book) and various tutorial, I cannot properly grasp how different objects and parts of the API interact and relate.

For example, I know that if a VAO is bound, then binding a VBO and setting an attribute will result in the VBO being bound to the VAO.

But there are many objects, their relation may vary. For example, the VAO is completely unrelated to the current shading program, but the outcome of drawing operations may depend on both of them.

Among all the various OpenGL components, I can see some relations like A-binds-to-B or A-and-B-are-used-by-C. All these relations concur in determining how one can alter the state of the context, how can change things, how can save things together and optimize.

I am looking for resources explaining *just* these relations. Like an UML diagram, a graph, or even a text document, which does not focus about the calls, but describes in a compact way how the various OpenGL components interact and relate one to each other.

Do you know where to find such a resource?

# Answer
> 7 votes
So, I tried painting my own diagram. It's not comprehensive, mostly because I am not interesting in some things right now, but also because I wanted it to be readable (even if it's not a formally specified graph, I think it should be easily readable).

Also, since seems to be of interest to some people, I want to share it here to get feedback and have it checked. I used the OpenGL wiki as a reference to check the correctness, but I may have introduced mistakes.

Also, if the information provided is not enough for you, or I left out important relations which are worthy to be included in the diagram, feel free to suggest it, and I will try to keep it updated.

**Again, feel free to report errors, issues or suggestions, they're warmly welcomed.**

## EDIT

1. Relation between drawing and attributes was missing: attributes must be enabled to be effective when rendering

---
Tags: opengl, documentation
---


# Question
Title: common math algorithms that aren't physics/object based
I'm starting to customize my game a lot more beyond just the engine and I'm curious what sorts of algorithms and concepts exist. There are a ton of solutions for physics and geometry-like questions, but I'm curious apart from that what is the most common. I know of things like LERP, etc. What else do you find most useful? Thanks,

# Answer
> -1 votes
Common math algorithms (besides physics and geometry) can be everything since programming can be reduced to math. :-)

But I understand what you mean. I can't offer you a detailed list of algorithms since this would be a really long list (and I don't know them all).

General topics besides the two mentioned would be:

* Artifical intelligence: you can crack your brain with support vectors and markov chains or start with the A-Star alogrithm
* Animation algorithms/systems for 2D and 3D like Spine, a loco motion and or something like Unity3D
* Not to forget tweening systems for animation
* If you like algorithms for image effects/image processing like filters can be fun (it can be fun they said :-) )
* Procedural generation of terrain is also about math
* Noise algorithms can be used for procedural texturing
* Randomness and random number generation is a big topic in the gambling sector

Well, I haven't read them (all) but here are some books that may could fit your interests. I know them but it doesn't mean I have read them all.

* Beginning Math and Physics for Game Programming: Wendy Stahler, 2004, New Riders Publishing
* Essential Mathematics for Games and Interactive Applications (Edition 1 and 2): James M van Verth and Lars Bishop, 2008, Morgan Kaufmann Publishers
* Mathematics for 3D Game Programming and Computer Graphics: Eric Lengyel, 2003, Charles River Media
* Mathematics for Game Developers: Christopher Tremblay, 2004, Thomson Course Technology PTR
* Core Techniques and Algorithms in Game Programming: Daniel Sanchez-Crespo, New Riders (I can remember there has been AI questions like: how to organize a group of soldiers going through a door,...)
* Also the "Game Programming Gems" Series and derevatives (Graphics Programming Gems, AI Programming Gems,...) offer a good collection of reusable techniques and algorithms (e.g. component based systems)

---
Tags: mathematics, algorithm
---


# Question
Title: Looking for good comunication schema in turn-based game with multiple players
based coop game that will need to communicate to the server to handle the game process. Basically I need to be able to invite to the game, progress through turns (one player at a time) and finish in win or loss. Also players could drop off from the game and the game should continue. Is there a known basic schema for this or a set of standards?

# Answer
> 2 votes
Generally I would say "No, there is no schema for this and no set of standards". This is because this purely is based on the needs of the specific game (which data is sent) and the used protocols (how the data is sent).

You can use this via plain UDP/TCP packages and write your own protocol using binary data transmission, you can use HTTP/S and send your data wrapped as XML or json. This depends on your specific needs and your existing server implementation. Altough a HTTP/S fallback will be very usefull once you game should be played on public wifis or something compareable (Admins can block unknown protocols).

Based on your short description I will try to give a small schema for this.

Lets assume the server is always/already running somewhere and waits for clients to connect. Once they connect they go into the lobby. There you can handle invites, messaging, player matching or whatever you need to "invite to the game".

Once you have your players together you can start a game session with them. In many online games this will be the part where you click play and see the "joining game" message. The session will be controlled by the server. He knows the state of every player and the total game state. For a round based game some rough state machine concept will save you a lot of troubles. This does not mean you have to implement a complete state machine framework (switch, if) should be enough for the beginning.

Clients also have such a state machine where transitions are controlled by the server. Clients start in state idle until the server knows everybody joined is ready. Then the server sends "a player X your turn" message and the client X knows he is allowed to accept game relevant input. The client waits for user action. Once the player has made his turn the client sends the action to the server which distributes them amoung the other players. The client also blocks input for the player to prevent further actions. The server receives the actions of the player and sends the client "a your turn is over message" and sends the next player "a player X your turn" message. And so on and so on.

---

Feel free to leave comments on which part I should go into detail. :-)

---
Tags: multiplayer, client-server, turn-based, logic
---


# Question
Title: In Unity, why does my IndexOutOfRange exception disappear when trying to debug it?
I don't get errors when playing from Unity "Game" tab. But when I build an executable (development or not) it stucks. I get "IndexOutOfRange" exception. Which also magically disappears (yes) when I add some debug lines:

This does not work:

```
for (int i = x1; i <= x2; i++)
for (int j = y1; j <= y2; j++)
{
    int a, b;
    a = 7 + i; // Out of range
    b = 7 + j; // Out of range

    submap[a, b] = world.WalkableMap[(int)CurrentWalkableTile.x + i, (int)CurrentWalkableTile.y + j];
}

```

This works:

```
for (int i = x1; i <= x2; i++)
for (int j = y1; j <= y2; j++)
{
    int a, b;
    a = 7 + i;
    b = 7 + j;

    if (a < 0 || a > 15) // now with this never gets out of range
        Debug.Log("A out of range: " + a);

    if (b < 0 || b > 15) // now with this never gets out of range
        Debug.Log("B out of range: " + b);

    submap[a, b] = world.WalkableMap[(int)CurrentWalkableTile.x + i, (int)CurrentWalkableTile.y + j];
}

```

I can't find any sense. The exception literally hides from me

Additional info maybe is useful:

```
x1 = (CurrentWalkableTile.x - 7) >= 0 ? -7 : -(int)CurrentWalkableTile.x;
x2 = (CurrentWalkableTile.x + 7) < world.wmap_x_size ? 7 : (world.wmap_x_size - (int)CurrentWalkableTile.x - 1);

y1 = (CurrentWalkableTile.y - 7) >= 0 ? -7 : -(int)CurrentWalkableTile.y;
y2 = (CurrentWalkableTile.y + 7) < world.wmap_y_size ? 7 : (world.wmap_y_size - (int)CurrentWalkableTile.y - 1);

```

I'd like to post more information, but I can't even debug to find the problem.

# Answer
> 1 votes
```
if (a < 0 || a > 15) // now with this never gets out of range
            Debug.Log("A out of range: " + a);

if (b < 0 || b > 15) // now with this never gets out of range
            Debug.Log("B out of range: " + b);

```

submap is bool\[15,15\] (according to comments)

then that should be

```
if (b < 0 || b >= 15)

```

or

```
if (b < 0 || b > 14)

```

index 15 would be already outside of bounds (size 15, indizes 0 - 14)

Since you couldn't trace your bug with the current if statement this leads to the conclusion your invalid index causing the exception is 15 and not a negative index.

---

Since part one didn't find the problem the next chance is to not check the submap\[a\]\[b\] array but the world.WalkableMap\[\] array.

Just do the same as with a b.

```
int c = (int)CurrentWalkableTile.x + i;
int d = (int)CurrentWalkableTile.y + j;

if (c < 0 || c >= world.WalkableMap.length) Debug.Log("C out of range: " + c);

```

`if (d < 0 || d >= world.WalkableMap[0].length) Debug.Log("d out of range: " + d);`

Because you are using two arrays but so far you haven't excluded one causing the IndexOutOfBoundsException.

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


# Question
Title: Reading messages from a certain client in Lidgren
I'm setting up a game with Lidgren, and I was wondering if there was a way to read a message from a certain client instead of just from the server as a whole, such as-

```
//Why doesn't this exist?
NetIncomingMessage message = server.Connections[0].ReadMessage();

```

This way I would be able to split up reading data from each client into it's own thread and have a separate thread for sending data to each client. Currently there is only one loop in my server, which reads packets and I fear is favoring one client more than others, as some movements made by players take a while to be received by other players. I believe reading messages separately from each client would solve this issue. With simple TcpClients, you can read from each client's stream instead of the server as a whole, and I like this functionality but also rely on the simplicity of sending packets through Lidgren and was wondering if there was a similar functionality with Lidgren.

# Answer
Each message has the sender's remote unique identifier as a field. When handling incoming messages just compare the `SenderConnection.RemoteUniqueIdentifier` to each client's `RemoteUniqueIdentifier` (you get this on the connection being established).

```
// read incoming messages
while ((var message = server.ReadMessage()) != null)
{
    // for each existing connection/player
    foreach (var player in Players)
    {
        // if this message is from this player
        if (message.SenderConnection.RemoteUniqueIdentifier == player.RemoteUniqueIdentifier)
        {
            // Handle message
        }
    }
}

```
> 1 votes

---
Tags: xna, c#, networking
---


# Question
Title: What are some good namespaces for gameplay code?
I always struggle with naming namespaces when working in a team. I'd be very thankful if someone could share your preferred way of namespacing gameplay code? At least the root namespaces.

**Edit:** As this question has been downvoted I'm adding more details - I'm basically looking for a namespacing template/examples that could be easily reused on many projects and won't have names like MarioCharacterNamespace which will obviously last a week. Also no maintenance greedy dependencies like depending on the company name or project name. I also tend to end up with very long namespaces like Game.Battle.BattleLogic.Controllers.Enemy and such that I'd also like to avoid.

So some template that's not too specific nor too general and can easily be reused on many projects at least in the beginning.

# Answer
> 2 votes
Name it in a way that will be obvious to anyone reading it. If you are going to have alot of classes for Objects, perhaps have something like `companyname.gamename.objects`, all your game logic-related classes could go in `companyname.gamename.gamelogic`

It doesnt really matter *what* you call the classes or the namespaces, but having a system that you can take a look at the first couple of lines and go "ah yes, this belongs to *this* subset of code and will probably alter *this* level of the game" can make things a lot easier, especially in larger projects.

---
Tags: c#, architecture, teamwork
---


title: EULER Integration

text:
# Question
Title: EULER Integration
I'm a little confused over using integration to move a sprite. This is how I've always achieved this:

```
float time = 10f;  //Number of seconds to pass a pre-defined area (using the screen width in this example)
float velocity = 1f/time; //work out velocity based on above time
float realX+=velocity*dt; //Move the sprite to the left (where dt is previously defined delta)
x = realX*screenWidth //convert to screen coordinates so it can be rendered

sprite.draw(x, y); //Working out the y position in the same way

```

Now, with the above code, there are 2 elements that are closely tied. Those being 'time' and 'screenWidth' - (of course, screenWidth could be replaced with another unit of distance such as a tile width in a tile-based game). However, It will always move the sprite at a speed that would take it 'time' (seconds) to cross 'screenWidth' (or whichever unit is specified).

However, I've been looking at various articles on Euler integration such as:

```
position = position + velocity * dt;
velocity = velocity + ( force / mass ) * dt;

```

So, the first line is the same my method, but the second line is working out the velocity differently (using force/mass). Also, some examples I've seen have an 'acceleration' variable (which seems logical as I assume you could just then explicitly define the acceleration).

**On acceleration**

If I need to accelerate a sprite, I have been doing something like this:

```
time-=.3;

```

And then working out the velocity again. So I'm using my time component to speed up or slow down my rate of acceleration. Not sure if this is correct.

I'm not great with physics so I would like to know - is my method valid? How would I use EULER with an 'acceleration' variable? Or how does force/mass come into play? Any help anyone could offer would be great.

# Answer
> 2 votes
You method is valid if it produces the result you want.

That said, you'll likely run into issues as the complexity of your simulation increases. The reason you've seen things like

```
position = position + velocity * dt;
velocity = velocity + ( force / mass ) * dt;

```

is because it maps on well to what actually happens in the real world.

The *velocity* is the derivative of the *position*, and the *acceleration* is the derivative of the velocity. That, coupled with the fact that you often don't assign a velocity to a physics object but rather give it an acceleration by giving it a push (applying a force) means that to find the position for the next frame you take the sum of the forces acting on the object and integrate to get the velocity, then from the velocity you get the new position.

Because Newton's laws of motion tells us that **F = ma**, you can get the **a** by divinding the sum of the forces by the mass. That will give you the acceleration. The acceleration is scaled by the elapsed time and applied to the velocity. The scale the velocity by time and apply that to the position.

The way force and mass comes into play is that if you model you physics world using the laws (or at least close approximations of) that apply to the real world a lot of things come for "free", by assigning intuitive properties to objects (like density or mass) interactions between object and how the react when subjected to forces makes sense.

As the problem you're trying to solve becomes bigger it becomes more important for the solution to be consistent, in your example you say that to accelerate something you do **time-=.3**, but to me that doesn't make sense.

I think the answer to the question "*How do we make the box move faster?*" should be "*Push it using a greater force*.", not "*Pretend less time has passed*".

To use an Euler integration with an acceleration variable you would (very simply put);

Have a physics object that looks something like this;

```
class Body {
  float mass;
  Vector position;
  Vector velocity;
  Vector force;
}

```

Then, to affect the `Body` you would apply a force;

```
body.force += additionalForce;

```

Then, to move the `Body` to the new position you would;

```
void update(float dt, Body body) {
    body.position += body.velocity * dt;
    body.velocity += (body.force / body.mass) * dt;
    body.force = Vector.empty; // Clear out the forces
}

```

---
Tags: android, physics, integration, euler-method
---


# Question
Title: In Unity, how can I register a custom file type that is always opened with my game?
I want my players to be able to create their own scenes as custom levels, save them as files (say `custom1.gamelevel`), and open them directly in my game program by double-clicking the level file, rather than having to go through the steps of opening the game, browsing to the file in my menus, and then loading that scene/level.

I already have loading custom levels covered. I just need a way to associate this custom file type with my game which can open it.

I am mainly interested in a Windows-based solution.

How can I do this?

# Answer
> 2 votes
This isn't explicitly a problem of Unity. This is something an installer could do for your programm.

Summed up: it is a registry setting

Hope this link helps:

where-in-the-registry-does-windows-store-with-which-program-to-open-certain-files @ superuser

Code samples on microsoft social network

MSDN

---
Tags: unity, windows, loading, file-format, operating-system
---


title: FixedJoint error in Unity?

text:
# Question
Title: FixedJoint error in Unity?
I get the following error every time I run the code:

error CS0120: An object reference is required to access non-static member \`UnityEngine.Joint.breakForce'

```
Joint.breakForce = Mathf.Infinity;

```

How can I properly write this? I want to set the break force to Mathf.Infinity to render the joint unbreakable.

# Answer
> 1 votes
Looks like you just need to reference the object

```
private FixedJoint joint;
void Start()
{
    joint = GetComponent<FixedJoint>();//assuming the joint and script components are attached to same gameobject.
    joint.breakForce = Mathf.Infinity;
}

```

# Answer
> 0 votes
Here `Joint` is a class. If you have an object called `Joint`, rename it to lowercase `joint`, since that is the proper naming style in C#. Your code then should become:

```
joint.breakForce = Mathf.Infinity;

```

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


# Question
Title: How to convert UV position to texture atlas pos and reapply to UV in Unity
I'm trying to apply a texture from an atlas to a mesh by reiterating through the UV array on that mesh, but I'm a bit lost on converting the coordinates.

For example, if the texture required is at x,y pixels on the material texture atlas, how can I convert and get those coordinates and apply to the mesh? I'm redrawing meshes dynamically with a chunk loader for a voxel game, I have it down for square voxels but now when adding more complex meshes, need to know how to apply the texture to these.

I imagine the code would be something like, but I'm hoping someone can help me fill in the blanks:

```
   void UpdateMesh()
   {
       UVList.Clear();
       Mesh mesh = this.GetComponent<MeshFilter>().mesh;
       for (int i = 0; i < mesh.uv.Length; i++)
       {
           UVList.Add(GetUVTextureFromAtlas(mesh.uv[i].x, mesh.uv[i].y, voxelType);
       }
      mesh.uv = UVList.ToArray();
   }
  //converts UV position expected from mesh model to position on texture atlas
  Vector2 GetUVTextureFromAtlas(float x, float y, int voxelType)
  {
        Vector2 uv;
        Vector2 textureAtlasPos = GetTextureOffset(voxelType); // returns texture pos from atlas

      //not exactly sure what this would look like for code to convert
      //from the position on the atlas to the expected UV position based on
      //expected UV position (i.e. from 1,0 to whereever the texture is on the atlas)

        return uv;
  }

```

# Answer
Your base UVs exist on a unit rectangle:

```
    (0, 1)            (1, 1)
    +-----------------+
    |                 |
    |                 |
    |                 |
    |                 |
    |                 |
    |                 |
    +-----------------+
    (0, 0)            (1, 0)

```

You're trying to map that space to a different rectangle on the atlas:

```
    (xmin, ymax)      (xmax, ymax)
    +-----------------+
    |                 |
    |                 |
    |                 |
    |                 |
    |                 |
    |                 |
    +-----------------+
    (xmin, ymin)      (xmax, ymin)

```

Since your base UVs range from `0` to `1`, it's trivial to use `Lerp`:

```
float xout = Mathf.Lerp(xmin, xmax, x);
float yout = Mathf.Lerp(ymin, ymax, y);

```

You'll need appropriate values for `xmin`, `ymin`, `xmax`, and `ymax`, which means you need to know the location and size of the texture on the atlas.

I've also assumed that those four values are in UV-space. If your atlas coordinates are specified as pixel coordinates, you can convert those to UV coordinates with `InverseLerp`. Suppose you have a texture at `(x, y)` with size `(xlen, ylen)`, on an atlas with size `(xsize, ysize)`:

```
xmin = Mathf.InverseLerp(0, xsize, x);
xmax = Mathf.InverseLerp(0, xsize, x + xlen);
ymin = Mathf.InverseLerp(0, ysize, y);
ymax = Mathf.InverseLerp(0, ysize, y + ylen);

```

It's absolutely possible to improve on this method, if you're comfortable with the math, but that's the basic gist of it.
> 2 votes

---
Tags: unity, c#, uv-mapping, mesh
---


title: Can not change rotation of prefabs

text:
# Question
Title: Can not change rotation of prefabs
```
var angle = temp.transform.rotation.eulerAngles;
            angle.y = 90;

temp.transform.rotation = Quaternion.Euler (angle);

```

I have tried this and some other variation to change the rotation of the instantiated prefab but it does not work at all.

How can I fix this?

# Answer
You could create an already rotated object by using

```
GameObject instance = GameObject.Instantiate (prefab, position, rotation)

```

where `rotation` is a `Quaternion` you compute earlier in the code like this:

```
Quaternion rotation = Quaternion.Euler (0, 90, 0)

```
> 1 votes

---
Tags: unity
---