title: Keep cube spinning after fling

text:
# Question
Title: Keep cube spinning after fling
So I've been trying to get started with game development for Android using Unity3D. For my first project I've made a simple cube that you can spin using touch. For that I have the following code:

```
using UnityEngine;
using System.Collections;

public class TouchScript : MonoBehaviour {

float speed = 0.4f;
bool canRotate = false;
Transform cachedTransform;

public bool CanRotate {
    get { return canRotate; }
    private set { canRotate = value; }
}

void Start () {
    // Make reference to transform
    cachedTransform = transform;
}

// Update is called once per frame
void Update () {
    if (Input.touchCount > 0) {
        Touch touch = Input.GetTouch (0);

        // Switch through touch events
        switch (Input.GetTouch (0).phase) {
        case TouchPhase.Began:
            if (VerifyTouch (touch))
                CanRotate = true;
            break;
        case TouchPhase.Moved:
            if (CanRotate)
                RotateObject (touch);
            break;
        case TouchPhase.Ended:
            CanRotate = false;
            break;
        }
    }
}

bool VerifyTouch (Touch touch) {
    Ray ray = Camera.main.ScreenPointToRay (touch.position);
    RaycastHit hit;

    // Check if there is a collider attached already, otherwise add one on the fly
    if (collider == null) gameObject.AddComponent (typeof(BoxCollider));

    if (Physics.Raycast (ray, out hit)) {
        if (hit.collider.gameObject == this.gameObject)
            return true;
    }
    return false;
}

void RotateObject (Touch touch) {
    cachedTransform.Rotate (new Vector3 (touch.deltaPosition.y, -touch.deltaPosition.x, 0) * speed, Space.World);
}

}

```

The above code works fine. However, I'm wondering how I can keep the cube spinning after the user lifts his finger. The user should be able to "fling" the cube, which would keep spinning and after a while would slowly come to a stop due to drag.

Should I do this using AddForce or something? I'm really new to this stuff so I'd like it if you guys could point me in the right direction here :) .

# Answer
> 1 votes
Right now, you're feeding the delta directly into the Rotate() method.

Instead, try saving the delta to a temporary Vector3 struct and decaying the value over time. The best way to do this is using a co-routine.

I also noticed that `CanRotate` is being set to false when the touch ends, which will make the check for `RotateObject()` fail, so I suggest you use check against the temporary value to determine if you can fling it again.

---
Tags: android, unity, rotation, touch
---


title: How to categorize textures into atlases

text:
# Question
Title: How to categorize textures into atlases
I am going to use texture atlasing for the first time in my games, and at first it seemed like a great idea to split textures into atlases by categorizing them by terrain themes e.g *ForestTextures*, *WinterTextures* etc.

But that could cause a problem when for example a flower has to use transparency shader and other models use a diffuse shader. So those cannot be atlased into the same texture. Thus, would atlasing textures into themes as mentioned before and then splitting them by shader like *ForestDiffuse* and *ForestTransparent* be good? Or is there a better way to categorize and build them?

# Answer
Because the whole purpose of atlasing is to reduce draw calls by using fewer materials, you definitely want to categorize by material, rather than a theme. It may seem backwards at first, but categorizing by "theme" is actually an arbitrary way to categorize them. Don't constrain yourself to themes; instead, think of your atlas in terms surface and material type.
> 1 votes

---
Tags: unity, textures, shaders, texture-atlas
---


# Question
Title: Lightmapped prefabs for procedural content
I'm doing a game with procedural content from handmade prefabs, but I ran into a problem as Unity bakes the *scene* instead of *objects* when lightmapping with Beast. So when the prefabs are instanced they are without lightmaps.

Is there a way to get lightmaps for dynamically created prefabs with Unity's built-in lightmapper?

# Answer
One solution is to use Lightmap Manager 2

Also, a recent update to Unity (sorry, can't remember if it was 4.1 or 4.2) exposed some additional lightmapping methods in the API which help with this.
> 1 votes

---
Tags: unity, lighting, procedural, lightmap
---


title: Jumping with Mecanim synchronization

text:
# Question
Title: Jumping with Mecanim synchronization
I am using Unity3D 4.1 for one of my projects. I have a robot character which is always running. I am using mecanim animation system.

* **What I really want**:When I press Space bar, the character should jump up in the air, triggering an animation clip and then by the time it reaches the ground, the animation clip should also end.
* **What actually is happening**:When I press Space bar, the character jumps in the air. Animation clip plays as it should, but ends way before it reaches the ground. So, it looks like he is running in the mid air.
* **What have I done**: I have this humanoid robot setup with a jump animation bounded with the space bar key. Also, instead of using root motion, I am directly moving the robot from code.

```
    //Jumping
if(Input.GetKeyDown(KeyCode.Space)){
    rigidbody.AddForce(Vector3.up*jumpVelocty);
    anim.SetBool("Jump",true);

}
else
    anim.SetBool("Jump",false);

```

Character's Details:

1. Rigidbody = Mass:30, Freeze rotaion:x,y,z
2. Capsule Collider = Material: metal, center(0,4.5,0), radius:1, height:11
3. Script = jumpVelocity:20000

Jump Animation Clip: ~ 2 seconds. I am really out of ideas how to synchronize everything. Should I make the character jump in some other way so that it quickly comes down and touches the ground to match the animation clip? If yes, please provide a direction.

# Answer
You need to use multiple clips for this. Because you're using a single clip, and your jump is handled via physics, you can't really (easily) figure out the time the animation should take to complete, and even if you went that route, you'd have to slow your animation down to match.

What you need to do is split the animation into 3 separate clips, a jump, an in-air loop, and a landing animation.

You'd play the jump animation when you hit the jump button.

Transition into your in-air loop and remain there as long as the character is not grounded,

then when the character becomes grounded, transition to your landing animation.
> 2 votes

---
Tags: unity, physics, synchronization, mecanim
---


# Question
Title: Handling buildings in isometric tile based games
A simple question, to which i couldn't find a definitive answer - how to manage buildings on a tiled map? Should the building be sliced in to tiles or one big image?

EDIT: The game is being built from scratch using C++/SDL 2.0, it will be a turn based strategy, something like Fallout 1 & 2 without the hex grid, a simple square grid, where the Y axis is squished by 50%. Buildings can span multiple tiles, the characters move tile by tile. For now, the terrain is completely flat. Some basic functionality is in place, so I'm aiming to advancing the terrain and levels them selves - adding buildings, gates, cliffs, not sure about the elevation.

# Answer
Really not enough information in your question to give a definitive answer. However, in general, if you have a building which extends vertically to occlude multiple other tiles behind it, should be a single image. The quasi-3D nature of the isometric viewpoint is usually achieved by **layering**, and is distinct from laying out your map by breaking it up into tiles. That is, you render tiles in front after first rendering the tiles behind, so that a tall building may obscure the tiles behind it.

This results in some amount of overdraw (painting tiles onto the screen which are going to be partly or wholly obscured) but is generally a much more simple system to manage than trying to associate part of the building with tiles other than the tile it's directly sitting on.
> 1 votes

---
Tags: tilemap, isometric
---


# Question
Title: Drawing chunks, and positioning the camera
I've seen many questions and answers regarding how to draw tiled maps but I can't really get my head around it. Many answers suggest either loading the visible part of the map, or loading and unloading chunks of the map. I've decided the best option would be to load chunks, but I'm slightly confused as to how this would be implemented.

Currently I'm loading the full map to a 2D array of buffered images, then drawing it every time repaint is called. **Q1:** *If I were to load chunks of the map, would I load the map as a whole then draw the necessary chunk(s), or load & unload the chunks as the player moves along, and if so, how?*

My second question regards the camera. I want the player to be in the centre of the X axis and the camera to follow it. I've thought of drawing everything in relation to the map and calculating the position of the camera in relation to the players coordinates on the map. So, to calculate the camera's X position I understand that I should use **cameraX = playerX - (canvasWidth/2)**, but how should I calculate the Y position? I want the camera to only move up when the player reaches **cameraHeight/2** but to move down when the player reaches **3/4(cameraHeight)**. **Q2**: *Should I check for this in the same way I check for collision, and move the camera relative to the movement of the player until the player stops moving, or am I thinking about it in the wrong way?*

# Answer
**Q1:** Would depend on your hardware limitations (usually mainly memory size and the speed of loading new chunks from disk) and your game, but for larger worlds, the latter one (un/loading on the way) will usually be more suitable. Note that if using this option, you will often also want to pre-load some chunks (yet-not-visible) around the borders of the viewport to avoid stuttering when the players moves and you will need to do this in a separate thread (otherwise the game will stop whenever you load a new chunk).

Again, this might be just an over-kill for a simple 2D side-scroller, so you will probably want to consider whether it wouldn't be feasible to go with the first solution.

**Q2:** Don't know if I actually understood what you were asking about, but I would change the Y coordinate of the camera only when

* player moves down & is at **3/4(cameraHeight)**
* player moves up & is at **cameraHeight/2** (and both relatively to his own movement). Can't see any reason why complicate this.
> 2 votes

---
Tags: java, camera, side-scroller
---


# Question
Title: Rotating object along bezier curve: not rotating enough?
I tried to follow the instructions from the threads on the forum (Cocos2d rotating sprite while moving with CCBezierBy) with Unity, in order to rotate my object as it moves along a bezier curve. But it does not rotate enough, the angle is too low, it goes up to 6 instead of 90 for example, as you can see on this image (the y eulerAngle is at 6, I would expect it to be around 90 with this curve) :

---

EDIT: here is the solution :

```
Vector3 v3 = newPos - oldPos;
v3.y = 0.0f;
transform.rotation = Quaternion.LookRotation(v3);

```

---

Here is the code (in c# with Unity) : (I am comparing x and z to get the angle, and adding the angle to eulerAngles.y so that it rotates around the y axis)

```
void Update () {
        if ( Input.GetKey("d") ) start = true;
        if ( start ){
            myTime = Time.time;
            start = false;
        }
        float theTime = (Time.time - myTime) *0.5f;
        if ( theTime < 1 ) {
            car.position = Spline.Interp( myArray, theTime );//creates the bezier curve
            counterBezier += Time.deltaTime;

            //compare 2 positions after 0.1f
            if ( counterBezier > 0.1f ){
                counterBezier = 0;
                cbDone = false;
                newpos = car.position;
                float angle = Mathf.Atan2(newpos.z - oldpos.z, newpos.x - oldpos.x);
                angle += car.eulerAngles.y;
                car.eulerAngles = new Vector3(0,angle,0);
            }
            else if ( counterBezier > 0 && !cbDone ){
                oldpos = car.position;
                cbDone = true;
            }

```

Thanks

# Answer
here is the solution :

```
Vector3 v3 = newPos - oldPos;
v3.y = 0.0f;
transform.rotation = Quaternion.LookRotation(v3);

```
> 1 votes

---
Tags: c#, unity, rotation, curves, beziers
---


title: How to Use Text in Unity3d

text:
# Question
Title: How to Use Text in Unity3d
How Can i Create Text in Unity3D? I Use "3D Text" But Its Always on Top Of Everything! Can You Suggest Anything? I creating a 2D Game So its not Necessarily a 3D Text..

Edit: Because I Building a 2D Game My Scene is Full of Planes in Front of Camera And I want My Text to be Over One of the Planes and when plane is moving My Text appears behind it. But When I Use "3D Text" Its Always In Front of Everything.

Sorry for My Bad English...

# Answer
You will want to use this shader to achieve the effect you're after.
> 2 votes

# Answer
You can create a polygon with the texture of your text.

Are you using 2D Toolkit or something similar? This makes the process super easy and you can layer the text however you'd like.
> 0 votes

# Answer
The simplest solution would be to use a secondary camera to render your airplanes, and use the main camera to render everything that has to be below the airplanes (such as text).

Add a new camera, adjust its depth to a value greater than your main camera. Make sure its `normalized view port rect` property has the values `X:0 Y:0 W:1 H:1` (to take the whole screen). Make sure it's set to ignore all layers except for the airplanes' layer (see the `Culling Mask` property). Also change your main camera so that it ignores the airplanes' layer (but doesn't ignore the rest).

Now the text will be rendered by the main camera, and the airplanes will be rendered by the secondary camera. The text will appear below the airplanes.

To make the text appear on top of the airplanes, use the 2nd camera to render text, and the first camera to render the airplanes.
> 0 votes

---
Tags: unity, text
---


# Question
Title: GameObject in hierarchy needs to know who it belongs to
I have two objects from the same prefab. They have bodies and swords. What good options do i have to check if a sword belongs to player2 or player1?

For example when body registers that it has been hit by a sword i need to see if its the sword belonging to the enemy or the same body.

# Answer
I trust you are using `OnCollisionEnter` and/or `OnTriggerEnter`.

```
void OnCollisionEnter(Collision col)
{
}

```

Allows you to investigate the collider properly.

First, keep track of each sword's owner in the sword's script (you do have a script that you attach to swords, right?). When a sword collides with something, you:

```
class Sword
{
    public Player owner; //Set this when the script initializes or in the editor.
                     //It should point to this sword's owner.

    void OnCollisionEnter(Collision collision)
    {
         //You might want to iterate through all collision points and do this check so
         //you don't miss collisions with the player if multiple collisions are registered.
          Collider col = collision.collider;
          Player player = col.gameObject.getComponent<Player>();
          if (player != null) //We hit a player
          {
                if (player != this.owner) //If we didn't hit this sword's owner.
                {
                     player.getHit(SomeDamage);
                }
          }
    }
}

```

To set the sword's owner you can just drag & drop the owner's GameObject in the sword's owner property field. Alternatively, if you're instantiating characters dynamically at runtime, you can search for the sword's owner and set it appropriately. Here's a function that will work in any hierarchy:

```
private void setOwner()
{
     Transform tr = this.transform.parent;
     bool foundParent = false;
     while ((tr != null) && (!foundParent))
     {
            Player player = tr.gameObject.getComponent<Player>();
            if (player != null)
            {
                 this.owner = player;
                 foundParent = true;
            }
            tr = tr.transform.parent;
     }
}

```

This will go up in the hierarchy to find the closest Player, which becomes the sword's owner. If no suitable owner is found, the owner field keeps its default value, `null`. If you can guarantee the owner of the sword is the direct parent GameObject, you can instead ditch the hierarchy travelling and just do

`this.owner = this.transform.parent.gameObject.getComponent<Player>()`.

Do all of this inside `OnStart()`.
> 1 votes

# Answer
Either set a specific tag on each sword (I.e PlayerSword and Player2Sword) and then test which one is the one colliding with an if statement.

The other option is to use `transform.parent.gameobject.tag` This way is different than the previous method as it checks the tag of whatever game object is the parent. So if each player has a tag then this will work.

All you have to do now is just handle the events when they collide however you'd like.

Let me know if you have any questions.
> 0 votes

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


# Question
Title: Do I need path finding to make AI avoid obstacles?
How do you know when a path-finding algorithm is really needed?

There are contexts, where you just want to improve AI navigation to avoid an object, like a space -ship that won't crash on a planet or a car that already knows where to steer, but needs small corrections to avoid a road bump.

As I've seen on similar posts, the obvious solution is to implement some path-finding algorithm, most likely like A\*, and let your AI-controlled object to navigate through the path.

Now, I have the necessary skills to implement a path-finding algorithm, and I'm not being lazy here, but I'm still a bit skeptical on if this is really needed. I have the impression that path-finding is appropriate to navigate through a maze, or picking a path when there are many alternatives. But in obstacle avoidance, when you do know the path, but need to make slight corrections, is path finding really necessary? Even when the obstacles are too sparse or small ?

I mean, in real life, when you're driving and notice a bump on the road, you will just have to pick between steering a bit on the left (and have the bump on your right side) or the other way around. You will not consider stopping, or going backwards. A path finding would be appropriate when you need to pick a route through the city, right ?

So, are there any other methods to help AI navigation, except path-finding? And if there are, how do you know when path-fining is the appropriate algorithm ?

Thanks for any thoughts

# Answer
**No.**

There are a few levels of navigation available to you. In order of complexity, the choices go something like:

1. **Scripted movement**. All the movements are pre-programmed. Characters follow pre-defined paths, simply updating their position to make them move along a path.
2. **Random changes**. Characters continue moving forward, and at random intervals turn left or right. Collision detection and response still have a factor here, but it only keeps the character from walking through walls, not avoiding obstacles.
3. **Simple steering**. When an object is detected ahead of the character, it randomly chooses between a right or left turn. There are two forms of this:
    1. Turn when colliding with the object. This is the easier form, since it can use the existing collision detection and response code to add some steering.
    2. Turn before colliding with the object. This is a little more advanced where the characters need to test the position where they're going to be soon. When an obstacle is detected in that forward position, the character turns (hopefully avoiding a collision altogether).
4. **Steering**. More advanced steering. This type uses the "checking in front" type of avoidance. It will decide a direction to turn based on a various factors. It can use a ray cast to determine the normal of the collision that's about to happen. With that normal, we can get a slightly better idea of which way to turn. For example, when approaching a wall like this:
It makes a lot more sense to turn right instead of left.
5. **Advanced Steering**. The most advanced steering. This type uses multiple probes to detect obstacles ahead and in multiple directions. This gives us the most information when deciding how to turn, and *how much* to turn to avoid an object. In this way we can just make slight adjustments to avoid collisions.

As Nathan linked in his comment, the red3D article on steering is one of the best around. Their demos show some of the features you'd want to implement, including an example of advanced obstacle avoidance:

There are also a number of questions and answers about the topic on this site. Some good search terms would be: Steering and Boids.
> 11 votes

---
Tags: physics, ai, path-finding
---


title: How do I create a 2.5d parallax effect?

text:
# Question
Title: How do I create a 2.5d parallax effect?
I have a decent background in 3D graphics and programming, but I'm new to game development. I'm currently exploring different possibilities and I really want to make an RPG game. I was thinking about classic 2D isometric view, but I really love how Diablo 2 looks and feels to play.

My question is - how can I achieve Diablo 2's **parallax effect**? Everything looks hand drawn with baked lights and shadows and looks awesome, but when you move around you notice some **perspective**.

For example, let's say that I drew a big hall with columns in Photoshop with an orthographic perspective (classic pixel art style, just parallel lines). How would I give **parallax effect** to this scene when the character moves around? If I use camera-facing sprites for everything it would probably look OK in the distance, but it would be really fake when a character comes close to a column (cylinder) for example.

Any suggestions? How did Blizzard make the parallax effect in Diablo 2?

See this screenshot: http://guidesmedia.ign.com/guides/10629/images/act2tombs.jpg

# Answer
This is a long answer, but actually the basic premise of divide-by-camera-z is very simple: The further something is away from you, the smaller it appears. Also, the smaller distances between two things appear.

**Positions** (Not required reading if you're using Unity!)

Firstly, you need to render positions / points that using correct perspective.

Positions lie on a flat plane. You want something like the image on the right... consider the corners of the tiles as sample points / positions.

Here's how you approach the transformation of points:

* Your coordinate system is as follows: positive `z` runs into the screen, while `x` runs left-to-right and `y` runs down. Camera z *is* world z. That's the shortcut that makes this much easier than writing a full 3D engine. Downside? The Camera cannot change orientation (though it can change position).
* Store your camera's initial 3D position. Put it somewhat back (minus `z`) from the world origin.
* Store a collection of 3D points on the xz plane (give them `y=0`). Try to centre them across the world origin in `x`, `(0,0,0)`, i.e. from negative `n` to positive `n`. This is to centre them in the viewport, when rendering commences.
* Consider the diminishing point / pixel-plotting origin to be the centre of the screen.
* Decide on a distance from the camera at which 1 world space unit = 1 pixel. This means if you move the camera just 1 world space unit, any object 10 units away would shift by only 1 pixel -- quite far! Store this distance as a constant `K`.
* Now, for every point, render at a position using the following formula: `screenPosition(x,y) = screenOrigin + (worldPosition(x,y) - cameraPosition(x,y)) / ((worldPosition(z) - cameraPosition(z)) * K)`... as you can see, we are basing the render position on the `z`-distance between the current point and the camera.
* Play with the camera's z position until you see points being rendered. But what you will see is that the points will all display across the centreline of the screen. So we need to remedy that. Try `K=1` vs. `K=10` to see the difference.
* You can now move the camera in `y` to see how your camera goes above and below the plane of points (i.e. the points will render, perspective-correct, below or above the midline of the screen, respectively, as you move the camera up and down).

These are very rough guidelines. There are several implementation details that will be up to you. The first step is just to get something displaying, then amend from there. One detail that comes to mind is that if you want to camera to look more like it's looking down at the ground, then you need to shift your rendering origin upward, closer to the top of the viewport. Another detail is that your distance between camera and point may need to include a trig ratio... I think using `tan` offers more realistic perspective. Don't remember clearly about this, but you will quickly see if the perspective looks strange and can adapt accordingly. I can't be more specific without rewriting a sample.

**Per-billboard warping and scaling** (required)

Now that you can see perspective amongst your set of point-positions, and can add, remove, or move (as with characters) positions at will, you need to also apply perspective to the individual sprites which will be rooted at those positions.

In D2, it always appeared to me to be a simple lateral warp function that is applied more to the billboards that are the bottom of the screen, than to those at the top, and also more as you get futher away from the midline running down the screen.

There may be some vertical scaling applied to the billboards too, eg. trees getting shorter in comparison to their expected scale, nearer the bottom of the screen (to make it appear as if the camera is looking down on the trees -- I found Tristram's trees to be the best way to explore this safely, back in the day ;) ).

What I would do is:

1. Tackle the basic scaling function based on distance from camera to ground at different points. So you'd have similar scaling for every scanline.
2. Only after I'd done that, would I then look at the lateral warp -- first based on distance from the midline running down the screen.
3. Lastly I'd investigate how that lateral warp is affected by the distance down the screen (and I get the feeling that a simple trig ratio would be at the heart of this).

**Perspective-correct tiling** (Not required reading if you're using Unity!)

The above will hopefully give you correctly positioned, warped "stand up" sprites (i.e. objects that sit perpendicular to the ground plane, such as characters, trees, houses).

However, you also need to consider how to get the ground tiles to deform correctly and seamlessly. And I think you'll find that's the part which, in particular, required a GPU on D2. I remember that on systems without a GPU, the perspective option was disabled. The reason for this would almost certainly have been that the GPU can take a texture surface and apply perspective correction to it very rapidly, without any glitches between tiles, and without concerns over performing non-affine transforms in application code, which involves some matrix math and can be a bit costly:

I have a few suggestions for you to deal with this:

* (Unity) Use a Unity Camera to supply the rendering of the flat, textured ground plane, then handle the billboard distortions separately based on screenspace positions.
* Do this logic (or even all render logic) in GPU shaders.
* Don't use ground tiles at all. Instead, just use point sprites -- just like the characters themselves -- on a uniformly-coloured plane (eg. green for grass) to provide detail for that plane to not look dull. This will increase your rendering costs, but it is certainly the easiest way to tackle this problem.
> 6 votes

---
Tags: 2d, unity, graphics, 2.5d
---


# Question
Title: Making a new instantiated prefab as a child for existing GameObject
I've been searched about how to make these fruit to move as the basket movement if it collided with it, and I've been found that if I want to perform this I've to let these fruit to be a child to the basket game object .. for example :

```
banana.transform.parent = basket.transform;

```

banana and basket each of them of type "GameObject" ...

BUT unfortunately this way didn't work !! and I don't know why ??

So now I need to know if it is possible to destroy the banana if a collision with the basket happened and instantiate a new banana in the basket as a child at run time ?!!

I need to try this stupid way because I've tried all the other ways and nothing worked :(

# Answer
> 0 votes
`banana.transform.parent = basket.transform;`

should work. If it doesn't, what happens?

This depends on how you are moving the fruits in the first place. You'll need to disable the script, or at least the function, that is making the fruit move down. Once you set the parent the fruit will still move independent of the parent unless you explicitly state to move in a relative way. Otherwise, the fruit will still be moving downwards even when it's parented unless you remove the script that is causing the downward movement.

I think the best approach would be to have a funciton like `doMove(bool true){if true //Stuff}` and then change the variable when the fruit collide with the basket.

---
Tags: unity, unityscript
---


title: How to use mipmap in OpenGL-ES

text:
# Question
Title: How to use mipmap in OpenGL-ES
I have recently entered in the OpenGL world. I am very pleased with the performance that I got with opengl compared to those obtained with a SurfaceView and its canvas. At the same time because of the limitation of the images to be in power of two I noticed that the quality of the sprite of my game is a little decreased. I read that we can use mipmap in Android but I have not found a real tutotial.

Are they compatible with Android 2.2+ ?

Which program creates mipmaps?

How do you actually use in code?

# Answer
> 0 votes
Here is a good tutorial for using mipmaps (and other filtering techniques).

**To answer your other questions:**

It should work fine in Android 2.2+.

Mipmaps are created from your base texture at runtime.

The tutorial provides full source code :)

---
Tags: opengl, android, opengl-es
---


# Question
Title: I need to move an entity to the mouse location after i rightclick
Well I've read the related questions-answers but still cant find a way to move my champion to the mouse position after a right-button mouse-click. I use this code at the top:

`float speed = (float)1/3;`

And this is in my void Update:

```
  //check if right mouse button is clicked
        if (mouse.RightButton == ButtonState.Released && previousButtonState == ButtonState.Pressed)
        {
            // gets the position of the mouse in mousePosition
            mousePosition = new Vector2(mouse.X, mouse.Y);

            //gets the current position of champion (the drawRectangle)
            currentChampionPosition = new Vector2(drawRectangle.X, drawRectangle.Y);

            // move champion to mouse position:
            //handles the case when the mouse position is really close to current position
            if (Math.Abs(currentChampionPosition.X - mousePosition.X) <= speed &&
                Math.Abs(currentChampionPosition.Y - mousePosition.Y) <= speed)
            {
                drawRectangle.X = (int)mousePosition.X;
                drawRectangle.Y = (int)mousePosition.Y;
            }
            else if (currentChampionPosition != mousePosition)
            {
                drawRectangle.X += (int)((mousePosition.X - currentChampionPosition.X) * speed);
                drawRectangle.Y += (int)((mousePosition.Y - currentChampionPosition.Y) * speed);
            }
        }
        previousButtonState = mouse.RightButton;

```

What that code does at the moment is on a click it brings the sprite 1/3 of the distance to the mouse but only once. How do I make it move consistently all the time? It seems I am not updating the sprite at all.

EDIT I added the Vector2 as Nick said and with speed changed to 50 it should be OK. I tried it with if ButtonState.Pressed and it works while pressing the button. Thanks. However I wanted it to start moving when single mouse clicked. It should be moving until reaches the mousePosition.

The Edit of Nick's post says to create another Vector2, But I already have the one called mousePosition. Not sure how to use another one.

```
            //gets a Vector2 direction to move *by Nick Wilson
            Vector2 direction = mousePosition - currentChampionPosition;

            //make the direction vector a unit vector
            direction.Normalize();

            //multiply with speed (number of pixels)
            direction *= speed;

            // move champion to mouse position
            if (currentChampionPosition != mousePosition)
            {
                drawRectangle.X += (int)(direction.X);
                drawRectangle.Y += (int)(direction.Y);
            }
        }
        previousButtonState = mouse.RightButton;

```

# Answer
> 0 votes
In your update code:

```
drawRectangle.X += (int)((mousePosition.X - currentChampionPosition.X) * speed);
drawRectangle.Y += (int)((mousePosition.Y - currentChampionPosition.Y) * speed);

```

Since the speed is *1/3*, you're only moving it *1/3* of the distance to the mouse's position.

If you want it to *immediately* jump to that position, set `speed` to 1.

If you want it to *slowly* move to that position, you'll want `speed` to be something smaller (unless you want the champion to move to whatever position the user clicked in in three frames). However, it will still take equal time to get to any position with your current implementation.

You'll want to get a `Vector2` that goes from the champion position to the mouse position. IE:

```
    Vector2 direction = mousePosition - currentChampionPosition;

```

Then you'll want to make the player move an equal amount along that vector. You can do this my *normalizing* the vector, and then multiplying it by your speed. (In this case, the vector will be multiplying 1 by the speed, so you'll want to put the speed as how many pixels you want the player to move every frame.)

```
    direction.Normalize();
    direction *= speed;

    drawRectangle.X += (int)(direction.X);
    drawRectangle.Y += (int)(direction.Y);

```

You'll also want to check if doing this will move the player too far past the mouse position, so that you don't get back-and-forth jittering when the player is near the destination.

## Edit:

It seems that you're only applying this once, when the user clicks. Save a `Vector2` for the position that you want the player to move to, and on every frame where the player needs to move, apply your move code.

# Answer
> 0 votes
What are you doing this in?

The only thing that comes to mind looking at your code is the way you are checking the state of the button. Don't store the past click if you don't have to. You should be able to get the same result by doing something like `mouse.RightButton == ButtonState.Down`

Also, there is not need to do your check of if the mouse is really close to the character, just handle all in one block. Make sure to multiply your movement by delta time as well.

---
Tags: mouse
---


# Question
Title: Rotating an object about a point (2D) using box2d
i just started developing using box2d on flixel and i realise the pivot point of the rotation of an object in box2d is set to the center of an object.

i had read on forums and i found out that SetAsBox can change the pivot point of the object, however, i cannot seem to get it work to rotate about a point.

what i would like to achieve is to rotate an object about a point like earth revolving around the sun. any one can help me with it? really thanks a lot and sorry for the bad english

# Answer
> 1 votes
You could create a Sprite subclass that features a pivot point and uses transformation matrix to update position, scaling and rotation. A nice example with source code can be found here : http://jamesvango.co.uk/blog/?p=136

Another lazy way to get around, is adding your sprite in a container sprite, then move it so it's center is alligned with the parent's top left corner

```
containerSprite.addChild(child);
child.x = -child.width/2;
child.y = -child.height/2;

```

and update the containerSprite's position and rotation

```
containerSprite.x = body.GetPosition().x * worldScale;
containerSprite.y = body.GetPosition().y * worldScale;
containerSprite.rotation = body.GetAngle() * 180 / Math.PI;

```

---
Tags: box2d, flash, flixel
---


# Question
Title: Pixmaps, ByteBuffers, and Textures....Oh my
My ultimate goal is to take a specific region of the screen, and redraw it somewhere else. For example, take a square from the upper left hand corner of the screen and redraw it on the lower right hand corner, so that it is basically a copy of that screen section; kind of like a minimap, but at the same scale as the original. I have looked in to pixmaps and bytebuffers. Also maybe copying that region from the backbuffer somehow. Wondering the best way to go about this. Any help is appreciated. I am using opengl es and libgdx for what it's worth.

# Answer
You could use a frame buffer object (FBO) -- basically think of it as "render to texture". You render your scene to the buffer rather than the screen. Then, after the scene is done you render simpler things like quads to the "real" screen, using the FBO as a texture sampler in your shaders. This means you could render multiple quads each using some subset of the image or write more involved shader that knows how to pull data out of the texture the way you want.

I'm not very familiar with libgdx but you'd be using this thing I believe: http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/graphics/glutils/FrameBuffer.html
> 3 votes

---
Tags: graphics, opengl-es, libgdx
---


title: First Person Camera strafing at angle

text:
# Question
Title: First Person Camera strafing at angle
I have a simple camera class working in directx 11 allowing moving forward and rotating left and right. I'm trying to implement strafing into it but having some problems.

The strafing works when there's no camera rotation, so when the camera starts at 0, 0, 0. But after rotating the camera in either direction it seems to strafe at an angle or inverted or just some odd stuff.

Here is a video uploaded to Dropbox showing this behavior. https://dl.dropboxusercontent.com/u/2873587/IncorrectStrafing.mp4

And here is my camera class. I have a hunch that it's related to the calculation for camera position. I tried various different calculations in strafe and they all seem to follow the same pattern and same behavior. Also the m\_camera\_rotation represents the Y rotation, as pitching isn't implemented yet.

```
#include "camera.h"

camera::camera(float x, float y, float z, float initial_rotation) {
m_x = x;
m_y = y;
m_z = z;
m_camera_rotation = initial_rotation;

updateDXZ();
}

camera::~camera(void)
{
}

void camera::updateDXZ() {
m_dx = sin(m_camera_rotation * (XM_PI/180.0));
m_dz = cos(m_camera_rotation * (XM_PI/180.0));
}

void camera::Rotate(float amount) {
m_camera_rotation += amount;

updateDXZ();
}

void camera::Forward(float step) {
m_x += step * m_dx;
m_z += step * m_dz;
}

void camera::strafe(float amount) {
float yaw = (XM_PI/180.0) * m_camera_rotation;

m_x += cosf( yaw ) * amount;
m_z += sinf( yaw ) * amount;
}

XMMATRIX camera::getViewMatrix() {
updatePosition();

return XMMatrixLookAtLH(m_position, m_lookat, m_up);
}

void camera::updatePosition() {
m_position = XMVectorSet(m_x, m_y, m_z, 0.0);
m_lookat = XMVectorSet(m_x + m_dx, m_y, m_z + m_dz, 0.0);
m_up = XMVectorSet(0.0, 1.0, 0.0, 0.0);
}

```

# Answer
> 1 votes
What I do in my camera class is that I always store the forward and up vector and then use cross product in every update to calculate the right vector. In other words you need at least to store/calculate your right vector in order to be able to correctly determine the direction that you should strafe in. In your case you can do the following:

```
forward = normalize(m_lookat - m_position);
right   = cross( forward, m_up );

```

And the you use right for moving the camera:

```
m_position += (right * moveOffset ); // make sure right is normalized, moveOffset is a scalar not a vector.

```

---
Tags: c++, 3d, camera, directx11
---


# Question
Title: How to manage sleep/awake state of physics body
I have a loop, which updates all the physics, inside the loop I'm updating the position of the objects, first thing is the gravity, which pulls all the objects to the bottom. Now my question is, how do I manage the sleep/awake state of the object, let's say the object reached some static body, like ground. So it won't continue falling down because of the gravitation pull?

# Answer
You need collision resolution to handle object-ground collisions.

A basic example: check if the object is below/colliding with the floor, move it into a position where it does not collide, and set its velocity to make it either sit there, or bounce off (depending on how fast the object is moving downwards).

If you need more accurate physics Google will help you.

Sleeping is an optimisation for the engine such that it does not have to simulate the objects that are not doing anything interesting.
> 1 votes

---
Tags: game-mechanics, physics, game-loop
---


title: How to attract modders to your game?

text:
# Question
Title: How to attract modders to your game?
I am developing a game, but as I am working on it alone, the amount of content I can create is very limited. Because of that I want my game to be modded, for this purpose I am planning to create a complete modding API which would be exposed for lua scripting. I would also create tutorials to get people started. And the "Original" game would also be a "mod"(similar to Warcraft III maps) .

My question is: What can a developer do to encourage modding of its game?

PS: my game is a sandbox-ish multiplayer survival(most things are procedural).

# Answer
* Make the modding tools very easy to use. There should be a tool for creating the mod, and a fast way to test the mod, ideally live creation if that's practical for your game.
* Make the distribution and installation of mods dead simple (think steamworks). People are more likely to make mods if they know they'll be used! A rating system will give recognition to modders and allow people to choose the best mods.
* Make many aspects of the game modifiable. If users can add levels, enemies, weapons, etc. they're more likely to make a mod. If the aspect of the game they want to change isn't modifiable, they won't make a mod.

And the most difficult task:

* Make a game that people love to play. People won't bother modifying a game they don't like.
> 11 votes

# Answer
Follow these two principles:

* Make your game data-driven.
* Make your data files human-readable.
> 7 votes

---
Tags: user-generated-content, modding
---


title: Normals vs Normal maps

text:
# Question
Title: Normals vs Normal maps
I am using Assimp asset importer (http://assimp.sourceforge.net/lib\_html/index.html) to parse 3d models.

So far, I've simply pulled out the normal vectors which are defined for each vertex in my meshes. Yet I have also found various tutorials on normal maps...

As I understand it for normal maps, the normal vectors are stored in each texel of a normal map, and you pull these out of the normal texture in the shader.

Why is there two ways to get the normals, which one is considered best-practice and why?

# Answer
**Short Answer**

Normal maps and Normals are two different things: Normals are a geometric property of any mesh/surface its use is not exclusive for shading and lighting calculations but have actually many other uses for example in physics. Normal maps are textures that encode alternative normal vectors used in computer graphics to simulate bumps.

**Long Answer**

**Normals** in geometry a normal is a vector or a line that is perpendicular to a given object (e.g. plane normal, vertex normal ). Normals in graphics are usually used for light calculations, such as calculating Diffuse reflection across a surface by taking the dot product between the light direction and surface normals. Normals are usually calculated based on the geometrical properties of the mesh (Faces/Vertices), by taking the cross product of any two non-parallel edges that lies on the same plane.

In OpenGL normals are specified per vertex (hence called vertex attributes) even though they might be calculated only for each face in this case you need to specifiy the same normal for each vertex in a face. Normals can be interpolated by OpenGL across each vertex of a face(triangle) so you can calculate the reflected light per pixel not per vertex, hence giving a more *accurate* result.

**Normal Mapping**: on the other hand is a technique in computer graphics that encodes Normals in a texture map, so each normal is encoded per texel. It is usually used for faking the lighting of bumps and dents (e.g. bump mapping, parallax mapping).

Since normals are calculated based on the geometrical properties of the mesh/surface, Normal Maps will give you alternative Normals that can simulate the bumps to add detail to the surface without adding more polygons.

Normal maps are usually generated using a much more detailed 3D model, then calculating the normals based on this model and encoding it in a Normal Map.

**Why do we need both?**

Well talking only about rendering, normals and normal maps are usually used together to achieve the final lighting effect, a good example might be a bump shader, where you need the normals map normal to achieve the bump lighting effect, and you will still need the geometric normal to calculate what is called the tangent space. Tangent space is usually used to provide re-usability for normal maps.

Keep in mind that a normal is considered a geometrical attribute of the surface and has many more uses than only light calculations. Normal maps on the other hand are usually used for superficial effects.

**Extending the answer to explain why tangent spaces are important:**

**Short answer:** Tangent spaces are used to make normal maps independent of the underlying geometry.

\[EDIT\] Added Image to represent normal map in tangent space and normal map in world space.

**Long answer:** The below picture shows the UV plane and the normal that defines the tangent space, when generating a normal map we will already know that the used space will always have the Normal pointing in the Z direction (that's why normal maps look bluish), this will help us ignore the surface curvature\**, .

Tangent space gives us the advantage that our normal maps encoding isn't bound to a specific mesh normals. Suppose we encode our normal map in world or object space, then each normal we encode will have a direction based on how the original mesh normals vary in world space, not to mention your normal map will be affected by the model transformations.

In the above two pictures it's pretty clear that tangents space makes normal maps(right), independent of the underlying geometry because all normals are encoded in almost the same direction with small variation to simulate the effect of the bumps.

\**surface curvature is defined by the amount which a geometric object deviates from being flat, or straight in the case of a line but this is defined in different ways depending on the context.
> 32 votes

---
Tags: c++, opengl, normals, normal-mapping, assimp
---


title: Material System

text:
# Question
Title: Material System
I'm designing Material/Shader System (target API DX10+ and may be OpenGL3+, now only DX10). I know, there was a lot of topics about this, but i can't find what i need.

I don't want to do some kind of compilation/parsing scripts in real-time.

So there some artist-created material, written at some analog of CG. After it compiled to hlsl code and after to final shader. Also there are some hard-coded `ConstantBuffers`, like

```
cbuffer EveryFrameChanging
{
    float4x4 matView;
    float time;
    float delta;
}

```

And shader use shared constant buffers to get parameters. For each mesh in the scene, getting needs and what it can give (normals, binormals etc.) and finding corresponding permutation of shader or calculating missing parts.

Also, during build calculating render states and the permutations or hash for this shader which later will be used for sorting or even giving the ID from 0 to `ShaderCount` w/o gaps to it for sorting.

`FinalShader` have only 1 technique and one pass. After it for each Mesh setting some shader and it's good to render.

some pseudo code

```
SetConstantBuffer(ConstantBuffer::PerFrame);
foreach (shader in FinalShaders)
    SetConstantBuffer(ConstantBuffer::PerShader, shader);
    SetRenderState(shader);
    foreach (mesh in shader.GetAllMeshes)
        SetConstantBuffer(ConstantBuffer::PerMesh, mesh);
        SetBuffers(mesh);
        Draw();

class FinalShader
{
public:
    UUID m_ID;
    RenderState m_RenderState;
    CBufferBindings m_BufferBindings;
}

```

But i have no idea how to create this CG language and do i really need it? May be WYSIWYG editor?

Edit:

I found interesting articles: Shader Designer and here DICE Frostbyte. I think it's good cause it's more easy to build then parsing custom language and more flexible cuz all graph elements are inherited from `IBaseNode` which have inputs, outputs, so `cbuffer EveryFrameChanging` is also `IBaseNode` with 0 inputs and 3 outputs. Maybe possible apply graph optimization theory to shaders. Any usefull links or advises?

# Answer
> 1 votes
This is a common thing where there is tons of different implementations.
I Will give you my approach, how i would implement this. ( according to your psudo code )

```
SetConstantBuffer( GlobalData ); <- this would be bound to the first register, so i always know that this one will be there.

For( unsigned int i = 0; i < m_Materials; ++i ) <- where this is a variable containing the amount of material we got in our "database"
SetConstantBuffer( MaterialSpecificData ) <- R1
SetRenderState( MaterialSpecificStates )
for( unsigned int u = 0; u < meshQueue[i].size(); ++i )
Draw->

```

This point is all the same. But the main thing i would do is to have a loadtime collector, where you collect each mesh, find itś assigned material and from there store them correctly in the meshQueue, where meshqueue would be a vector vector, so you could store an array for each corresponding material.

For the shaders, I would have one main Include named something like, System.H or Materials.H which would hold the Registery0 where all the "per frame" stuff would be held. Also some neat helpers you might need.

From that point on, you could have a define or a integer saying what part of a shader to run. You could compile different part of the program with ifdef/ifndef. So if you would have a "Main" shader entry point, you could esily branch that one out to different branches by just having defines beeing defined before running. since the .h files wont get compiled you can change them on the fly with simple c++ code.

I hope this answers your question as you hoped.

---
Tags: c++, c#, architecture, shaders, materials
---


# Question
Title: How to balance experience gain in an RPG
I am currently developing an RPG game with a classic experience-points and levelup mechanic. The player kills monsters, gains experience points, levels up when they collect enough and become stronger.

How do I balance the amount of Exp points necessary for reaching each level and the amount of Exp awarded by each monster on each level?

# Answer
> 18 votes
The best way to come to a conclusion in this regard is - like with most things in game development - to first think about how you want the game to *play*, and then make up the math which will result in the game playing like that.

## How long do you want the player to play on each level?

In a story-focused single-player RPG you likely want to keep levelups as a constant reward stream and have the player level up every few minutes during the whole game. The rate of levelups stays constant, so your minutes-per-level function is a constant (`time = c`).

On a more achievement-focused game, like an MMORPG, you usually want levelups to be frequent for beginners but become less and less frequent the further the player progresses. In that case your minutes-per-level function would be polynomial (`time = Level ^ c`) or even exponential (`time = c ^ Level`). Taking the level-number as-is in an exponential formula is usually much too extreme, however. It can be a good idea to divide it by a constant to make the increase a lot slower while still keeping it exponential (`time = c1 ^ (1 + Level / c2)`).

I would recommend you to use a spreadsheet to crunch the numbers. Create a table with a column with the numbers from 1 to your expected maximum level, and a second column with the level formula. This easily allows you to experiment with different formulas to find numbers which are to your liking. Maybe you get better results when you combine a polynomial with an exponential component?

Remember that you are seeing *net combat time* here. The game time the player is actively collecting experience points. It doesn't count the time the player spends talking with NPCs, comparing their equipment and does other tasks which don't directly cause progress.

In my current game (an MMORPG) I came up with the formula `seconds(level) = 10 ^ (1 + Level / 20)`. The first few levels only take seconds of actual combat (very instant gratification during the tutorial phase), the levels 20 - 40 take minutes, in the 50s it becomes hours per level and when near the maximum level of 100 it takes whole weeks to see progress.

## How different should the experience reward per enemy be?

Even when your enemies don't have an explicit (or meaningful) level stat, you will want to design them to be a balanced challenge for a certain character level. But how much more experience should an enemy recommended for level 40 reward over one recommended for level 30?

The answer to this question is closely related to how much more powerful the character gets per level and how far you want to allow them to be ahead or behind the current enemies with their character level.

Some game systems, like that of World of Warcraft for example, make it quite pointless to pursue any combat with an enemy just slightly below or above the level of the player character. Anything just a few levels above will annihilate the player, anything a few levels below will be no challenge (and no reward) at all.

A counter-example would be the Disgaea series. In that game you can easily defeat enemies with several *times* the level of your own characters when you play it smart.

The more restrictive you want to be in the level bracket which is a fair fight for the player, the more you need to make sure that the player doesn't lag behind or get ahead the level of the enemies they are currently fighting. When the player falls behind the enemies, the game will become frustratingly difficult without grinding. When the player gets ahead of the monsters, the game will become too easy and boring.

A good way to keep the player inside the level bracket is to increase the exp reward per level. On the one hand, it will easily allow the player to catch up when they are slightly below recommended level. On the other, it won't allow them to level up efficiently on weak enemies without progressing to a harder area.

A polynomial exp curve (`exp = Level ^ c`) usually works well. The larger the value of `c`, the more you force the player into the current level bracket of the monsters they fight.

Keep in mind that enemies which take longer to defeat should also give proportionally more experience. A battle which takes 20 seconds should give twice as much exp as one which only takes 10 seconds. This extends your formula to `exp = (Level ^ c) * minutes_per_combat`.

## The final exp-per-level formula

The final formula can now be derived from the two. The `experience per level` is the `time per level in minutes` multiplied with the `experience gained per minute`. So just take the two formulas you came up with in the last two sections and multiply them. There it is: Your experience-per-level formula.

With a polynomial time-increase per level, the formula would be

```
exp(level) = (level ^ c1) * (level ^ c2)

```

where

* `c1` depends on how long you want each level to take
* `c2` depends on how close you want to keep the player to the level of the enemies they fight

## What could go wrong?

Even the best thought-out concept can't replace proper playtesting. Should your playtesting turn out that the average players progress much faster or slower than you want, it is usually a sign that you over- or underestimated the recommended levels of your enemies and how long it takes for the average player to kill them. Try analyzing together with your playtesters which enemies are how hard to kill on what character level and adjust their exp value or stats accordingly.

---
Tags: mathematics, game-mechanics, rpg, progression
---


title: Bouncing ball isssue

text:
# Question
Title: Bouncing ball isssue
I am currently working on the 2D Bouncing ball physics that bounces the ball up and down. The physics behaviour works fine but at the end the velocity keep +3 then 0 non-stop even the ball has stopped bouncing. How should I modify the code to fix this issue?

Here is the video shows how it works. Note: Bandicam cannot record the velocity transition between -3 and 0. So, it just shows -3 when the ball stops bouncing.
http://www.youtube.com/watch?v=SEH5V6FBbYA&feature=youtu.be

Here is the generated report: https://www.dropbox.com/s/4dkt0sgmrgw8pqi/report.txt

```
    ballPos         = D3DXVECTOR2( 50, 100 );
    velocity        = 0;
    acceleration    = 3.0f;

void GameClass::Update()
{
    // v = u + at
    velocity += acceleration;

    // update ball position
    ballPos.y += velocity;

    // If the ball touches the ground
    if ( ballPos.y >= 590 )
    {
        // Bounce the ball
        ballPos.y = 590;
        velocity *= -1;
    }

    // Graphics Rendering
    m_Graphics.BeginFrame();
    ComposeFrame();
    m_Graphics.EndFrame();
}

```

# Answer
Put a isBounce flag to make the velocity to zero when the ball stops bouncing.

```
 void GameClass::Update()
{
    if ( isBounce )
    {
        // v = u + at
        velocity += acceleration;

        // update ball position
        ballPos.y += velocity;
    }
    else
    {
        velocity = 0;
    }

    // If the ball touches the ground
    if ( ballPos.y >= 590 )
    {
        if ( isBounce )
        {
            // Bounce the ball
            ballPos.y = 590;
           velocity *= -1;
        }

        if ( velocity == 0 )
        {
            isBounce = false;
        }
}

```
> -1 votes

# Answer
The main problem you are encountering is due to the fact that you are using Euler integration. It is very innacurate and assumes a constant acceleration over the whole timestep (in your case an implicit dt = 1), which is wrong in general, but in the case of a bounce, very very wrong indeed.

Also, there is no damping. In the real world, energy is always lost due to friction and collisions. In fact, your code is actually giving free energy to the ball: at the moment of impact, you teleport the ball upwards a short distance, while giving it an impossibly perfect eleastic collision, thereby giving the ball free potential energy. The only reason your ball's bouncing becomes smaller is because of the innacurate Euler integration, not something you want to rely on.

To make your code better, I would first introduce an explicit timestep, then you can call your integration function multiple times per frame with smaller timesteps to get better accuracy, or have an adaptive timestep.

You could also look into higher order integration functions. 4th Order Runge-Kutta is very accurate, but overkill for what you want, but perhaps a second order leapfrog method.

You could also look into Verlet integration. While it is still not very accurate, it is easy to control and very stable.

You should also add some damping. The easiest way is to multiply the velocity by a number slightly smaller than 1 (which is equivalent to adding a small force proportional to velocity, in the opposite direction):

```
vel *= 0.9999; <- energy loss every frame, air resistance
if ( ballPos.y >= 590 )
{
    ballPos.y = 590;
    vel *= -0.95; <-larger energy loss in collision
}

```

So, to sum up, here is a list of keywords to research to improve your simulation:

*leapfrog integration, runge-kutta integration, verlet integration, adaptive timestep, collision detection/resolution, rigid body stacking, resting contact, impulse collisions,*

You can easily find lots of easy to understand tutorials, samples and papers relating to this. That's probably a lot deeper than you need/desire to go. But writing a simple, but solid, physics simulation is a great learning experience and a whole lot of fun.
> 2 votes

# Answer
Your acceleration will negate any upward velocity at the point that speed \<= 3.
> 0 votes

---
Tags: 2d, directx, physics, logic
---


# Question
Title: Would it be more efficient to handle 2D collision detection with polygons, rather than both squares/polygons?
I'm working on a 2D game engine and I'm trying to get collision detection as efficient as possible. One thing I've noted is that I have a Rectangle Collision collider, a Shape (polygon) collider and a circle collider. Would it be more efficient (either dev-time wise or runtime wise) to have just one shape collider, rather than have that and everything else? I feel it would optimize my code in the back end, but how much would it affect my game at runtime? Should I be concerned with this at all, as 3D games generally have tens of thousands of polygons?

# Answer
> 4 votes
**Why do we use axis-aligned bounding boxes (AABBs) in collision detection?** This question has been asked and answered more than once on this site, but I will answer it here again, briefly.

AABB checks are an optimisation. And the optimisation works as follows: You do the very cheap check before you even approach doing the order-of-magnitude more expensive check. The latter, more expensive check still has a good chance of failing. Because the disparity between execution times for these two types of checks is so large, it is statistically worthwhile to always do AABB pre-checks. This would still be the case even if 50% of all bodies in the world were colliding on *every single frame*.

Why are AABB checks so very cheap, by comparison? Because they are nothing more than a greater-than or less-than check, limited to one each per individual axis (2 in 2D, 3 in 3D). There is no trig, there are no divisions, there are no square roots, and there is no iteration (which introduces excess conditionals).

So provided that you've already precalculated what your maximum extents are in each axis, this is a very rapid pre-check that can be used to eliminate far more expensive checks which utilise one or more of the aforementioned operations -- any of which polygonal checks will require (and this worsens as per the Curse of Dimensionality). This is further compounded by the number of discrete elements per polygon (2D) / polyhedron (3D), i.e. points, edges and (3D) faces. O(n) in the number of pertinent elements, vs. O(d) where d is the dimensionality.

# Answer
> 2 votes
It's simple, the more vertices you have, the higher the performance cost. But, keep in mind you are doing 2D collisions so it's not as intensive as 3D. Doesn't mean things can't get complicated, but for the most part there won't be a huge difference between a square and say, an octagon or some custom polygon. Take a look at Box2D and how they handle more complicated collisions and notice how little performance is required.

Now, if this is for mobile then every vert counts so keep that in mind. There will be a much larger difference from a square and an 100 vert pixel perfect collider on mobile. But not so much on PC's because of things like dedicated vRAM that phones don't have (most).

---
Tags: 2d, collision-detection, refactoring
---


# Question
Title: Unity GUI not in build, but works fine in editor
I have:

1. GUITexture attached to an object
2. A script that has GUIStyles created for the Textfield and Buttons that are created in OnGUI(). This script is attached to the same object in number 1
3. 3 GUIText objects each separate from the above.
4. A script that enables the GUITexture and the script in number 1 and 2 respectively

This is how it is supposed to work: When I cross the finish line, number 4 script enables number 1 GUITexture component and number 2 script component. The script component uses one of number 3's GUIText objects to show you your best lap time, and also makes a GUI.Textfield for name entry and 2 GUI.Buttons for "Submit" and "Skip". If you hit "Submit" the script will submit the time. No matter which button you press, The remaining 2 GUIText objects from number 3 will show you the top 10 best times.

For some reason, when I run it in editor, everything works 100%, but when I'm in different kinds of builds, the results vary.

When I am in a webplayer, The GUITexture and the textfield and buttons appear, but the textfield and buttons are plain and have no evidence of GUIStyles. When I click one of the buttons, the score gets submitted but I do not get the fastest times showing.

When I am in a standalone build, the GUITexture shows up, but nothing else does. If I remove the GUIStyle parameter of the GUI.Textfield and GUI.Button, they show up.

Why am I getting these variations and how can I fix it?

Code below:

```
    void  Start ()
    {
        Names.text = "";
        Times.text = "";
        YourBestTime.text = "Your Best Lap: " + bestTime + "\nEnter your name:";

        //StartCoroutine(GetTimes("Test"));

    }

void Update()
{
    if (!ShowButtons && !GettingTimes)
    {
        StartCoroutine(GetTimes());
        GettingTimes = true;
    }
}

IEnumerator GetTimes ()
{
    Debug.Log("Getting times");
    YourBestTime.text = "Loading Best Lap Times";
    WWW times_get = new WWW(GetTimesUrl);
    yield return times_get;
    WWW names_get = new WWW(GetNamesUrl);
    yield return names_get;

    if(times_get.error != null || names_get.error != null)
    {
        print("There was an error retrieiving the data: " + names_get.error + times_get.error);
    }
    else
    {
        Times.text = times_get.text;
        Names.text = names_get.text;
        YourBestTime.text = "Your Best Lap: " + bestTime;
    }
}

IEnumerator PostLapTime (string Name, string LapTime)
{
    string hash= MD5.Md5Sum(Name + LapTime + secretKey);
    string bestTime_url = SubmitTimeUrl + "&Name=" + WWW.EscapeURL(Name) + "&LapTime=" + LapTime + "&hash=" + hash;

    Debug.Log (bestTime_url);
    // Post the URL to the site and create a download object to get the result.
    WWW hs_post = new WWW(bestTime_url);
    //label = "Submitting...";
    yield return hs_post; // Wait until the download is done
    if (hs_post.error != null)
    {
        print("There was an error posting the lap time: " + hs_post.error);
        //label = "Error: " + hs_post.error;
        //show = false;
    }
    else
    {
        Debug.Log("Posted: " + hs_post.text);
        ShowButtons = false;
        PostingTime = false;
    }
}

void OnGUI()
{
    if (ShowButtons)
    {
        //makes text box
        nameString = GUI.TextField( new Rect((Screen.width/2)-111, (Screen.height/2)-130, 222, 25), nameString, 20, TextboxStyle);

        if (GUI.Button( new Rect( (Screen.width/2-74.0f), (Screen.height/2)- 90, 64, 32), "Submit", ButtonStyle))
        {
            //SUBMIT TIME
            if (nameString == "")
            {
                nameString = "Player";
            }
            if (!PostingTime)
            {
                StartCoroutine(PostLapTime(nameString, bestTime));
                PostingTime = true;
            }

        }
        else if (GUI.Button( new Rect( (Screen.width/2+10.0f), (Screen.height/2)- 90, 64, 32), "Skip", ButtonStyle))
        {
            ShowButtons = false;
        }
    }
}

```

}

# Answer
> 0 votes
The reason it wasn't working was because I had C# and Javascript scripts with the same class name.

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


title: SFML: Generate a background image

text:
# Question
Title: SFML: Generate a background image
I want to generate a background, which is used in the game, on every instance of the game based on certain conditions. To do so, I'm using a `sf::RenderTexture` and a `sf::Texture` like this:

```
sf::RenderTexture image;
std::vector<sf::Texture> textures;
sf::Texture texture;
// instantiating the vector of textures and the image not shown here
for (int i = 0; i < certainSize; ++i)
{
    if(certainContition)
    {
        texture.setTexture("file");
        texture.setPosition(pos1, pos2);
    } else
    {
        ...
    }
image.draw(texture);
}

```

The point here is that I draw single textures on a `sf::RenderTexture`, but because textures always are on the graphic cards memory, I can't exceed a certain map size which I have to.
I also considered using an `sf::Image`, but I can't find a way to draw an image (i.e. a texture) to it.
The third way I found was using an `sf::VertexArray`, but this seems to be a bit too low-level for my rather simple purposes.
So is there a common way to dynamically generate a background image based on other existing images?

# Answer
I had the exact same problem and this is how I solved it.

I am not sure exactly what limit you are hitting. It could be that you are using only one `sf::RenderTexture` and are hitting the max texture size, or you are using more than one `sf::RenderTexture` and are hitting the graphics card memory limit.

If it is the first, you might consider using more than one texture and creating a tiled background image. You would split your background into a 256x256 or 512x512 (or maybe higher) grid and then render each tile that is currently in the view.

Something like:

```
//---BACKGROUND CREATION---//
std::vector<std::vector<sf::RenderTexture*>> background;
std::vector<std::Sprite*> sprites;
for(int x = 0; x < MAP_TILE_WIDTH; ++x)
{
    for(int y = 0; y < MAP_TILE_HEIGHT; ++y)
    {
        background[x][y] = new sf::RenderTexture(TILE_WIDTH, TILE_HEIGHT);
        background[x][y]->create(TILE_WIDTH, TILE_HEIGHT);
        background[x][y]->setView(sf::FloatRect(x * TILE_WIDTH,
                                                y * TILE_HEIGHT,
                                                TILE_WIDTH,
                                                TILE_HEIGHT));
    }
}
for(sf::Sprite *sprite : sprites)
{
    const sf::Vector2f &position = sprite->getPosition();
    background[position->x / TILE_WIDTH][position->y / TILE_HEIGHT]->draw(*sprite);
}

//---BACKGROUND RENDERING---//
sf::RenderWindow *window; // initialized somewhere else
const sf::Vector2f topLeft = window->mapPixelToCoords(sf::Vector2f(0,0));
const sf::Vector2f bottomRight = window->mapPixelToCoords(window->getView().getSize());
for(int x = topLeft.x / TILE_WIDTH; x <= bottomRight.x / TILE_WIDTH; ++x)
{
    for(int y = topLeft.y / TILE_HEIGHT; y <= bottomRight.y / TILE_HEIGHT; ++y)
    {
        window->draw(background[x][y]->getTexture());
    }
}

```

If your sprites are sized right and aligned well, this will work nicely. If your sprites can be across tile boundaries then you have to draw the sprites on all the tiles they are positioned over.

This works until you fill GPU memory with all your render textures then you have to move on to method 2 which is some type of streaming system. Tiles close to the view are loaded into an `sf::Texture` via the `sf::Texture::loadFromImage()` function while tiles farther away from the view are copied into an `sf::Image` for storing in system memory via the `sf::Texture::copyToImage()` function. This might cause some performance slowdown due to the copying back and forth from gpu memory but it is the only alternative to reducing the resolution of your images so they fit in GPU memory.
> 1 votes

# Answer
what image format are you using as your backgroud images. some format such as png support transparency. here is a way of creating background image.
> -1 votes

---
Tags: c++, textures, image, sfml, vertex-arrays
---


title: Detailed Modern Opengl Tutorial?

text:
# Question
Title: Detailed Modern Opengl Tutorial?
I am asking for a specific modern opengl tutorial.

I need a tutorial that does not skip to explain any lines of code. It should also include different independent objects moving/rotating (most tutorials use only one object), as well as imported 3d objects and collision detection for them. Maybe not collision detection, but I want to see how to use OpenGL with a real project. It is important for me to know how in a good way I can combine modern opengl and a virtual environment structure.

It should also avoid stuff that won't be used. Arcysnthesis for example gives a new concept, and after teaching it, in the next tutorial, it explains how bad it is for performance and introduces another method.

Do you know any?

# Answer
> 6 votes
> I need a tutorial that does not skip to explain any lines of code. It should also include different independent objects moving/rotating (most tutorials use only one object), as well as imported 3d objects

Arcysnthesis is the best modern OpenGL tutorial I know of, using imported objects doesn't add much to the use of the API, and it's usually API agnostic. Lighthouse3D on the other hand, has some decent tutorials that use openGL 3.0+ and Assimp to import 3D objects.

But in my opinion I think you are **asking for too much from a tutorial**. The topics you are asking for can be covered in multiple books.

**Tutorials are meant to get you started**, most of what you are asking for should be learned by **expanding on the tutorial code and experimenting with it for yourself**, for example multiple object rendering isn't much different from rendering a single object, and most tutorials avoid it because they only want to focus on using a specific feature of the API. **what I recommend is that you get OpenGL Superbible** because it's really detailed and has some nice examples.

> it explains how bad it is for performance and introduces another method

Introducing multiple methods/technique is what I think a good tutorial should do, as it's really essential for understanding the API and the best practices to use.

> and what about collision detection for them?

Other topics like collision detection has nothing to do with rendering (at least directly) and **are just too huge to be included in one tutorial** with other topics. If you just Googled Collision Detection you will find a lot of topics on the subject but in my opinion non of them are *good enough*, because this topic varies greatly depending on the complexity and the requirements you are looking for. I advise you to **get a book like Real Time Collision Detection**. There is also **Real Time Rendering** and its companion site that covers a lot of the intersection testing and collision detection methods.

---
Tags: opengl, collision-detection, objects
---


# Question
Title: What are the advantages and limitations of using Qt for game development?
I know there is already a thread asking for example 3d games written using Qt. What I'd like to have a discussion about is whether or not Qt is a good framework for game development.

In my experience Qt is a joy to work with and thanks to QML and QML/3d it's looking like it could be a viable framework for game development. The thought of using signals and slots for gamedev is exciting.

I'd like to hear some opinions on Qt in general as a game development platform. What are it's limitations? What are it's advantages?

Edit: I found an official Qt game development forum.

# Answer
If used properly, Qt can be great for games. It has good OpenGL support if you want hardware acceleration, and if you're dealing with 2D elements or custom widgets, the QPainter class and its friends have decent performance (just stay away from QPainter::SetOpacity, that'll kill your performance).

The other great thing about Qt for games is Qt Style Sheets. You can create a custom look-and-feel for your GUI using a CSS-like syntax, so your game's GUI won't look like a boring gray platform-specific interface.
> 1 votes

# Answer
I've been working with Qt and it is quite nice, defenitely OK for a not too complicated game, for a 2D game it would be perfect I'd say.

The pros I found:

* integrated translation
* simplicity when creating menus

The cons I've stumbled into:

* no draw calls from other threads than the main thread.
* complicated to debug signals
> 1 votes

# Answer
Although this thread is quite old, maybe this could still be interesting for some of you: V-Play is a cross platform game engine based on Qt.

It offers a wide range of components specialised for game development, monetization and social services.API reference.

You can also have a look at some games that are already live in the App Stores in the showcase section of their homepage.

(Disclaimer: I'm one of the guys behind V-Play)
> 0 votes

---
Tags: qt
---


# Question
Title: Computing pixel's screen position in a vertex shader: right or wrong?
I am building a deferred rendering engine and I have a question. The article I took the sample code from suggested computing screen position of the pixel as follows:

```
VertexShaderFunction()
{
    ...
    output.Position = mul(worldViewProj, input.Position);
    output.ScreenPosition = output.Position;
}

PixelShaderFunction()
{
    input.ScreenPosition.xy /= input.ScreenPosition.w;
    float2 TexCoord = 0.5f * (float2(input.ScreenPosition.x,-input.ScreenPosition.y) + 1);
    ...
}

```

The question is what if I compute the position in the vertex shader (which should optimize the performance as VSF is launched significantly less number of times than PSF) would I get the per-vertex lighting insted. Here is how I want to do this:

```
VertexShaderFunction()
{
    ...
    output.Position = mul(worldViewProj, input.Position);
    output.ScreenPosition.xy = output.Position / output.Position.w;
}

PixelShaderFunction()
{
    float2 TexCoord = 0.5f * (float2(input.ScreenPosition.x,-input.ScreenPosition.y) + 1);
    ...
}

```

What exactly happens with the data I pass from VS to PS? How exactly is it interpolated? Will it give me the right per-pixel result in this case? I tried launching the game both ways and saw no visual difference. Is my assumption right?

Thanks.

P.S. I am optimizing the point light shader, so I actually pass a sphere geometry into the VS.

Solution:

```
struct PSInput
{
    float2 vPos : VPOS;
};

PixelShaderFunction(PSInput input)
{
    float2 ScrPos = input.vPos*halfPixel*2;

        //The correct Screen Space Texture Coordinates.
    float2 TexCoord = ScrPos + halfPixel;

    //Bonus: getting the world position.
    ScrPos = ScrPos*2 - 1;
    ScrPos = float2(ScrPos.x, -ScrPos.y);

    float4 position;
    position.xy = ScrPos;
    position.z = depthVal; // Read from the depth map.
    position.w = 1.0f;

    position = mul(position, InvertViewProjection);
    position /= position.w;
}

```

# Answer
As you are using hlsl I presume you use DirectX. You can use the input semantic VPOS (DX9) or SV\_Position (DX\>=10): MSDN - VPOS & SV\_POSITION semantics

When you pass the render target resolution reciprocal one mad is sufficient to construct the screen space uv for every type of geometry.

---

You can not simply do what you proposed as the interpolation does a perspective correction. In SM4 you can deactivate this for a single fragment shader input by setting the interpolation modifier to `noperspective`: MSDN - InterpolationModifier

I did not use this method but it should work. Using the semantic is the easier and probably equally performant way.

---

A simple optimization for your code is replacing

```
float2 TexCoord = 0.5f * (float2(input.ScreenPosition.x,-input.ScreenPosition.y) + 1);

```

by

```
float2 TexCoord = 0.5f * float2(input.ScreenPosition.x,-input.ScreenPosition.y) + 0.5f;

```

this should ensure that a mad instruction is used instead of two seperate instructions.
> 5 votes

# Answer
I doubt it you will get a optimized gain from this. But to answer your question, that looks a bit funky. rather do it like this :

Setup a quad with the vertex positions from -1 to 1 in xy. In the pixelshader just simply pass the input position as the SV\_Position. no need for projection multiplications.

And for uvs, do the following equation.
texCoord = ( input.pos + 1.0f ) * 0.5f;
-1 + 1 -\> 0 -\> 0 * 0.5 = 0
1 + 1 -\> 2 -\> 2 * 0.5 = 1
And from there you have the basic 0-\>1 uvset.

This is super simple and should be super fast to.
> 0 votes

---
Tags: hlsl, vertex, fragment-shader, interpolation
---


# Question
Title: Does research exist on the impact of vibration in mobile games?
I've implemented vibration for various player collisions in my mobile game, but I feel like this is not a common thing on mobile even though it is on consoles.

Is there any research on the positive or negative benefits of using vibration feedback in mobile games that would suggest guidelines for when it is and isn't appropriate to use?

# Answer
I don't think you will find the specific research you are probably looking for. However, it may exist: the predominate source of papers on the subject of haptic feedback seems to be the Immersion Corporation, who have published a series of white papers on the topic.

I also stumbled across this paper, which is a course thesis, on the subject.

Actual market research data may be available (for example, from here). You will need to pay for this research in almost all cases. For other sources of market research, you can browse this site. There have been at least a few questions on the subject (not specifically concerning vibration, but the resulting research firm sites may be worth a browse).

Haptic feedback can be a good way to inform a user of game state changes without necessarily having visual feedback; this is especially useful in a game where the player may not always be looking at the part of the screen that stimulates the feedback (for example, in a shooter, they may be looking at a target and the vibration can tell them their ship or character is being damaged, and that they should refocus their attention temporarily).

My gut feeling says that you should:

* Keep the vibration in your game. You already implemented it, after all. If it turns out this is a common thing in your genre, then you are doing what people will have expected. If it turns out it is an uncommon thing, you have given yourself a differentiating factor. Something to set your game apart.
* If possible, make sure your vibration is distinct enough in feeling from built-in, system vibrations (like "new email" or "missed call"). Consider disabling the vibration if you cannot make it different enough on a given system, to avoid potential user confusion.
* Build in an option to disable the haptic feedback if a user desires. That way, if somebody finds it annoying or if they need to play in a quiet environment where even the hum of the phone motors can be distracting, they can do so.

If you have enough friends/beta testers/et cetera, you could also consider conducting an informal user feedback session. Give some players a version of the game with feedback on, some with feedback off, for example, and poll them about who had more fun and felt more engaged in the game. Or provide a survey inquiring as to how they felt the feedback added or detracted from the gameplay.
> 6 votes

---
Tags: mobile, user-experience
---


# Question
Title: What would be a good way to implement/render a 2D tiled map for a browser game?
I coded a a little RPG in ruby and I used an array to contain the map squares. The elements of the array (which defines the X coordinates) are arrays themselves whose elements defines the Y coordinate, and each of these are arrays too which stores the terrain data on first position, and player/npc/objects/buildings on following positions.

What I am trying to do is render those terrain data "squares" to a 2D tiled map in the browser.

The map does not need to refresh or be dynamically fetched as you scroll it, (at least at this stage of development) but an implementation which would allow me to do so in future is a possible path.

Being a total beginner at web design/rendering the things that I thought of are: HTML tables, HTML5 canvas, some JS framework which is designed exactly with this purpose (which I do not know of = please advice).

I know about gameQuery but I've never used it and I don't know if it's going to slow everything down as I will be adding new features (scrolling, ajax).

I really don't know of any other alternatives, maybe there any lighter approaches? Easier or more minimalistic ways ? More targeted JS framework which is the right tool for the job? Maybe just some html canvas code, or even simple image maps, or images with absolute positioning will be enough?

The thing is that I'd like to start simple, and then gradually make it better, so I'd like something which will give me a bit of gratification in the beginning but that also has room for improvement and is headed toward new web technologies

p.s. Flash is excluded of course...

**Update**: rewrote the question in a more decent english (hopefully) :)

# Answer
> 2 votes
I ended up using Fabric.js:

> Fabric.js is a powerful and simple Javascript HTML5 canvas library.

Look at this:

```
// create a wrapper around native canvas element (with id="c")
var canvas = new fabric.Canvas('c');

// create a rectangle object
var rect = new fabric.Rect({
  left: 100,
  top: 100,
  fill: 'red',
  width: 20,
  height: 20
});

// "add" rectangle onto canvas
canvas.add(rect);

```

It has many more features and **this was exactly the simple and "extensible" approach I was looking for for a start**. At the time it was quite a big project for me and I needed all but adding tedious low-level canvas code to the mix.

# Answer
> 17 votes
Let's start with the array. Don't think about it as tridimensional. Indeed, if you want to have stackable units there, it makes sense at first sight:

* first dimension is collumns of rows of tiles
* second dimension is rows of tiles
* third dimensions is tiles, i.e. arrays of units.

But this third dimension won't be consistent, as you will store there not only units, but also tile's properties like it's height or terrain type. Also, while tiles are fixed and don't move, a player will bring some units to front, move to other tiles etc, and so it doesn't behave like a dimension.

Create a two dimensional Array (a grid) of tiles, where a tile is an object with it's own properties, one of which is an Array of units residing there.

I also don't recommend using a framework to learn - Give yourself a try, and after a month or two you will know what features you need and only then look for a framework if you really need. But as it goes for 2D, features frameworks provide aren't astonishing. Keep in mind frameworks have their limits and with as simple things as 2D tile game I would rather create everything from scratch, then learn to use a framework.

I don't program in JS, so I can't recommend a good IDE, but I made something in JSFiddle for you, because I know that beginnings are hard.

http://jsfiddle.net/8adUK/1/

# Answer
> 9 votes
Renderer apart, consider reading the following articles to understand how older systems implemented optimal tile-based map traversal:

Tile-Based Games FAQ version 1.2, and Tile Graphics Techniques 1.0

They're indispensable guides for implementing tile based games on systems which may have limited resources. In terms of today's technology, HTML5-based games' loading-times are affected by HTTP connection speed, and it's still important to keep memory usage as low as possible.

The bottom line for optimal tile map rendering is breaking your map down into X\*Y regions, and only loading those regions as they are needed. Once you can load, unload, and render a region, you're on your way to handling variably-sized maps.

*(Another method would be to implement strip-loading; i.e. loading a strip of tiles as the user progresses through the map. When loading using AJAX or WebSockets, however, this mightn't be optimal.)*

To start out, consider defining some logical entities, and progress from small to large.

* Tile: A single tiny entity which can have a terrain type, a graphic, an onEnter event, an onLeave event, an altitude,
* Region: A two-dimensional array of Tiles, which can also have onEnter and onLeave events. It should also have render functionality. When you're drawing content from the map, consider drawing it in a 3x3 array of regions.
* Map: A two-dimensional array of regions.
* Camera: A virtual object which has X,Y coordinates, which the player "controls" when he traverses the map. The Camera should know what Region it's currently viewing, as well as surrounding Regions in N/S/E/W and NE/NW/SE/SW directions. It has a clipping rectangle; when a region's border goes outside of the clipping rectangle, the player has traversed a region; the three 'out of sight' regions can be deleted from memory, and three 'new' regions loaded into memory.

Good luck!

# Answer
> 1 votes
Have a look at Impactjs. It is a game framework that allready implements a tile/camera system, -the tiles can even be animated- and offers a nice level editor. It is not free, it is 100 bucks, it uses html5 = canvas + javascript, is quite well written and documented, despite a few annoying design flaws, and there's a community around.
http://impactjs.com/
http://www.pointofimpactjs.com/

There's also Gamvas, a free javascript gaming framework, perfectly written and documented, but which does not handle tiles natively and has little community. (still it handles camera, physics with Box2D, animation, sound, events,...).
http://gamvas.com/

There are obviously a lot of other frameworks but they did not convince me, ...

Did you google for a javascript / canvas framework that does tiling ? maybe just by combining a few little frameworks together it might do it.
Crafty.js is a starter for instance :
http://craftyjs.com/
it is free, very small and does allready quite a few things for you.

# Answer
> 0 votes
I would strongly recommend using canvas, not discrete html elements. In my experience, you'll find that discrete HTML elements works ok when they are small in number, but becomes bad at scale. You may also find garbage collection pauses are worse when there are lots of html elements to GC rather than just Javascript objects (for example, if you used one html element for each particle or explosion)

You'll want to write your own (simple) renderer which performs culling, i.e. only renders those tiles within the displayed area (or perhaps slightly outside).

I wrote such a game and found that it performed very well on most desktop browser (yes - even Internet Explorer).

When you want to do more fancy effects, you will probably want to move to WebGL, because the performance of stuff like blending is going to be quite variable (i.e. poor) for 2d canvas.

---
Tags: javascript, html5, tiles, maps, html-canvas
---


# Question
Title: Model in Maya looks strange, what went wrong?
I am modeling a tank and I don't know what key I've pressed, but now the object in Maya is looking very weird.

Does anybody know how to solve this problem?

# Answer
> 4 votes
The issue was due to z-fighting in an inaccurate depth buffer. The reason the depth buffer got inaccurate was because your camera's near and far clipping planes had gotten too far apart. Basically, the depth buffer has a limited number of possible depth values that are spread out between the near and far clipping planes. Thus as the clipping planes get further apart, the depth values spread apart as well.

I believe the far clipping plane in Maya gets pushed out automatically as you zoom the camera, so going to an extreme zoom will cause this issue.

The reason pasting your model in a new file fixed the issue was because the camera's near and far clipping planes were reset.

# Answer
> 2 votes
To fix this issue you want to go to

1. view\>camera attribute editor. in the panel windows, and then in the attribute editor change the
2. near clip plane to 0.100 (or whatever works for your scene).
3. far clip plane to 10000.000 (or whatever works for your scene).

# Answer
> 0 votes
Sorry guys, I fixed it. I just had to copy the object, open a new file and paste it in there. I still don't know what the cause of this problem was, but this is a solution.

Thanks everyone for helping, thanks a lot!

---
Tags: 3d, models, maya
---