# Question
Title: Better way to find all sprites that would overlap with other sprite
first question on this site :-)

I'm not really sure that the title is very clear so feel free to edit/suggest a better one.

I have a piece of Game Maker code which works, but feels like a bit of a hack and also causes some side affects else where so I wanted to know if there is a better way.

I'm building a Tetris clone and this snippet occurs in the Step event of the falling tile parent object. The idea is that when the falling object collides with something it should be replaced by 'brick' objects so that I can destroy them independently.

So what I want to do is test whether a brick would overlap with the falling object and if so then create a brick there. I'm using an instance of brick (called trialBrick and created globally) to do the testing.

I could just try creating a brick and then destroy it if it doesn't overlap with the falling object but I'm not sure whether this is efficient or not.

Thoughts?

```
// just move the brick downward if we can by one pixel.
var obstacle = instance_place(x, y + 1, all);
if (obstacle != noone)
{
    isFalling = false;

    // loop through each row of the object.
    var row;
    var column ;
    for (row = y - 4 * brickSize; row < y + 4 * brickSize; row += brickSize)
    {
        for (column = x - 4 * brickSize; column < x + 4 * brickSize; column += brickSize)
        {
            // need to check whether the current row and column intersects with this falling object.
            trialBrick.x = column;
            trialBrick.y = row;

            with (trialBrick)
            {
                if (place_meeting(x, y, objFallingParent))
                {
                    instance_create(x, y, objBrick);
                }
            }
        }
    }
    trialBrick.x = 0;
    trialBrick.y = 0;

    // remove ourselves from the game.
    instance_destroy();
}

```

**Edit:** The 'problem' is when I test whether the bricks are outside the play area (indicating game end) I have to remember to exclude the trialBrick. It would be nicer if I didn't have the trialBrick at all.

# Answer
> 1 votes
Turns out what I was looking for is the `instance_position` function.

> When you use this you are checking a single point in the room for an instance or an object.

Here is my updated code without need for the trialBrick.

```
// just move the brick downward if we can by one pixel.
var obstacle = instance_place(x, y + 1, all);
if (obstacle != noone)
{
    isFalling = false;

    // loop through each row of the object.
    var row;
    var column ;
    for (row = y - 4 * brickSize; row < y + 4 * brickSize; row += brickSize)
    {
        for (column = x - 4 * brickSize; column < x + 4 * brickSize; column += brickSize)
        {
            if (instance_position(column, row, objFallingParent))
            {
                instance_create(column, row, objBrick);
            }
        }
    }

    // remove ourselves from the game.
    instance_destroy();
}

```

---
Tags: game-maker
---


# Question
Title: SDL2 - Isometric map: Draw visible tiles or draw pre-rendered slice of the whole map?
I started a small project which is basically an isometric map with tiles. Right now I render only the visible tiles - at each rendering cycle.

Because I don't have experience with actual SDL2 projects I'm asking myself if I can **store a large map** (e.g. 10000 x 10000 tiles with 32px each) **completely into an SDL\_Texture**. In my rendering routine I could slice out everything that's visible and draw a few things on top of it, e.g. units.

# Answer
> 1 votes
I'd recommend against storing a huge image as a texture like that. SDL\_Texture is stored in your video memory which only has so much space, usually a lot less than the main memory on your machine. Even if you're only drawing a screen sized portion of the texture you sill have 10000x * 10000y * 32px * 32bpp (almost 12Gb (I don't think they even sell cards with that much memory)) clogging up your vram.

You'll want to stick with tiles is what I'm saying. Best approach is to put all your tiles on the one image and load that up as a texture and then draw each of the visible tiles each draw. That way you pack a much smaller texture into vram. Don't worry too much about asking your gpu to draw a lot of sprites per frame if they're made in succession on the one texture, gpus are designed to do just that!

---
Tags: sdl2
---


# Question
Title: Rotate an object smoothly by 90 degrees on key press in unity3D
\[I saw few similar question on stackexchange but none is solving the purpose.\]

I want to rotate a 3D object by 90 degrees on different axis on respective inputs. For example if 'a' is pressed, the object should rotate left by 90 degrees. `transform.Rotate(0,90,0);` is working but it is not rotating the object smoothly.

I am new to C# and js so cannot manually code but I tried the codes given in this answer at Rotate an object smoothly on the Y axis in Unity. The below code works but it it has two problems - code:

```
void Update () {
SwingOpen();
}

void SwingOpen()
{
    Quaternion newRotation = Quaternion.AngleAxis(90, Vector3.up);
    transform.rotation= Quaternion.Slerp(transform.rotation, newRotation, .05f);
}

```

Problem 1: The above code rotates object without any keyboard inputs. I added the condition `if (Input.GetKeyDown (KeyCode.RightArrow))` but now the object rotates partially on every keyboard input. I want to rotate it by 90 degrees on a single key press.

Problem 2: It will never actually rotate the object by 90 deg. It will always be tending towards 90 deg. I want exact 90 deg rotation to allow multiple 90 deg rotations for 'n' number if inputs.

How can I solve this? Please help. Please let me know if the question isn't clear enough.

\[EDIT\]

I applied the below script but it is giving me some totally unexpected output

Code:

```
public float speed = 1;
private int xtimesHit = 0;
private int ytimesHit = 0;
private int ztimesHit = 0;

void Update () {
    if( Input.GetKeyDown( KeyCode.RightArrow ) ){
        ztimesHit--;
    }
    if( Input.GetKeyDown( KeyCode.LeftArrow ) ){
        ztimesHit++;
    }

    if( Input.GetKeyDown( "a" ) ){
        ytimesHit++;
    }
    if( Input.GetKeyDown( "d" ) ){
        ytimesHit--;
    }

    if( Input.GetKeyDown( "w" ) ){
        xtimesHit++;
    }
    if( Input.GetKeyDown( "s") ){
        xtimesHit--;
    }

    this.transform.rotation = Quaternion.Lerp(this.transform.rotation, Quaternion.Euler(xtimesHit*90,ytimesHit*90,ztimesHit*90), Time.deltaTime*speed);

}

```

On running this script If I press rightarrow once followed by 's' the object rotates on 'z' axis and 'x' axis correctly but there after if I press arrowkeys or 'a/s' in both the cases the object rotates on y axis. I dont understand why this is happening.

I want it to rotate w.r.t. the world axis always.

# Answer
This is how I would do it

```
private Quaternion startingRotation;
public float speed = 10;

void Start(){
    //save the starting rotation
    startingRotation = this.transform.rotation;
}

void Update () {
    //return back to the starting rotation
    if( Input.GetKeyUp( KeyCode.RightArrow ) || Input.GetKeyUp( KeyCode.LeftArrow ) ){
        StopAllCoroutines();
        StartCoroutine(Rotate(0));
    }

    //go to 90 degrees with right arrow
    if( Input.GetKeyDown( KeyCode.RightArrow ) ){
        StopAllCoroutines();
        StartCoroutine(Rotate(90));
    }

    //go to -90 degrees with left arrow
    if( Input.GetKeyDown( KeyCode.LeftArrow ) ){
        StopAllCoroutines();
        StartCoroutine(Rotate(-90));
    }

}

IEnumerator Rotate(float rotationAmount){
    Quaternion finalRotation = Quaternion.Euler( 0, rotationAmount, 0 ) * startingRotation;

    while(this.transform.rotation != finalRotation){
        this.transform.rotation = Quaternion.Lerp(this.transform.rotation, finalRotation, Time.deltaTime*speed);
        yield return 0;
    }
}

```

---

Edit # 1

```
public float speed = 1;
private int timesHit = 0;

void Update () {
    if( Input.GetKeyDown( KeyCode.RightArrow ) ){
        timesHit++;
    }
    if( Input.GetKeyDown( KeyCode.LeftArrow ) ){
        timesHit--;
    }

    this.transform.rotation = Quaternion.Lerp(this.transform.rotation, Quaternion.Euler(0,timesHit*90,0), Time.deltaTime*speed);

}

```

---

Edit #2

Perhaps like this?

```
public float speed = 1;
private GameObject endRotation;

void Start(){
    endRotation = new GameObject();
}

void Update () {
    if( Input.GetKeyDown( KeyCode.RightArrow ) ){
        endRotation.transform.Rotate(Vector3.forward, 90, Space.World);
    }
    if( Input.GetKeyDown( KeyCode.LeftArrow ) ){
        endRotation.transform.Rotate(Vector3.forward, -90, Space.World);
    }

    if( Input.GetKeyDown( "a" ) ){
        endRotation.transform.Rotate(Vector3.up, 90, Space.World);
    }
    if( Input.GetKeyDown( "d" ) ){
        endRotation.transform.Rotate(Vector3.up, -90, Space.World);
    }

    if( Input.GetKeyDown( "w" ) ){
        endRotation.transform.Rotate(Vector3.left, 90, Space.World);
    }
    if( Input.GetKeyDown( "s") ){
        endRotation.transform.Rotate(Vector3.left, -90, Space.World);
    }

    this.transform.rotation = Quaternion.Lerp(this.transform.rotation, endRotation.transform.rotation, Time.deltaTime*speed);

}

```
> 3 votes

# Answer
Well, the solution here is pretty simple - if you don't know how to write your own code yet, you should definitely take a course rather than looking up code and trying to patch it in your program somehow without knowing at all how it works.

First, delcare a variable called currentFrame, and initially set it to -1. Also, make a variable called numOfFrames, and set it to the number of frames over which the change will occur.

```
void Update () {
    if(Input.GetKeyDown(KeyCode.RightArrow) && currentFrame == -1) {
        currentFrame = 0;
    }
    if(currentFrame >= 0 && currentFrame < numOfFrames) {
        SwingOpen();
        currentFrame = currentFrame + 1;
    }
}

void SwingOpen()
{
    if (currentFrame == numOfFrames) {
        Quaternion newRotation = Quaternion.AngleAxis(90, Vector3.up);
        transform.rotation = newRotation;
        currentFrame = -1;
    }
    else {
        Quaternion newRotation = Quaternion.AngleAxis(90, Vector3.up);
        transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, .05f);
    }
}

```

Is this what you wanted? Obviously the code could probably be made cleaner but the concept will be the same.
> 1 votes

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


# Question
Title: Transition from UIView to CCScene in Cocos2D
I've surfed the internet for quite some time but haven't come to find an answer. Any help would be greatly appreciated. I am trying to perform a transition from a UIView to a CCScene So i have a class which is connected to a .xib file. I am able to present that scene using

> \[\[CCDirector sharedDirector\]replaceScene:\[LevelSelect scene\] withTransition:\[CCTransition transitionCrossFadeWithDuration:1\]\];

But when i try to change to a CCScene which does not have a .xib file, it doesn't perform the transition, but plays the audio that is present in the next scene.

> \[\[CCDirector sharedDirector\]replaceScene:\[Play sceneWithDifficulty:1\]\];

Thanks.

# Answer
I found it, i was adding the view but not removing it.
So, even if the view was loading, it loaded under all the view.
Now before every transition, i remove the current xib view and then perform the transition.

> \[myXIBFile removeFromSuperView\];
> 0 votes

---
Tags: cocos2d-iphone, cocos2d, objective-c
---


title: Libgdx understanding screen size

text:
# Question
Title: Libgdx understanding screen size
I'm trying to create my own jumper type game where the player moves up through an infinite y value. The problem I am having is getting the screen size to match up with the android screen.

```
  viewport = new FitViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), camera);
    camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

```

Currently I just want the sprite to be drawn in the center of the screen. I'm not worried about the game world size as it will differ from each device.

```
  camera.update();
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    batch.draw(player.getKeyFrame(animationTime), Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);

```

This draws the player somewhere in the upper right corner of the screen. It's my understanding that Gdx.graphics.getwhatever is used to get the dimensions of whatever your device screen is. So I'm wondering if I'm using the viewport class correctly or not?

# Answer
The call to `camera.setToOrtho` sets the `camera`s position to the center. So it's P(0,0) is the middle of the `Screen`. So you are seeing everything from `P(-Gdx.graphics.getWidth() / 2, -Gdx.graphics.getHeight() / 2)`, which is the lower, left corner, to `P(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2)`, which is the upper, right corner, where your player is drawn at.
There are now two posibilities:

* Draw your `player` at P(0,0)
* Set the `camera`s position to `P(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2)`

Also, don't forget to call `viewport.update(width, height)` in the `resize(width, height)` method.
And you might consider using a different `Viewport` size. It could make things easier, as you don't need to think in pixels, but in meters or another preferred unit. The `Viewport` size will then be "translated" to pixels by Libgdx, you don't need to worry about that.

**EDIT:** As @MrPlow wrote in this comment, the `sprite`s origin by default is it's lower left corner. Also it's position is given by the lower left corner, not it's center.
While the `origin` can be changed, so that the `sprite` will be scaled and rotated arround the given `origin`, the position will always be the lower left corner.
> 2 votes

---
Tags: java, libgdx
---


# Question
Title: Unity - Missing Render Setting from Edit menu
Where I can select Render Setting from Edit menu from Unity5? It looks missing.

It suppose to be like this one.

Please advice. Thank you.

# Answer
Choose Window\>Lighting from the menubar.

That should have all of the same settings as render settings in Unity 4.
> 1 votes

---
Tags: unity
---


title: Grenade throw logic

text:
# Question
Title: Grenade throw logic
My case is:

We are developing a kart racing game, and the players are fighting with each other and trying to reach the finish line.

The thing is, I am confused over how to implement following logic:

The player has missile and grenade as weapons.

I can do missile lock, then the missile follows the enemy and hits the enemy with it. (Vector3.MoveTowards()).

But how would I do grenades?

Suppose both enemies and players are moving forward on the Z axis:

Case 1:

> Player throws grenade at enemy.
>
> It goes and hits enemy.

\**I can do this the same way as missile logic.

Case 2:

> Player throws grenade at enemy.
>
> Enemy changes position on the X axis (right, left).
>
> Grenade should not follow player to the next position.

\**I am confused about this case: how to let grenade not change its position and get the blast on surface??

# Answer
You could model the grenade as a conventional rigidbody with an initial speed and have it affected by gravity. Add a script with an OnCollision method to trigger when it touches a vehicle or the ground.
> 2 votes

# Answer
When throwing the grenade, take a copy of the enemy's original position Vector3. Move towards that instead of towards the enemy GameObject. Alternatively spawn in a pre-cache'd "GrenadeTarget" GameObject at the original enemy position as a marker and move the missile towards that.
> 0 votes

---
Tags: unity
---


# Question
Title: Is Global location using OpenGL bound by the shader?
I have recently started writing a game engine in C++ with OpenGL and using some tutorials online. So far from what I have seen, shaders are the way to manipulate an object's position in worldspace. Is this true or is there a way to write a physics engine which can work without shaders in order to "move" and object in worldspace?

# Answer
Shaders are just programs that run on different stages of the graphics pipeline. You say:

> So far from what I have seen, shaders are the way to manipulate an object's position in worldspace.

This is partially correct, as this is not the only thing shaders can do. Moving an object's position in world space would be the job of a **vertex shader**.

Vertex shaders work on each vertex passed to it. A simple shader that moves an object would be like:

```
#version 410 core
uniform mat4 mvp;
layout(location = 0) in vec4 vPosition;
void main() {
  gl_Position = vPosition * mvp;
}

```

This shader simply does `for each vertex multiply by matrix mvp`.

The `mvp` is just a matrix comprised of a **Model Matrix**(the objects position), **View Matrix**(the view/"camera" matrix) and a **Projection Matrix**(usually a perspective projection martix).

There is a great OpenGL tutorial here which should help you further understand OpenGL, shaders and how matrices work to move your objects.
> 2 votes

# Answer
Physics engine and shaders are unrelated. A game engine stores object's location/orientation somewhere and both shaders and physics engine can use it. Vertex shaders can modify the position to change an object's appearance but it's a visual thing, the rest of the game engine doesn't automatically get the modified position.
> 1 votes

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


# Question
Title: Rotation with respect to world instead of the object itself using Quaternion.Euler in unity
\[Other answers on similar questions on stackexchange didnt help\]

This script is giving some weird outputs

On running this script If I press rightarrow once followed by 's' the object rotates on 'z' axis and 'x' axis correctly but there after if I press arrowkeys or 'a/s' in both the cases the object rotates on y axis forever. I dont understand why this is happening.

I want it to rotate w.r.t. the world axis always.

code:

```
public float speed = 1;
private int xtimesHit = 0;
private int ytimesHit = 0;
private int ztimesHit = 0;

void Update () {
    if( Input.GetKeyDown( KeyCode.RightArrow ) ){
        ztimesHit--;
    }
    if( Input.GetKeyDown( KeyCode.LeftArrow ) ){
        ztimesHit++;
    }

    if( Input.GetKeyDown( "a" ) ){
        ytimesHit++;
    }
    if( Input.GetKeyDown( "d" ) ){
        ytimesHit--;
    }

    if( Input.GetKeyDown( "w" ) ){
        xtimesHit++;
    }
    if( Input.GetKeyDown( "s") ){
        xtimesHit--;
    }

    this.transform.rotation = Quaternion.Lerp(this.transform.rotation, Quaternion.Euler(xtimesHit*90,ytimesHit*90,ztimesHit*90), Time.deltaTime*speed);

```

How can I do that? I have created this code with help from other, so I'd wish to edit it rather than using totally new functions.

\[Optional\] Code explanation: My code is fulfilling partial requirements, I want to rotate my object on x,y,z axis by 90 deg on respective keyboard inputs. (Example: keys a and s should rotate the object by 90 deg on z axis, w and s should rotate the object by 90 deg on y axis and arrow keys should rotate the object by 90 deg on y axis). Also pressing 'a' n times should rotate the object by 90 deg n times.

# Answer
> 2 votes
Because rotations are order-dependent, as described in my comment above, the internal state you store needs to fully-describe an orientation.

In general, you can do this by storing a targetOrientation quaternion. If you're only ever doing rotations of +-90 degrees about the x/y/z axes then you can store a more reduced state (there are only 24 possible values), but I think this version is clearer to read:

```
public float speed = 1;
private Quaternion targetOrientation = Quaternion.identity;

void Update () {
    if( Input.GetKeyDown( KeyCode.RightArrow ) ){
        targetOrientation = Quaternion.Euler(0, 0, -90) * targetOrientation;
    }
    if( Input.GetKeyDown( KeyCode.LeftArrow ) ){
        targetOrientation = Quaternion.Euler(0, 0, 90) * targetOrientation;
    }

    if( Input.GetKeyDown( "a" ) ){
        targetOrientation = Quaternion.Euler(0, 90, 0) * targetOrientation;
    }
    if( Input.GetKeyDown( "d" ) ){
        targetOrientation = Quaternion.Euler(0, -90, 0) * targetOrientation;
    }

    if( Input.GetKeyDown( "w" ) ){
        targetOrientation = Quaternion.Euler(90, 0, 0) * targetOrientation;
    }
    if( Input.GetKeyDown( "s") ){
        targetOrientation = Quaternion.Euler(-90, 0, 0) * targetOrientation;
    }

    this.transform.rotation = Quaternion.Lerp(
                                this.transform.rotation,
                                targetOrientation,
                                Mathf.Clamp01(Time.deltaTime*speed));
}

```

There's a possibility, depending on how Unity does its rotation math, that rounding errors could creep into this form over time. Try it and see if that occurs. If so, there are some steps we can take to snap the internal state to one of the 24 valid ones and prevent error accumulation.

---
Tags: c#, unity, rotation, quaternion, gimbal-lock
---


# Question
Title: Unity3D - Change player input axes on trigger
Hope someone can help me with this, it seems like it should be a simple problem but that only makes it more frustrating!

I have a simple game where you roll a ball around by applying force to the horizontal and vertical axes. What I want to happen is, on a trigger, the axes switch from say the X and Y, to the X and Z, changing the way the player controls without changing the input buttons... The script I use to move the player is below:

```
{
  float moveHorizontal = Input.GetAxis ("Horizontal");
  float moveVertical = Input.GetAxis ("Vertical");

  Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
  rb.AddForce (movement * speed);
}

```

(Where rb is the player ball object) - I'm thinking I'm going to have to change the way the player is controlled as I can't any reference to a 3rd axis in the Input.GetAxis documentation... any help with this would be great!

Thanks!

# Answer
> 1 votes
How about something like this:

```
public class TriggerMovement : MonoBehaviour
{
    float speed;

    enum eAxis
    {
        Normal = 0,
        Switched,

        MAX
    }

    Vector3[] horizontalAxes = new Vector3[(int)eAxis.MAX];
    Vector3[] verticalAxes = new Vector3[(int)eAxis.MAX];

    eAxis curAxis = eAxis.Normal;
    void Start()
    {
        //Setup all axes you want to use here ...
        horizontalAxes[0] = new Vector3(1f, 0f, 0f);
        horizontalAxes[1] = new Vector3(0f, 0f, 1f);

        verticalAxes[0] = new Vector3(0f, 1f, 0f);
        verticalAxes[1] = new Vector3(1f, 0f, 0f);
    }

    void doMovement(Rigidbody rb)
    {
        //Get Input
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        //Set input on appropriate axes
        Vector3 horizontalMovement = horizontalAxes[(int)curAxis] * moveHorizontal;
        Vector3 verticalMovement = verticalAxes[(int)curAxis] * moveVertical;

        //Get total movement
        Vector3 movement = horizontalMovement + verticalMovement;

        //Scale by speed
        rb.AddForce(movement * speed);
    }
}

```

If you define the axes you want to use up front then the movement method could make use of the currently selected axes and apply the moevement from the triggers to those axes. To switch the axes you would just need to change the curAxis enum.

I haven't run this code but believe it should do what you want. Any questions just ask :)

---
Tags: c#, unity, input, control
---


title: Pathfinding Algorithms

text:
# Question
Title: Pathfinding Algorithms
I am new to game programming I currently am using unity's 2D power to remake an 2D game for sake of practice. So I am just little confuse about one thing, so far every enemy in my game was dumb(they move on predefined paths) but this enemy, alien-copter, flies and follow the player wherever the player goes. My question is should I implement any pathfinding algorithm? I had studied A\* but I trying to figure out if A\* is gonna be helpful in my envoirnment because player will be moving and the enemy have to keep on looking for shortest path. I tried to write code for this AI my code was working perfect when there were no obstacles but my game has obstacles so I want something efficient so what do you people think should I implement A\* or any other algorithm or not?

# Answer
without any clues of what your game looks like, what platform it is aimed for and what are you willing to do I'm going to try to give some hints (since I myself have been in your place):

**Research:**

* Research games that look alike the one you're making;
* Contact the devs of such games, converse with they implementations and strategies;
* Do some reverse engineering.

**Try:**

* You asked: "my code was working perfect when there were no obstacles but my game has obstacles \[...\] should I implement A\* or any other algorithm?" Yes, yes you should. That's just the next step to know if the algorithm will be suitable for your game;
* Experiment with navigational meshes, waypoints, different heuristics and note down the results to compare and evaluate;
* Also https://gamedev.stackexchange.com/a/73740/30632

And lastly, when I was first learning path-finding algorithms, I used to make tons of little test cases to see how would the agent behave in certain situations and how could I make it do better by tweaking the heuristics and etc.
> 1 votes

---
Tags: algorithm, path-finding
---


# Question
Title: What is a reasonable way to avoid GC issues in Unity?
I've been reading about how garbage collection is a big problem when programming games using C#, Java, and the like - if you have a large amount of objects, the GC will run sporadically and scan through all the non-static objects you have, deleting them from memory as necessary. This can bog down your framerate or cause the game to crash if you've got a lot of objects.

From what I've read, the problem can be mitigated by statically declaring many objects during the game's initialization and storing them in an object pool (swapping out "active" and "inactive" static objects as needed so that the GC is never run). But I know it's also generally bad practice to use static objects (since it can become unclear what's what in memory, etc, etc) and I'm wondering if there's a middle ground.

So I guess I've really got 2 related questions:

1. **Is object pooling using static objects the best way to avoid GC?**
2. **Under what circumstances should a Unity game be developed with some kind of GC avoidance in mind - when you're expecting to have 100 objects? 1000? 10000+?**

# Answer
> 3 votes
If you're really hardcore and want to take the extra optimization, a static object pooler will be the best choice performance-wise. Most of the time, an instance object pooler will work perfectly. It all depends on what you're doing and what platform you're targeting. PC games usually take longer so an instance object pooler that only recycles objects for the current session will be fine - that, and PCs are much more powerful. On a mobile device, you might want to consider using static object pooler because instantiation/destroy is more expensive and sessions are shorter.

The number of objects you have doesn't matter so much as how frequently those objects get instantiated and destroyed. For anything that's redundant and created frequently, you should pool them. For example, bullets, creeps, pick-ups, etc.. By the time you have a system set up for those things, you might as well pool everything else to make your object creation more centralized but for a game that doesn't have any redundant objects that are spawned frequently, pooling is an unnecessary effort.

---
Tags: c#, unity, frame-rate
---


title: Large scale iterative design

text:
# Question
Title: Large scale iterative design
Typically in game development, linear development (waterfall model) is riddled with obstacles that drain the programmer's sanity (game turned out horrid, can't redesign). Enter iterative design. Iterative design allows for prototyping of various possibilities in the play space. Unfortunately, it has a *major* catch. As soon as a project increases in size, iterations become tediously long killing off the main advantage: rapid results.

**How can one shorten design iterations for large scale projects?**

# Answer
> 4 votes
I think good infrastructure can help this. One example is having a nice, easy to use data system that engineers can easily expose new data through, and that designers can quickly alter data and see their results. Another good one is having a scripting language - like lua - that gameplay programmers, and even designers, can use to quickly prototype things in.

Also, having a nice art / asset pipeline that is easy to use and easy to get assets into the game.

Basically, remove obstacles to people doing their jobs and streamline their workflows.

Unfortunately, off the shelf solutions for those things don't really exist (even in popular game engines, these aren't all really solved problems), which means that you are going to have to invest some engineering time to get this agility. So, sadly, the answer is you have to spend time to make it so you can work quickly, which sort of defeats the purpose. Once you spend the time though, things go great. If you can re-use your work for future projects, the dividends are even better.

# Answer
> 3 votes
### Timeboxing means iterations don't get longer

You ask how to **shorten** iterations. But that implies they are taking more time, which implies you're not applying time boxing. In any iteration when complexity starts to weigh more (or you have other unforseen setbacks), you don't change iteration length. You instead *descope* the incremental addition you planned at the start of the iteration. Some iterative methods suggest doing this assessment at the middle of an iteration (before it's too late). Read more about what OpenUP suggests:

> **Manage objectives** When a team is falling significantly behind, or critical problems occur that prevent the team from meeting the iteration objectives, it may be necessary to descope work to ensure that the team delivers a useful product increment by the end of the iteration, while maximizing stakeholder value. Work with the team and stakeholders to revise the Iteration Plan and, as necessary, reduce the emphasis on less critical tasks by postponing them to a subsequent iteration. In rare cases, if the iteration objectives still seem impossible to meet, the team might consider terminating the iteration or reformulating the iteration to a new objective.

If you look at the first chart you can see that added value is less at later iterations. This means iterations still take as long as before, but maybe there's less new functionality (relatively) within each iteration.

As you say, iterative's strength is to reduce risk by getting feedback frequently. It sounds like you're talking about *project complexity* dogging you down on the later iterations? I don't agree this is a weakness of iterative. It's a weakness of badly managed complexity.

Theoretically, you put the projects biggest risks up front. This means you have a very unstable project, but as you manage the big risks, it is *supposed to* stabilize. Complexity, of course, is one of the risks.

Scripting languages and automated processes help reduce the risk of complexity, which can be called "accidental" complexity (and is discussed in another answer). Highly iterative yet complex projects (Chromium is a good example, even if it's not a game) have lots of infrastructure to manage complexity. Take a look at https://www.chromium.org/developers for lots of examples of things like coding advice to the BuildBot.

What this figure doesn't show is the project stability, which probably looks something like this:

Until the technical risks are well understood, you're dealing with simple prototypes

---
Tags: design-patterns, development-speed
---


# Question
Title: Unity UI vanishes when the camera Z exceeds 1000
We are developing 3D racing game. After the player's position in Z axis reaches 1000, our Canvas UI is hidden and reset. If I unparent it from Character controller, it still gets auto reset but not hidden. If I drag player back to \< 1000, it again shows my UI.

Any suggestions why this may be happening?

# Answer
> 1 votes
Problem was solved after changing Render mode of canvas to Screen Space - camera from Screen Space - Overlay

---
Tags: unity
---


# Question
Title: player does not collide with walls unity 5
I just started a new proyect with a personalize first person controller, like arrow move style, it worked, but when I tryed to collide it with walls it did not happen, I tryed adding a capsule, then adding the camera, rigidbody, character controller and my script to that capsule , then if you can see there are two walls one with box collider trigger the other one unchecked, it walks around but it does not collide at all, i'll add my controller script + scereenshot, thanks for you time

```
#pragma strict

public var speed = 100.5;

function Update () {
//rotate
var horizontalDir = parseFloat(Input.GetAxis("Horizontal") * speed * Time.deltaTime);
transform.Rotate(0, horizontalDir, 0);

//move backward and foreward
var verticalDir = parseFloat(Input.GetAxis("Vertical") * (speed / 10) * Time.deltaTime);
transform.Translate(0,0, verticalDir);
}

```

# Answer
we update the script as follows

```
#pragma strict

var walkSpeed = 150;
var rotateSpeed = 100;
var jumpSpeed : float = 8.0;
var gravity : float = 20.0;

private var moveDirection : Vector3 = Vector3.zero;

function Update () {
var controller : CharacterController = GetComponent.<CharacterController>();

if (controller.isGrounded) {
    // We are grounded, so recalculate
    // move direction directly from axes
    moveDirection = Vector3(0, 0, Input.GetAxis("Vertical"));
    moveDirection = transform.TransformDirection(moveDirection);
    moveDirection *= walkSpeed * Time.deltaTime;

    //also with jump ;)
    if (Input.GetButton ("Jump")) {
        moveDirection.y = jumpSpeed;
    }
}

// Apply gravity
moveDirection.y -= gravity * Time.deltaTime;

// Move the controller
controller.Move(moveDirection * Time.deltaTime);

// rotate controller
var horizontalDir = parseFloat(Input.GetAxis("Horizontal") * rotateSpeed * Time.deltaTime);
transform.Rotate(0, horizontalDir, 0);
}

```
> 0 votes

# Answer
Translating the Transform component directly doesn't not apply collision detection. You'll want to use Move() on the CharacterController.
> 1 votes

---
Tags: unity, unityscript
---


# Question
Title: How to setup animation based events without depending on an animation?
How can I have events based off animations without relying on them? Take for example reloading in a FPS game. You'd hit a button to reload your weapon, the animation will play, then animation will hit a certain frame, then the weapon will be reloaded. There's a dependency on the animation eventually hitting that key frame before the weapon can reload and the character can go into another state. Without the animation, the weapon would never reload, and without some arbitrary timeout, the character would be stuck in that state forever.

Checking for the existence of an animation is an option. However, this requires us to still know about some sort of animation, and what it's playing. Am I over engineering this? Would it be okay for the logic of some object to have some information about it's animations?

# Answer
> 2 votes
Introduce a new abstraction: `Action`

An `Action` represents *something* that can be done, and encompassed the time aspect as well as information about the state and state transitions of the action. So a reload action definition might contain information about total duration, relative timestamp of reload complete etc. A spear throw action definition contains information about total duration and timestamp of spear release.

Exactly how you wrap this up in code is up to you and depends on your framework/style. `Actions` could be simple data objects which you just use to define different actions, and then you make use of the timestamps, durations and other information "manually" in the rest of your code. Or you could improve encapsulation by having your `Action` module expose events which trigger when the action changes state (OnReloadStarted,OnReloadReady,OnReloadFinished,OnSpearThrown). Or you could have a medium where there are no events, but the `Action` still manages its states/transitions so that you can poll it: `throwSpearAction.isSpearThrown()`.

If you have multiple reload animations or spear-throw animations with different timings, then you define each alternative as an action, e.g. FastThrowAction and SlowThrowAction. Once again it is up to you exactly how you manage and pick from different alternatives.

The point of all this is that the `Action` abstraction becomes a natural part of the gameplay model when you focus on the concepts that affect gameplay (action transitions/events) and remove the concepts that don't (animation).

These `Action` objects can then be used to drive the animation as well. Whenever a FastThrowAction is started, then your renderer/view starts the corresponding FastThrowAnimation.

# Answer
> 0 votes
All animations are more-or-less based on the idea of "keyframes", whereby you define two or more states/poses/transforms and the length of time between them; when 50% of the animations' total time has passed, the animation is 50% complete. Animations like "reload" have fixed time-costs based on the character, weapon, being suppressed, etc..

Your `InputHandler` will need to ignore invalid input until the `Reloading` state expires (not when the animation is finished).

During that time, the animation **may** also progress, smoothly, from 0% to 100%. When the player presses "R", the current time is recorded. If the computer, then, lags out for X+1 seconds, the entire animation will happen "instantly", when the computer catches back up; the `InputHandler` would also detect the (instant) expiration of the reload state and clear it.

Basically, the game continues playing with, or without, acceptable animations:

1. Player presses "R"
2. Set the player's `Reloading` flag (disable reload-incompatible inputs)
3. `ReloadTime` or `ExpiryTime` is recorded (100% reload after 3.2 seconds)
4. `Update()` and `Render()` for 3.1999 seconds...
If using `ReloadTime`, subtract delta-time from it, every Update().
(Could be one 3.1999-second update or one-hundred 0.031999-second updates)
5. During the next `Update()`,
`ReloadTime` will be \<=0, or
`ExpiryTime` will be a time in the past
6. If so, clear the player's `Reloading` flag (enable reload-incompatible inputs).
The animation **is** done (not a question).

---
Tags: architecture, animation
---


# Question
Title: Leading Zero's in int returning weird number c++
I'm doing UTs on a class of mine, and I tried the edge case of putting 05421 in the ctor instead of 5421.

As far as I know, putting a leading zero in an integer results an octal number, but seeing as iy returns 2833 as the number, it's not octal.

Anyone knows what's going on behind the scenes here?

# Answer
> 2 votes
Starting a literal number (that is, a number written down in your source code) with a zero does indeed mean it will be interpreted as an octal number.

However, this does not carry any further than the interpretation of that one number. It does not store a flag next to the variable saying "This number was once octal, represent it as such", it just goes "Hey! A number, I can represent this." and shows the base-10 representation of that number.

Your IDE may have an option to show its numbers in different bases, I know visual studio has the option to show numbers in base 16 (hexadecimal).

And note, as congusbonugs said: `2833 == 05421` (1 + 2\*8 + 4\*8\*8 + 5\*8\*8\*8 = 2833)

---
Tags: c++
---


# Question
Title: How can I get complete path of a sprite?
I want to get a path of sprite using the spriteRenderer component in Unity.I want my path should be like - "asset/PATH OF MY FILE/FILENAME.EXTENSION". Currently I am using following code but it returns only parent name/path.

```
string GetSpritePath(Transform goPath){
    List<string> path = new List<string> ();

    Transform current = goPath.transform;
    path.Add(current.name);

    while (current.parent != null) {
        path.Insert(0, current.parent.name);
        current = current.parent;
    }

    return string.Join("/", path.ToArray());
}

```

Whats wrong with my code ?

# Answer
> 1 votes
Don't try to reinvent the wheel; the first thing you should do is to try find existing functionality and read the documentation. In your case you should use:

```
var path = AssetDatabase.GetAssetPath(this.renderer.sprite);

```

And your resources must be in the Assets directory. That is all.

Please see related documentation:

http://docs.unity3d.com/ScriptReference/AssetDatabase.GetAssetPath.html

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


# Question
Title: Computing Normals for a displaced material
*Disclosure: cross-posted on Unreal Answers, thought was sufficiently general for GameDev.SE*

I am currently rendering a displacement texture and, separately, a normal texture for my ocean. Is there a clever way where I can actually just compute the normal in the final material. I.E. the un-displaced normal is (0, 0, 1) then by using perhaps ddx/ddy work out the real normal? It seems like this question is trying a similar thing. I don't really understand the ddx/ddy nodes/functions but they seem at least related.

Using the ddx, ddy nodes what I tried was computing for each given point:

```
dx = ddx(WorldPosition.x)
dy = ddy(WorldPosition.y)
dz/dx = ddx(height) / dx
dz/dy = ddy(height) / dy

```

Then I used these values to rotate my base normal of (0, 0, 1) to the final normal. It kinda looks like I'm on the right track but I not 100% calculation at a couple of points. Further, it isn't quite right as the normal appears to change as I move the camera around (using the world normal buffer visualisation).

**Calculation:**

```
let Tan(theta) = dz / dx
let Tan(phi) = dz / dy

```

Then plugging these values into the rotation matrix R\_theta, R\_phi:

\\$R\_\theta=\begin{pmatrix} 1 & 0 & 0 \\ 0 & cos(\theta) & -sin(\theta) \\ 0 & sin(\theta) & cos(\theta) \\ \end{pmatrix} R\_\phi=\begin{pmatrix} cos(\phi) & 0 & sin(\phi) \\ 0 & 1 & 0 \\ -sin(\phi) & 0 & cos(\phi) \\ \end{pmatrix}\\$

I compute theta and phi by applying atan to dz/dx and dz/dy respectively.
Finally multiplying R\_thea * R\_phi * n to get:

```
sin(phi)
-sin(theta)cos(phi)
cos(theta)cos(phi)

```

Is what I am trying to do possible and what am I doing wrong? Specifically:

* Am I using the ddx, ddy nodes correctly to compute the change in height over x and y
* How come the normal appears to change as I move the camera
* Does the fact there is horizontal displacement in my ocean matter

# Answer
As usual was some what over-thinking the problem. I don't need to use the screen space normals (which is what I would have got with the ddx/ddy nodes) and can instead just compute a pair of tangents and cross them for the world space normal.

To do this I did the following:

For each point, using a small margin in UV space units (e.g if you have a 512x512 texture for the displacement, 1/512 is approx one pixel above).

```
TopLeft = Texture[uv + (-small, -small)]
TopRight = Texture[uv + (small, -small)] + (2.0 * small * world unit converter, 0, 0)
BottomLeft = Texture[uv + (-small, small)] + (0, 2.0 * small * world unit converter, 0)

v1 = TopRight - TopLeft
v2 = BottomLeft - TopLeft

n = cross(v1, v2)

```

I.E. the top right point is the world space position after going along the small distance and then transforming by the displacement stored in the texture. This then gives you two roughly tangential vectors, so crossing is roughly the normal.
> 0 votes

---
Tags: mathematics, rendering, normals, unreal-4
---


title: Rotate an objects velocity

text:
# Question
Title: Rotate an objects velocity
I have a collision system (in 3D but for the purpose of the question assume 2D) where I want to calculate the new velocity (stored as a vector) after a collision.

What I have is the velocity of the object colliding against a plane and I want the object to then slide down that plane.

I know the angle of impact with the plane and I know the normal of the plane. I can create a Rotation Matrix for the rotation that the velocity needs to be changed by, I just am not sure how I rotate the velocity vector by that matrix.

I'm sure it's an easy answer but I haven't quite been able to get it.

I added a picture as requested

Any help would be appreciated.

# Answer
> 0 votes
You don't need to rotate the velocity at all.

Get the velocity **Magnitude**, get the new direction, bring the two together. The new direction is the hardest part. Probably you want it a perpendicular vector to the plane normal, but now you have infinite perpendicular vectors to the plane normal. The easiest answer may be get the one going down, since you just said you want to slide "down".

```
Vector3 Length() {
    return sqrt(x*x + y*y + z*z);
}
Vector3 Cross(Vector3 a, Vector3 b) {
    return new Vector3(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x);
}
float magnitude = oldVelocity.Length();
Vector3 newDirection = Vector3.Cross(plane.Normal, Vector3.left);
Vector3 newVelocity = newDirection * magnitude;

```

This should do.

But just in case you REALLY want to know how to transform a vector by a matrix, then just read this: http://blog.wolfire.com/2010/07/Linear-algebra-for-game-developers-part-3

---
Tags: mathematics, matrix, vector, transformation
---


# Question
Title: How to rotate an object along its trajectory path?
I have a missile launcher that uses initial velocity for the trajectory. I edit the launch angle from the editor, and then the script calculates the initial velocity required to land the missile to the target location. The inputs for the calculation are

* Launcher position
* Target position
* Firing angle

In this scenario, the target and the launcher position has the same Y coordinates. I simply instantiate the missile prefab and set its initial rotation to match the firing angle (initial X rotation), rotate it to face the target position (corrected Y rotation), calculate the initial velocity using local space (calculate the Y and Z component of initial velocity), and then set its velocity so the trajectory is handled by the physics engine.

```
// initial X rotation of the missile: -_firingAngle;
GameObject missile = Instantiate(_projectile, transform.position, Quaternion.Euler(-_firingAngle, 0f, 0f)) as GameObject;
missile.transform.LookAt(_targetPosition);  // fix the Y rotation of the missile
// ...
// velocity calculations
// ...

// launch the missile
missile.GetComponent<Rigidbody>().velocity = Local2GlobalVelocity;

```

The missile lands its target just fine, however, the X rotation of the projectile during the trajectory doesn't change.

This is how the missile prefab looks like:

---

I want the missile to be rotated by the physics engine, or put another way, I want it to look natural while in motion. As you may have noticed from the first image, I have visited numerous unity forums to solve the issue. I tried updating the rotation of the missile on each frame as follows

```
transform.rotation = Quaternion.LookRotation(rb.velocity);

```

However, this results in a funny trajectory -- imagine an erect missile tilted a little backward, and at the time of landing, the missile is tilted a little forward. I'm not sure why, but when I try to edit the X rotation of the missile mid air when I use the `LookRotation(rb.velocity)` while the game is paused, the Z value of the rotation also changes. Since the velocity is a `Vector3` with non-zero X,Y and Z components, I think the missile is subject to Gimbal Lock.

**What are my options to make it look like a trajectory of a badminton ball?**

Can I achieve this by adding rigidbodies to the parts that are at the top of the missile and adjust their mass so that the physics engine handles the trajectory rotation as it is a badminton ball, instead of me messing up with the rotation by scripting? If yes, how can I do that exactly?

# Answer
> However, this results in a funny trajectory -- imagine an erect missile tilted a little backward, and at the time of landing, the missile is tilted a little forward.

The answer lies here. Physics engine actually successfully simulates the trajectory rotation of the object in relation with its rigidbodies velocity when you use `LookRotation()` in the objects `Update()` function. The only issue here is the rotation of the prefab. If you rotate the prefab's first child (body, in your case) by 90 degrees on X axis, you'll achieve the natural missile trajectory look.
> 2 votes

---
Tags: unity, physics, rotation, trajectory
---


# Question
Title: Cram search results into viewport (of a search minimap)?
I'm no coder, nor do I try to be. I just had one of those "it's impossible" arguments with folks who love to argue with me before they even understand what the argument is about :)

So I need to know how doable it is and the level of complexity on scales of: Noob LVL to Mediocre to Never-got-laid mad coding skills.

Normally the way people do this is by scaling. But I don't need to preserve the position ratios between objects. What I want to do is = IF the view-port cannot fit all results BUT has space to fit them - juts get them in there (position ratios be damned).

Basically the way I want to do it is the way you would do it in a crowded bar table. Just cram it in. Obviously the other objects move if they are in the way - but if there is space - they fit. (for instance the top orange star has moved down because the blue star was crammed in from outside the view port.

What I'm looking for is an overview explanation about how someone would go about such a thing and how hard it is. I'm pretty sure there is math for that sort of thing - but it's not really an area where i shine... So you don't really need to get into complexities.

Q? Why don't I care about accurate position ratios and directions?

A: Objects in the view port are intractable on click. Representing them displaced from their true positioning is irrelevant so long as you get to interact with them via their functionalities.

# Answer
> 2 votes
There is of course several ways to do this, and the solutions are very much gamedev related.

One perspective on a solution comes from game physics. Basically you'd start by clamping all data to the rectangular window, letting the data overlap.

Next, you treat each star as having a minimum distance constraint from every other star, so you'd loop through all stars and if a star was too close to any other star you'd either push the star away, or have the two stars push away from each other a small amount.

You'd also want to enforce a constraint that the stars stay on the inside of the walls, and keep a minimum distance, to make sure they stayed in the box.

After one loop of this you may still have overlaps, so you'd repeat the process either until all constraints are met, or until you reached some number of maximum iterations since its possible you could have more stars than you have area for - or that a solution would take too long to converge to.

For highest quality results, you'd move the stars only a very small amount per loop, and you'd have a high maximum loop count. For fast results on the other hand, you'd move them larger amounts and have a lower maximum loop count.

This is 2d physics collision / response at its simplest (:

There is probably a non iterative way to solve this from the physics perspective, but it likely requires inverting a gigantic matrix.

Some other areas of game dev that might have other techniques for you include path finding, flocking behaviors and path planning. Its a common problem in pathing to try to get things from one place to another without overlapping since that means pathing entities get caught in doors etc. You might find some interesting algorithms if you look in that direction.

---
Tags: mathematics, architecture, javascript, software-engineering, path-finding
---


# Question
Title: Problem getting mouse events while keys held down in SDL2
I'm attempting to write input capturing code using SDL2 on Windows. However, I'm running into a problem.

Whenever a key is held down, the SDL event queue has no mouse movement, nor will the mouse move on my screen. Instead, The SDL event queue continually returns the key I am holding down as an SDL\_KEYDOWN event.

Here is a simple example program which reproduces the problem exactly:

```
#include <SDL2/SDL.h>
#include <iostream>

int main(int argc, char** argv) {
  SDL_Init(SDL_INIT_EVERYTHING);
  SDL_Window* window = SDL_CreateWindow("Moust Input Test", SDL_WINDOWPOS_UNDEFINED,
                                        SDL_WINDOWPOS_UNDEFINED, 640, 480,
                                        SDL_WINDOW_SHOWN);
  SDL_Event event;
  for(; ;) {
    while (SDL_PollEvent(&event)) {
      if (event.type == SDL_QUIT) {
        SDL_DestroyWindow(window);
        return 0;
      } else if (event.type == SDL_MOUSEMOTION) {
        int x, y;
        SDL_GetMouseState( &x, &y );
        std::cout << "Mouse moved to: " << x << " " << y << std::endl;
      } else if (event.type == SDL_KEYDOWN) {
        std::cout << "Code of key pressed: " << event.key.keysym.sym << std::endl;
      }
    }
  }
  return 0;
}

```

What I would expect to happen is that, when I hold down a key (for example, 'a'), it prints exactly once:

Code of key pressed: 97

And then, while they key is held down, if the mouse is moved, it prints every time the mouse is moved:

Mouse moved to: \[wherever\]

Instead, I'll keep seeing over and over again:

Code of key pressed: 97

And I will not get any mouse movement whatsoever on the screen, nor will I get my mouse movement log printed, until I release whatever keys I am holding down.

Anybody know how I can capture mouse movement while I have a key held down?

The only thing I can think of which could possibly be relevant is I am compiling with MinGW using:

```
g++ -Dmain=SDL_main test.cpp -o test.exe -L./lib/SDL2 -lmingw32 -lSDL2main -lSDL2 -mwindows -mconsole

```

Thanks.

Edit: I've also just noticed that the problem persists even when the window is minimized- if I am holding a key down in this text window while my program is minimized in another Window, the mouse stops working, though my program is not printing out the key code.

# Answer
> 2 votes
The problem might not be in SDL. You can try going to your trackpad's settings, look for something called "palm sensitivity" or "palm-something" and reduce it to zero.

My trackpad momentarily turned off whenever I pressed a key, because of my PalmCheck settings. I reduced my PalmCheck sensitivity to zero and could freely register key presses and mouse motion events at the same time.

My solution was to go to Control Panel \> Mouse \> Device Setings \> Settings \> Pointing \> PalmCheck, then move the slider to zero. Of course, this is specific to my laptop, but anyone having this problem might be because their "palm-something sensitivity" is too high, and the laptop disables the mouse to prevent movement while typing. Set it to zero, and it might help.

# Answer
> 1 votes
SDL2 is intended to deliver all these events, not to block one while another is active.

SDL2 does deliver keyboard repeats. I use almost the same code, and I see repeated keys, but also mouse movement events interspersed.

You could filter out keyboard repeats by doing

```
  } else if (event.type == SDL_KEYDOWN) {
    if(event.key.repeat == 0) {
      std::cout << "Code of key pressed: " << event.key.keysym.sym << std::endl;
    }
  }

```

Maybe this helps...

# Answer
> 1 votes
I use this code below to limit the amount of times I run my Mouse calculations...

You could use something like this, and When KEY IS PRESSED , Make a bool KEYPRESS = true if (keypress == false){ do the key down event } When KEY IS UP, KEYPRESS = false;

See where I am headed with this?

if (e.type == SDL\_MOUSEMOTION){

```
            if (frameBuffer > 10){
                std::cout << "Mouse Relative to SCREEN CENTER RelativeX = " << Mouse1.getMousePosX(Engine.getScreenW()) << "\n" <<
                    "               RelativeY = " << Mouse1.getMousePosY(Engine.getScreenH()) << "\n";
                std::cout << "Current Mouse Angle Relative to Center is : " << mouseAngle << "\n\n";
                std::cout << "Mouse Handle Count : " << mouseHandleCount << "\n\n";
                mouseHandleCount++;
                frameBuffer = 0;
            }
            frameBuffer++;

```

---
Tags: sdl, input, windows, mouse, sdl2
---


title: Fade between scenes

text:
# Question
Title: Fade between scenes
So I have googled how to do this already but all the answers were for older versions of unity and use things that are not applicable anymore.

I am trying to do is fade the screen to white when the player wins, followed by a change to another level that will have a video playing.

How do I do this in Unity 5 (preferably in C#)?

# Answer
You can use the UI Canvas. Add a panel to the canvas and set the color to your preference. After you get that set up you could animate that panel to do anything from changing colors to custom sliding effects ect...

To implement something like this you would want

```
      Animator anim;
     //in Awake()
      anim = GetComponent <Animator> ();

     // Tell the animator that the player Won.
      anim.SetTrigger ("Win");
     //then after the Win animation is finished trigger a Application.LoadLevel("yournextscene");

```
> 3 votes

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


# Question
Title: Efficient way to store information about neighbour chunks
I've finally managed to implement an infinite chunk loading system for my voxel engine. Since every chunk needs to have information about the border of the neighbouring chunks, I need to access them fast. First some information about how I'm storing the voxel data: I have an Integer array of block information on each chunk (rather than byte because of the read/write access speed), which is stored in an Dictionary(Vector3i chunkPos, Chunk chunk). When building a chunk I have to access the voxel data of the chunk and of the neighbouring chunks several times.

Without information about their neighbours it currently looks like this:

So I've tried the following two things:

1. getting the chunk data every time like this:

```
public static int getBlockAt(int x, int y, int z) {
    Vector3i chunkIndex = new Vector3i(
        x >> ChunkManager.logChunkSize,
        y >> ChunkManager.logChunkSize,
        z >> ChunkManager.logChunkSize
    );

    if (chunkManager.chunkData.ContainsKey(chunkIndex)) {
        return chunkManager.chunkData[chunkIndex].data[x & ChunkManager.chunkMask, y & ChunkManager.chunkMask, z & ChunkManager.chunkMask]} return 0;

```
2. storing chunkSize + 2 information on each chunk, which makes editing much, much slower, but improves chunk loading alot

In general I want to implement something like using approach 1 only when the block data isn't on the chunk.

I really don't know how I could do it! Do you have an idea, or experience from writing voxel engines?

Thanks in advance!

# Answer
I'm also building a voxel like game, and this is how I do it.

I store a list of Chunks in an array. Each chunk have a position, and an short array of voxel materials.

Heres my local chunk get and set methods:

```
public short getBlock(byte x, byte y, byte z) {
    return blocks[y+(x*16)+(z*256)];
}

public void setBlock(byte x, byte y, byte z, short id) {
    blocks[y+(x*16)+(z*256)] = id;
}

```

To get/set globally you will just get the chunk position, and then call the local methods for the certain chunk.

Hope this inspired you, and sorry for not providing you a more detailed answer.
> 1 votes

---
Tags: unity, voxels, data
---


# Question
Title: How can I find the object closest to a given 2D point?
I have an array of objects. Their position is a `Vector2`. I want to select the closest object, given an X and Y coordinate that represents an user touch on screen.

How can I do this?

# Answer
> 2 votes
There isn't any libGDX function for this particular problem, but it should be something like:

```
Vector2 closestToFinger(Vector2[] vectorsArray, Vector2 touchPosition)
{
    float shortestDist = 0;
    Vector2 closestVector = null;
    for(point in vectorsArray){
        float dst2 = touchPosition.dst2(point);
        if(closesVector == null || dst2 < shortestDist){
            shortestDist = dst2;
            closestVector = point;
        }
    }
    return closestVector;
}

```

Also, when iterating through your array, using the `dst2()` function rather than `dst()` will improve performance because it doesn't need to calculate a square root.

---
Tags: algorithm, spatial-partitioning
---


# Question
Title: Swift - Why does my SKShapeNode pass through an object, pausing briefly beforehand?
The code below when run on a device that’s flat on the table shows a red circle (the 'ball') and a line.

When I gently tip the device the circle moves towards the line. When it reaches the line, it stops which is the expected and desired behaviour.

BUT if I keep tipping, the circle moves *through* the line. I’ve been trying for 2 days to work out why grrr I just want the circle to hit the line and **not** go through it.

Any ideas? Anything to do with the line being an 'edge'?

Cheers, Andy

```
import SpriteKit
import CoreMotion

class GameScene: SKScene, SKPhysicsContactDelegate {
    var ball : SKShapeNode!
    var line : SKShapeNode!
    var motionManager = CMMotionManager()
    var destX : CGFloat!
    var destY : CGFloat!
    let ballRadius = CGFloat(20.0)

override func didMoveToView(view: SKView) {
    backgroundColor = SKColor.whiteColor()
    physicsWorld.gravity = CGVector(dx: 0, dy: 0)
    physicsWorld.contactDelegate = self

    ball = SKShapeNode(circleOfRadius: ballRadius)
    ball.fillColor = UIColor.redColor()

    ball.position = CGPoint(x: frame.size.width/4, y: frame.size.height / 2)
    destX = frame.size.width/4
    destY = frame.size.height / 2
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ballRadius)
    addChild(ball)

    line = SKShapeNode()
    var lineStart = CGPoint(x: frame.size.width/2, y: 0)
    var lineEnd = CGPoint(x: frame.size.width/2, y: frame.size.height)
    var linePoints = [lineStart, lineEnd]
    var linePos : CGMutablePathRef = CGPathCreateMutable()
    CGPathAddLines(linePos, nil, linePoints, 2)
    line.path = linePos
    line.strokeColor = UIColor.blackColor()
    line.physicsBody = SKPhysicsBody(edgeFromPoint: lineStart, toPoint: lineEnd)
    addChild(line)
}

override func update(currentTime: NSTimeInterval) {
    moveBall()
}

func moveBall() {
    motionManager.startAccelerometerUpdatesToQueue(
    NSOperationQueue.currentQueue(), withHandler: {
        data, error in
        var currentX = self.ball.position.x
        var currentY = self.ball.position.y
        self.destY = currentY - CGFloat(data.acceleration.x * 100)
        self.destX = currentX + CGFloat(data.acceleration.y * 100)
        }
    )
    ball.position = CGPoint(x: destX, y: destY)
    }
}

import UIKit
import SpriteKit

class GameViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    let skView = self.view as! SKView
    let scene = GameScene(size: CGSizeMake(
    skView.bounds.size.width, skView.bounds.size.height))
    skView.showsFPS = true
    skView.showsNodeCount = true
    skView.ignoresSiblingOrder = true
    scene.scaleMode = .AspectFill
    skView.presentScene(scene)
}

override func prefersStatusBarHidden() -> Bool {
    return true
}
}

```

EDIT: many thanks to Attackfarm :)

I changed the moveBall() function as follows:

```
func moveBall() {
    motionManager.startAccelerometerUpdatesToQueue(
        NSOperationQueue.currentQueue(), withHandler: {
            data, error in
                self.ball.physicsBody!.applyForce(CGVector(dx: -data.acceleration.x*100,
                        dy: data.acceleration.y*100))
        }
    )

```

which in this proof of concept demonstrates what I needed. Thanks again!

# Answer
> 2 votes
You are not applying a force or a velocity to the ball. Rather, you're simply changing the position. If the tilt is small, it doesn't move much, and is thus stopped by the physics simulation. If the tilt is large, you're setting a position past the edge, thus the physics simulation does not even concern itself with the collision since the ball "teleports".

To solve this, simply apply the tilt as a force acting upon the physics body rather than a change directly to position.

---
Tags: collision-detection, ios
---


title: 2d canvas representation in c++ code

text:
# Question
Title: 2d canvas representation in c++ code
I would like to create a basic 2d graphics program to do very simple editing of in game assets.

My question, starting out how could I represent the canvas?

Let's say I know i'll need a canvas 512x512 pixels in siz, each pixel can be up to 256 colors. I can design a pixel as a struct with x,y,z coordinate and the canvas will be a 2d array or something that will hold each of those pixels.

That's a very basic way to model the drawing area, next how do I actually make that view so if I say put red at position 100x100 on my array it'll show up on screen?

Thanks in advance.

# Answer
> 1 votes
I would understand a level/map editor but use one of the many available image/photo editing software to create/modify your assets is better (IMHO). Also it will save you time, as image editors are full and complex projects in themselves and develop one, with serious and useful features, will take as many effort and time as the game itself. My advice is not to impose yourself such a workload.

GIMP is a good and free tool for that.

You have also paint.net

To support the loading of the assets in the game, BMP and GIF formats are not a challenge. BMP specs from Wikipedia are enough to support the most common, if not all, the variations of the BMP headers that the tools you decide to use will generate. There are libraries to save development time if you prefer. You probably don't need GIF.

PNG, and you probably want it, are a bit more complex. I recommend a library.

JPEG, maybe you don't need it but it will be nice to support, will surely be a challenge so use a library.

This library support all those formats: http://freeimage.sourceforge.net/

---

You can model a Canvas interface to encapsulate a pixel buffer in RAM or a DirectDraw Surface. Here an idea:

```
// Declare functions as virtual or abstract if
// you want only an interface to derive various implementations
class Canvas
{
    public:
    void moveTo (int x, int y);
    void lineTo (int x, int y);
    void draw (int x, int x, Image* src);
    void draw (int src_x, int src_y, int dst_x, int dst_y, Canvas* src);
    void draw (int src_x, int src_y, int dst_x, int dst_y, Image* src);
    void* lock (); // Give direct access to pixels
    void unlock ();
    PixelFormat* getPixelFormat (); // you need this info if you use lock()
};

```

Even if you decide to follow my advice on not to use time in developing an own image editor, you may still find value in a Canvas API, you can use it in your game engine, for example, not only in an image editor.

---

How can you represent the Canvas pixels?

If using a DirectDraw Surface, or its equivalent in other APIs, you will use the DirectDraw functions to create the surface, and to present them to visible portion of the screen. You will have to pin some tabs in your web browsers containing the DirectDraw documentation.

You can create the surface in the Canvas constructor or pass a pointer to a surface in one of the Canvas constructors.

Some functionality, like drawing lines, you will have to implement yourself. Usually, this involves to lock on the surface, then access the pixels to apply your line drawing algorithm of choice, then unlock the surface.

If using a pixel buffer in RAM, for a software renderer, just create a char array in the canvas constructor or pass a pointer to an already created one.

Tip: as many APIs out there do, do not use multidimensional arrays, it is better to use a single dimensional array where all pixels are contiguous in memory, maybe with padding at the end of each scanline. If you want the commodity of a multidimensional array, you can add, to your Canvas interface, a function like this:

```
// will return a multidimensional array
// of pointers to the first pixel of each scanline
void** getScanLines ();

```

By using the same pixel representation that the potential APIs with those your game engine will have to interact you save having to do expensive format conversions later.

---

To create and present surfaces using old DirectDraw API: http://www.codeproject.com/Articles/2370/Introduction-to-DirectDraw-and-Surface-Blitting

Note: old DirectDraw code tend to fail in modern platforms due to headers change. Don't panic, just search each error and you will probably find a solution, usually involving changing an #include or add a define in your project compiler parameters.

Alternatively, on modern Windows OSes, you can use Direct2D: https://msdn.microsoft.com/en-us/library/windows/desktop/dd370990%28v=vs.85%29.aspx

To draw a bitmap in memory using old OpenGL fixed pipeline (everything else, like drawing lines, you will do by software using your Canvas interface): http://www.glprogramming.com/red/chapter08.html

2D Sprites with OpenGL, better than previous approach, hardware accelerated: http://www.gamedev.net/page/resources/\_/technical/opengl/rendering-efficient-2d-sprites-in-opengl-using-r2429

To create a drawable area in a window using GDI and draw a bitmap into it: http://www.winprog.org/tutorial/bitmaps.html

Line drawing algorithm: http://en.wikipedia.org/wiki/Line\_drawing\_algorithm

Blit/Draw algorithm: just copy the pixels to the correct place, doing format conversion if needed. Tip: avoid format conversion by converting your assets to your current screen pixel format when loading them, this is specially needed if you develop a software renderer to improve performance of the game.

Blit/Draw algorithm with scaling: if using OpenGL or Direct3D this is very easy to do. Take as an example the link on 2D Sprites with OpenGL. You will have the GPU doing everything for you. If done by software, it will be probably very slow, offer "nearest-neighbor" as an option to allow the game to run in slower hardware.

---

Why 256 (probably indexed) colors?

The GIMP can create and edit (and convert to other formats) such images.

You may decide to store sprites like 256 colors, 1 Byte per pixel, bitmaps to save storage, but that does not mean you need to work with them during game execution. Just get a library that understand the format and load them and apply any required pixel format conversion to get the same format as the current screen configuration. Having the assets in that format does not imply that you are forced to leave them as they are once loaded.

---
Tags: c++, map-editor, editors, world-editor, unity
---


# Question
Title: Do I need to install any libraries or SDKs to use OpenGL?
I am wondering if I have to install libraries for openGL programming or if I can already use header files from the core library. I am asking this because I went to the SDK and there is no Core library for OpenGL development. There is however a few libraries to choose from. I am new to this.. If you could please help clarify the subject for me that would be great.

# Answer
Yes, you will need a library and headers to use OpenGL.

Fortunately, every major operating system ships with the libraries and headers already in place for you, so you do not need to download and install anything from the OpenGL website itself in most cases.

However, especially on Windows, you may want to download and install the latest drivers for your video card as they will generally improve the OpenGL functionality made available to you through the OS-supplied libraries.
> 4 votes

---
Tags: opengl
---


# Question
Title: In Pygame, I can only display text once I stop updating and drawing, why?
At this moment, I can only display text once I stop updating and drawing sprites. In the code below (which is actually the game loop), you can see how if `GAMEOVER == True` (gameloop stops drawing), the text "Game Over!" is displayed. But if I try to display any text while drawing and updating, it doesn't appears until I stop drawing the sprites. In fact, the frist block to display text ("My Game!") isn't shown, as I said, until the gameloop stops drawing. I need to display some info like, name of char, instructions, etc while the game is running, so, how can I render text in every loops and frames?

The game loop:

```
while True:

    myfont = pygame.font.SysFont("monospace", 30)
    label = myfont.render("My Game!", 1, (255, 255, 0))
    SCREEN.blit(label, (500, 400))

    if PLAYER.healthBase <= 0:
        GAMEOVER = True #True para que se acabe la partida

    if not GAMEOVER:
        charsGroup.update(time_passed)
        npcsGroup.update(time_passed)
        mapTilesGroup.draw(SCREEN)
        charsGroup.draw(SCREEN)
        npcsGroup.draw(SCREEN)
        drawBullets()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    time_passed = freq.tick(0) /1000.

    if GAMEOVER:
        myfont = pygame.font.SysFont("monospace", 30)
        label = myfont.render("GAME OVER!", 1, (255, 255, 0))
        SCREEN.blit(label, (400, 300))

    pygame.display.flip()

```

# Answer
> 0 votes
Are the sprites drawing over the text?

Text isn't a special thing, it's just another sprite you render to the screen (albeit one you generate in a special way).

If you render the text and then at the same position render a sprite you won't see the text because there is something in front of it.

Render the texts *after* rendering the sprites.

---
Tags: rendering, python, pygame, text
---


title: LWJGL Lighting advice / fix

text:
# Question
Title: LWJGL Lighting advice / fix
Problem: The spotlight I've set up with OpenGL won't light up anything behind it, no matter what values I set for GL\_SPOT\_DIRECTION

```
    float[] LightDir = new float[]{0,0,-1,0};
    float[] LightPos = new float[]{0,0,15f,1};

```

Initialization code for lighting

```
        glEnable(GL_LIGHTING);
        glEnable(GL_LIGHT0);
        glLightModel(GL_LIGHT_MODEL_AMBIENT,asFlippedFloatBuffer(new float[]{0.1f, 0.1f, 0.1f, 1f}));
        glLight(GL_LIGHT0,GL_DIFFUSE,asFlippedFloatBuffer(new float[]{0.5f, 0.5f, 0.5f, 1f}));
        glLight(GL_LIGHT0, GL_POSITION, asFlippedFloatBuffer(new float[]{0, 0, 0, 1}));
        glLightf(GL_LIGHT0,GL_SPOT_CUTOFF,60.0f);
        glLightf(GL_LIGHT0,GL_SPOT_EXPONENT,2.0f);

        glEnable(GL_COLOR_MATERIAL);
        glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
        glShadeModel(GL_SMOOTH);

```

Lighting code ran every loop

```
         glLight(GL_LIGHT0,GL_SPOT_DIRECTION,asFlippedFloatBuffer(LightDir));
         glLight(GL_LIGHT0,GL_POSITION,asFlippedFloatBuffer(LightPos));

```

The Following shows:

To try and change the direction I hit a key that does

```
LightDir[1]++;

```

The angle of the light goes up as expected, but seems to stop turning once it's pointed straight up. Which looks like

Which is the problem, it wont turn around. Iv'e tried every possible value for LightDir in all it's values, but I cannot get it to illuminate the back pf the tube. I've even tried to transform to light around the scene with glRotate and glTranslate. The light is supposed to function as a flashlight. Is this something that would be potentially solved with Shaders? Thanks in advance!

**EDIT:**

Anytime LightDir\[2\] goes above 0 the light goes dark.

# Answer
You're not actually rotating the light - at least not in the direction you think you are.

You said you're using `LightDir[1]++` to change the direction of the light. The direction starts as (0, 0, -1) - the negative Z direction (which appears to be towards the camera, in your program).

After you press the "rotate light" key a bunch of times, the light direction will be something like (0, 50, -1) - which is almost straight up (and not normalized).

In other words, it's not "no matter what values I set for GL\_SPOT\_DIRECTION" - *your program doesn't tell OpenGL* to make the light point backwards, only to make it point forwards and up. The direction (0, 0, 1) would be backwards.
> 2 votes

---
Tags: opengl, lighting, lwjgl
---


# Question
Title: Can we create same name class for different objects in unity?
I have four similar objects in my game. As they are all similar therefore I have created a single script that defines mash for all of them. The script that defines mash for these objects uses a variable called `radius` which I have imported from other file (by `classname.radius`). The radius updates on every frame and it is the only property that is different for all objects.

To allow different radius for different objects, What I thought would work was, making four different classes of same name `classname`. Creating variable `radius` in all of them and giving them different values. Dragging first file to the first object, second file to second object and so on.. When executed, every time the script that generated mash considers `classname.radius` from the file which is dragged to that object. But that isn't working. What is wrong and how can I implement it?

Seems I'm messing with OOPS concepts!

# Answer
You only need one class with one non static public member 'radius' (static variables wont work...)
Just create several instances of this class and connect them to correct meshes. You can have an empty gameObject to hold those instances, then drag and drag them to connect them to your other script on your meshes.

There are other ways to implement this though, but all require you to create class instances...
> 1 votes

# Answer
> The script that defines mash for these objects uses a variable called radius which I have imported from other file (by `classname.radius`).

So this means your variable `radius` is static? But since you want it to be different for every instance of your object, why do you have it as a static variable? Why not just make the variable not tied to the class, but to the instance of the class.
> 0 votes

---
Tags: unity
---


# Question
Title: Minecraft Bukkit Rename world and use in Java Plugin
I run a Minecraft server (Bukkit 1.7.9) and would like to have a second overworld-like world, into which I can teleport players from my plugin. I did some testing with the "world" folder:

* tried to simply rename the folder, but then a new world is generated on server start (into folder "world")
* moved another world with different folder name into the server directory (in addition the original world folder)
* tried to change the "level-name" value in server.properties but that does just generate new nether and end folders containing the new name

But in all cases the additional world is not listed when

```
Bukkit.getWorlds()

```

is called from the plugin (of course I restarted the server after adding the world). So now the question is how do I properly rename a world? I was not able to find something via a search engine nor could I find a file in the world folder that contains the world's name to change it there.

I know that I could use Multiverse or a similar plugin to do what I want but I hope that there is an easier way (like the one i tried).

I hope you can understand everything, sorry that it's not the best English but I'm not a native speaker ^^ . If I missed to tell you something you need to know please ask :) If anything else is wrong with this post please tell me as this is my first question posted here. Any idea or help is appreciated!

# Answer
> 0 votes
I actually solved it! I luckily found another question some minutes ago, and someone answered that you have to load the world first:

```
WorldCreator creator = new WorldCreator( "worldname" );
World w = creator.createWorld();

```

(That does not overwrite the world if a folder with name "worldname" exists but rather loads it and so you can see it in the list returned by Bukkit.getWorlds() and use it like any other world)

Then you can create a Location instance with that world.

I hope that helps other people, too!

---
Tags: bukkit
---


# Question
Title: 1D Simplex Noise Returns Same Generation
I've been using 1D Simplex Noise to create a random world surface, and it keeps generating with the same looking surface terrain, with some minor variations. Here is my sample code-

```
Tile[][] tiles = new Tile[rows][];
for (int i = 0; i < rows; i++)
{
    tiles[i] = new Tile[cols];
    for (int x = 0; x < cols; x++)
    {
        tiles[i][x] = new Tile(0, new Vector2(x, i), scale);
    }
}

int left = Main.rand.Next(rows / 4, rows / 2);

double seed = Main.rand.NextDouble();
for (int i = 0; i < cols; i++)
{
    int height = left + (int)(Noise.Generate((float)seed) * 10);
    height = (int)MathHelper.Clamp(height, 0, rows - 1);
    tiles[height][i] = new Tile(2, new Vector2(i, height), scale);
    //FillLower just fills everything under the top tile
    FillLower(tiles, height, i, scale);
    seed += .05f;
}

```

My question is am I doing something wrong with the Simplex Noise method? How should I generate it so it'll look different?

Images for reference- http://imgur.com/I0g98z8,M61UBfb,tYPflb7

# Answer
> 1 votes
```
double seed = Main.rand.NextDouble();

```

give you a 0..1 double value

```
(float)seed) * 10

```

give you a 0..10 value

```
seed += .05f;

```

give a little delta.

Try

```
double seed = Main.rand.NextDouble() * 255.0; //or greater
...
int height = left + (int)(Noise.Generate((float)seed) );
...
seed += 1.0; //play with this increment

```

---
Tags: xna, c#, 2d, simplex-noise
---


# Question
Title: Getting position of finger along a screen
I'm trying to get a list of Vector2 position by tracking my finger and then tracing them with a prefab (Basically just gestures). I have appended an onGUI function to help print out the list of vectors.

However, the attached code does not work and only prints "System.collection.Generic.List'1\[UnityEngine.Vector2\] when my finger moves along the screen. I know I'm missing something; any help would be greatly appreciated.

```
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class line : MonoBehaviour
{

    List<Vector2> movePos = new List<Vector2>();
    private float lastFingerRelease;
    public String printer;

    void Start()
    {

    }

    void Update()
    {

        if (Input.touchCount > 0)
        {

            Touch touch = Input.GetTouch(0);

            if(touch.phase == TouchPhase.Began && Time.time - lastFingerRelease > 2)
            {

                printer = movePos.ToString();

                movePos.Clear();
            }

            else if (touch.phase == TouchPhase.Ended)
            {
                lastFingerRelease = Time.time;
            }

            movePos.Add(touch.position);
        }

    }

   void OnGUI()
    {
        GUI.Label(new Rect(0, 0, 1000, 1000), printer);
    }

}

```

# Answer
> 1 votes
Your question actually has nothing to do with its title, but here's the answer anyway:

`ToString` is a method of the `Object` class, which all classes inherit, but not all implement it. It seems List does not implement it, so the default behavior is to make a string with the just the name of the namespace and the class.

That's why you're seeing a `"System.collection.Generic.List'1[UnityEngine.Vector2]`. It shows you the namespace, name and type of the class.

If you really want to do something useful to print that list, try iterating over it and showing each of its items:

```
int i = 0;
foreach(Vector2 vec in movePos)
{
    v += "[" + (i++) + "] = " + vec.ToString() + ";\n";
}
printer = v;

```

this should give you something in the lines of:

> \[0\] = (0.00, 0.00, 0.00);
>
> \[1\] = (0.11, 0.00, 0.00);
>
> \[2\] = (0.25, 0.10, 0.00);
>
> \[3\] = (0.30, 0.20, 0.10);

---
Tags: c#, unity, android, gestures
---


title: WebGL half float equivelant?

text:
# Question
Title: WebGL half float equivelant?
I'm trying to find a `half float` for the purposes of doing math in a fragment shader, not trying to have a half float texture.

Is there an equivalent of the `half float` data type in WebGL?
I know you can create a `lowp` float, but is that the same, or not necessarily?

# Answer
`lowp` is the same as a `half float`. But why does it matter that much? Are you really needing this kind of optimization right now? I'd say just use plain `float` and think about this only when you check that this is a bottleneck for either performance or memory or bandwidth.
> 0 votes

---
Tags: glsl, webgl, floating-point
---


# Question
Title: convert deprecated opengl function to modern opengl (3.3)
i need help to convert the render function of IQM model (void renderiqm()) to modern OpenGL (without the deprecated functions like enableClientState(), etc).

The code of renderiqm() function is here:

https://github.com/lsalzman/iqm/blob/master/demo/gpu-demo.cpp

and these are the shaders:

Vertex Shaders:

```
"#version 120\n"
"#ifdef GL_ARB_uniform_buffer_object\n"
"  #extension GL_ARB_uniform_buffer_object : enable\n"
"  layout(std140) uniform animdata\n"
"  {\n"
"     uniform mat3x4 bonemats[80];\n"
"  };\n"
"#else\n"
"  uniform mat3x4 bonemats[80];\n"
"#endif\n"
"attribute vec4 vweights;\n"
"attribute vec4 vbones;\n"
"attribute vec4 vtangent;\n"
"void main(void)\n"
"{\n"
"   mat3x4 m = bonemats[int(vbones.x)] * vweights.x;\n"
"   m += bonemats[int(vbones.y)] * vweights.y;\n"
"   m += bonemats[int(vbones.z)] * vweights.z;\n"
"   m += bonemats[int(vbones.w)] * vweights.w;\n"
"   vec4 mpos = vec4(gl_Vertex * m, gl_Vertex.w);\n"
"   gl_Position = gl_ModelViewProjectionMatrix * mpos;\n"
"   gl_TexCoord[0] = gl_MultiTexCoord0;\n"
"   mat3 madjtrans = mat3(cross(m[1].xyz, m[2].xyz), cross(m[2].xyz, m[0].xyz), cross(m[0].xyz, m[1].xyz));\n"
"   vec3 mnormal = gl_Normal * madjtrans;\n"
"   vec3 mtangent = vtangent.xyz * madjtrans; // tangent not used, just here as an example\n"
"   vec3 mbitangent = cross(mnormal, mtangent) * vtangent.w; // bitangent not used, just here as an example\n"
"   gl_FrontColor = gl_Color * (clamp(dot(normalize(gl_NormalMatrix * mnormal), gl_LightSource[0].position.xyz), 0.0, 1.0) * gl_LightSource[0].diffuse + gl_LightSource[0].ambient);\n"
"}\n",

```

Fragment Shader:

```
"uniform sampler2D tex;\n"
"void main(void)\n"
"{\n"
"   gl_FragColor = gl_Color * texture2D(tex, gl_TexCoord[0].xy);\n"
"}\n"

```

i tried to convert this to modern opengl (vbo, vao, shader version 330, etc), but i dont know which is the fail. Can you show me the correct form to convert it to modern opengl?

Im using opengl version 3.3 and here is my renderiqm() modified function :

```
void renderiqm(GLSLProgram& mainShader)
{
    m_matrix->loadIdentity();
    matrixTransformations();

    mainShader.sendUniform("modelYAxisDiff",getYAxisDiff());
    mainShader.sendUniform4x4("modelMatrix", m_matrix->getModelMatrix());
    //envía la matriz de normales
//  mainShader.sendUniform4x4("normalMatrix", m_matrix->getNormalMatrix());
    mainShader.sendUniform3x3("normalMatrix", glm::value_ptr(m_matrix->getNormalMatrix()));
    //envía la matriz de transformación  (modelview)
    mainShader.sendUniform4x4("modelViewMatrix", glm::value_ptr(m_matrix->getModelViewMatrix()));
    mainShader.sendUniform("objColor", m_color);

    m_matrix->pushMatrix(MODEL_MATRIX);

    glBindBuffer(GL_UNIFORM_BUFFER, ubo);
    glBufferData(GL_UNIFORM_BUFFER, ubosize, NULL, GL_STREAM_DRAW);
    glBufferSubData(GL_UNIFORM_BUFFER, bonematsoffset, numjoints*sizeof(Matrix3x4), outframe[0].a.v);
    glBindBuffer(GL_UNIFORM_BUFFER, 0);

    glBindBufferBase(GL_UNIFORM_BUFFER, 0, ubo);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);

    vertex *vert = NULL;

    GLsizei stride = sizeof(vert->position)+sizeof(vert->normal)+sizeof(vert->tangent)+sizeof(vert->texcoord);
    if(numframes > 0)
    {
        stride+= sizeof(vert->blendindex)+sizeof(vert->blendweight);
    }

    //vertices
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0,3, GL_FLOAT, GL_FALSE, stride, 0);

     //normales
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1,3,GL_FLOAT, GL_FALSE, stride, (void*)sizeof(vert->position));

    //tangente
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, stride, (void*)sizeof(vert->position)+sizeof(vert->normal));

    //texturas
    glEnableVertexAttribArray(3);
    glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, stride, (void*)sizeof(vert->position)+sizeof(vert->normal)+sizeof(vert->tangent));

    if(numframes > 0)
    {
        //blendweight
        glEnableVertexAttribArray(4);
        glVertexAttribPointer(4, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, (void*)sizeof(vert->position)+sizeof(vert->normal)+sizeof(vert->tangent)+sizeof(vert->texcoord));

        //blendindex
        glEnableVertexAttribArray(5);
        glVertexAttribPointer(5, 4, GL_UNSIGNED_BYTE, GL_FALSE, stride, (void*)sizeof(vert->position)+sizeof(vert->normal)+sizeof(vert->tangent)+sizeof(vert->texcoord)+sizeof(vert->blendindex));
    }

    iqmtriangle *tris = NULL;

    //DEBUG
    int i=0;
    for(i = 0; i < m_textureIndices.size(); i++)
    {

        iqmmesh &m = meshes[i];
        glBindTexture(GL_TEXTURE_2D, textures[i] ? textures[i] : notexture);
        tTextures[i].bindTexture(0);

        glDrawElements(GL_TRIANGLES, 3*m.num_triangles, GL_UNSIGNED_INT, &tris[m.first_triangle]);
    }

    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(2);
    glDisableVertexAttribArray(3);
    if(numframes > 0)
    {
        glDisableVertexAttribArray(4);
        glDisableVertexAttribArray(5);
    }

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    //glPopMatrix();
    m_matrix->popMatrix(MODEL_MATRIX);
}

```

**Clarification:** mainShader is a tested shader interface that works fine (no errors here) and m\_matrix is a GLM interface and also works fine.

the vertexShader would be this one:

```
string vAnimationShader = "\n\
#version 330                                                                \n\
                                                                            \n\
uniform mat4 projectionMatrix;                                              \n\
uniform mat4 modelViewMatrix;                                               \n\
uniform mat4 normalMatrix;                                                  \n\
uniform mat4 modelMatrix;                                                   \n\
uniform vec3 objColor;                                                      \n\
\n\
uniform mat4 DepthBiasMVP;                          \n\
smooth out vec4 ShadowCoord;\n\
\n\
smooth out vec2 texCoord;                                                   \n\
smooth out vec3 vNormal;                                                    \n\
smooth out vec3 vEyeSpacePos;                                               \n\
smooth out vec3 vWorldPos;                                                  \n\
smooth out vec3 vObjColor;                                                  \n\
\n\
layout (location = 0) in vec3 inPosition;                                   \n\
layout (location = 3) in vec2 inCoord;                                      \n\
layout (location = 1) in vec3 inNormal;                                     \n\
                                                                            \n\
uniform mat3x4 bonemats[80];\n\
\n\
layout (location = 4) in vec4 vweights;\n\
layout (location = 5) in vec4 vbones;\n\
layout (location = 2) in vec4 vtangent;\n\
void main(void)\n\
{\n\
    vObjColor = objColor;                                               \n\
   mat3x4 m = bonemats[int(vbones.x)] * vweights.x;\n\
   m += bonemats[int(vbones.y)] * vweights.y;\n\
  m += bonemats[int(vbones.z)] * vweights.z;\n\
   m += bonemats[int(vbones.w)] * vweights.w;\n\
    vec4 vEyeSpacePosVertex = modelViewMatrix*vec4(inPosition, 1.0);        \n\
    gl_Position = projectionMatrix*vEyeSpacePosVertex;                      \n\
   mat3 madjtrans = mat3(cross(m[1].xyz, m[2].xyz), cross(m[2].xyz, m[0].xyz), cross(m[0].xyz, m[1].xyz));\n\
   vec3 mnormal = inNormal * madjtrans;\n\
   vec3 mtangent = vtangent.xyz * madjtrans; // tangent not used, just here as an example\n\
   vec3 mbitangent = cross(mnormal, mtangent) * vtangent.w; // bitangent not used, just here as an example\n\
   texCoord = inCoord;      \n\
    vec4 vRes = normalMatrix*vec4(inNormal, 0.0);                           \n\
    vNormal = vRes.xyz;                                                     \n\
    vEyeSpacePos = vEyeSpacePosVertex.xyz;                                  \n\
    vec4 vWorldPosVertex = modelMatrix*vec4(inPosition, 1.0);               \n\
    vWorldPos = vWorldPosVertex.xyz;                                        \n\
    ShadowCoord = DepthBiasMVP * vWorldPosVertex;   \n\
}\n\
";

```

i didn't find the error... in the screen i dont see the iqm model.. all the other things draw perfectly, but iqm model doesn't appear.

**IMPORTANT DISCOVERING:**

recently, i have discovered that the problem occurs when the Opengl Context is 3.2+ . if I switch to the 3.1 Version of the opengl context , it works perfectly with my modified function.

i didn't find what the problem is... i associate that with a deprecated function but i cant findit. Please, can you help me? Thanks a lot.

# Answer
> 0 votes
Looks like you're not using Vertex Array Objects that are required by a modern OpenGL Core Profile context. It can be generated/used with calls `glGenVertexArrays` and `glBindVertexArray`.

# Answer
> 0 votes
The problem was the initialization of vbo without a vao (as say SurvivalMachine), i fixed it and now the model is rendering correctly.

---
Tags: opengl
---


# Question
Title: Collaborative Diffusion vs. A* for loose armies combat: any clear winner?
Collaborative Diffusion (CD) takes a lot of the work that A\* does and combines (writes) it cheaply for multiple agents to read cheaply. This is because the majority of CD's processing works via a simple CA / diffusion approach that produces a single shared map for every agent to use on a given game update. Agents then perform hill-climbing within that space, which is also very cheap.

The primary downside is that the data structure created by CD must apply for all agents; that is, each agent's subjective view of the environment is identical; A\* OTOH needs a path calculation per agent, each frame. In spite of this, the relatively low cost associated with CD would seem to make it, on average, a far more suitable approach than A\*, even when we must create unique views for agents (comments / experience on this are welcome).

**EDIT** Consider the following example using Collaborative Diffusion:

Two armies are on a battlefield, each army emitting a uniform scent. They charge (climb the scent gradient), and as the two lines clash, each agent takes on the first, closest enemy agent on the opposing line. This happens because on each approach step for each unit, it checks whether it's yet adjacent to an enemy; if so it locks on / attacks indiscriminately. This is much freer than specific targeting, which is where A\* would seem to be a better choice.

Am I correct in these assumptions? Are there other downsides to CD as opposed to \[insert your flavour of\] A\*, **for selecting ANY target between large groups**?

# Answer
> 2 votes
In the words of one Icefox here,

> Collaborative diffusion using agents and an anti-object is useful for when you are not trying to find a path from a specific node to another specific node.

...Confirming my suspicions as given in the question's example situation. The meaning being that when you need a member of one group to find *any* member of another group, ASAP (a battlefield is the perfect example) then Collaborative Diffusion is a good choice; OTOH for specific targeting, prefer A\*.

---
Tags: ai, performance
---