title: Multiple overlapping rectangles

text:
# Question
Title: Multiple overlapping rectangles
I have a collision method where the parameters for the method are the rectangle of the player and a list with the rectangles of the tiles.

I work with booleans like `bLeft`, `bRight`,... and this creates a problem if my player collides with two tiles at the same time, then one tile may say `True` while the other says `false`.

This is my collision method (NOTE: Very buggy and incomplete collision detection, this is because the reason above)

```
public override void Collision(Rectangle collisionRect, List<Rectangle> tileCollision)
{

    foreach (Rectangle rect in tileCollision)
    {
        if (collisionRect.Intersects(rect))
        {

            rect2 = Rectangle.Intersect(rect, collisionRect);

            collision = true;
            stopping = true;
            walking = false;

            if (collisionRect.X < rect.X && !(collisionRect.Y <= rect.Y - 50))
            {
                bLeft = true;
            }

            if (collisionRect.X > rect.X && !(collisionRect.Y <= rect.Y - 50))
            {
                bRight = true;
            }

            if (collisionRect.Y <= rect.Y - 50)
            {
                bUp = true;
            }

            if (collisionRect.Y >= rect.Y + rect.Height)
            {
                bDown = true;
            }

            if (bLeft && !bRight && !bUp && !bDown)
            {
                fallingTest = false;
                stopping = true;

                if (left)
                {
                    stopping = false;
                    fallingTest = false;
                }
            }

            if (bRight && !bLeft && !bUp && !bDown)
            {
                fallingTest = false;
                stopping = true;

                if (right)
                {
                    stopping = false;
                    fallingTest = false;
                }
            }

            if (bUp)
            {
                ground = true;
                fallingTest = true;
                stopping = false;

                if (moving)
                {
                    walking = true;
                }

                if (bLeft && bUp)
                {
                    stopping = true;

                    if (left)
                    {
                        stopping = false;
                    }
                }

                if (bRight)
                {
                    stopping = true;

                    if (right)
                    {
                        stopping = false;
                    }
                }
            }

            if (bDown && !bRight && !bLeft && !bUp)
            {
                stopping = true;
                fallingTest = false;

                if (moving)
                {
                    walking = true;
                }
            }
        }

        if (!(tileCollision.Any(c => collisionRect.Intersects(c))))
        {
            collision = false;
            fallingTest = false;
            stopping = false;

            ground = false;

            if (moving)
            {
                walking = true;
            }
        }
    }
}

```

So I basically need a line of code that counts the colliderboxes that the player collides with at the moment of collision. I tried doing this by adding 1 to the variable `collisionBoxes` but this results in doing +1 each frame (because this collision method is called in `Update`)

I also use `rect2` for visual overlapping of the player collision box and the tile collision box, but when the player touches more than one tile, then the rect2 only shows on one tile. This is because I use the `foreach` but I tried using a list to store the overlapping rectangles in but it didn't work.

One more question, should I use all these booleans? Because I don't know how to handle them if more than one block touches the player (all the tiles are checking for the booleans, resulting in bugs).

# Answer
I would make the change to deal with the collision itself outside the collision loop. Let each gameobject itself handle the collision result. Also if the object has been updated because a collision occurred, the collision rectangle might have been updated as well. Your current code is very foc

```
public void HandleCollisions(PlayerObj p, List<Tiles> tiles)
{
    foreach(Tile t in tiles)
    {
        if(p.CollisionRectangle.Intersects(t.CollisionRectangle))
        {
            p.HandleCollision(t);
            t.HandleCollision(p);
        }
    }
}

```

The player:

```
public void HandleCollision(Tile t)
{
    //Handle the collision.
    //Move the player out of collision position (stop falling etc.)
    //Update the collision rectangle.
}

```

Since you update the player after each collision, it will only handle collisions that are relevant. So if for example your player is falling down and is halfway two tiles, the collision with the first tile will move the player on top of the floor. The second collision will not happen.

Now the tile:

```
public void HandleCollision(PlayerObj p)
{
   // perhaps this tile is a lava tile?
   if(this.Type = Tiletype.Lava)
      p.DoDamage(10);
   // perhaps this is a breakable tile?
   if(this.Type = Tiletype.Breakable)
      this.Collapse();
}

```

In this example you can have side effects for each tile as well. This saves you from adding another bunch of tests/booleans elsewhere after the collisions.
> 0 votes

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


# Question
Title: Add navigation obstacles during runtime lags
Please watch this short video. http://screencast.com/t/vw2a5FdOOT It shows the problem.

It's using the build in Unity navigation and followed the guide to build the demo in the video.

Everytime I add a new obstacle than all agends pauses (hiccups) for a short time. I think this is because they have to recalculate a new path. How to make this recalculation in a background thread? I want to make a mace tower defense.

Thank you for reading an watching!

# Answer
Built-in navigation has lagging problems (more than lagging, actually), that's a known issue. I suggest you to use a better navigation solution.

This is, for example, pretty fast: http://arongranberg.com/astar/
> 1 votes

---
Tags: unity, performance, path-finding, navmesh
---


# Question
Title: Transformations are not correct using GLM and OpenGL
The aim of my program is to render a simple colored triangle in rotation. The rotations are correct if all Z values of my vertices are equals to 0.0f. If one of these values are different of 0.0f the transformations are not correct (if I retreat the camera, the triangle seems to be in the same place).

The following declaration works correctly :

```
static GLfloat vertices[9] =
{
   -1.000000f, 0.000000f, 0.000000f,
    0.000000f, 1.000000f, 0.000000f,
    1.000000f, 0.000000f, 0.000000f
};

```

But the following one not works correctly :

```
static GLfloat vertices[9] =
{
    -1.000000f, 1.000000f, 1.000000f,
    -1.000000f, 1.000000f, -1.000000f,
    -1.000000f, -1.000000f, -1.000000f
};

```

So if the polygon is coplanar with the plane (x0y) it's ok, but in the other case it's not correct. I searched to find the problem in my matrix usage in vain. Here's a part of my code :

//Main loop

```
while (continuer)
{
    eventListener(&event, &continuer);

    glClearDepth(1.0f);
    glClearColor(0.13f, 0.12f, 0.13f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(programID);

    //Projection matrix

    glm::mat4 projection = glm::perspective(70.0f, ((float)WIDTH)/(float)HEIGHT, 1.0f, 1000.0f);

    //View matrix

    glm::mat4 view = glm::lookAt(glm::vec3(0.0f, 0.0f, trans), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));

    //Model matrix

    glm::mat4 model = glm::mat4(1.0f);
    model *= glm::translate(model, glm::vec3(0.0f, 0.0f, 0.0f));
    model *= glm::rotate(model, angle, glm::vec3(1.0f, 1.0f, 1.0f));

    glm::mat4 ModelViewMatrix = view * model;
    glm::mat4 ModelViewProjectionMatrix = projection * ModelViewMatrix;

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

    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, colors);

    glUniformMatrix4fv(glGetUniformLocation(programID, "MV"), 1, GL_TRUE, glm::value_ptr(ModelViewMatrix));
    glUniformMatrix4fv(glGetUniformLocation(programID, "MVP"), 1, GL_TRUE, glm::value_ptr(ModelViewProjectionMatrix));

    glDrawArrays(GL_TRIANGLES, 0, 3);

    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(0);

    glUseProgram(0);

    angle += 0.050000f;
    trans += 0.00010f;

    glFlush();
    SDL_GL_SwapBuffers();
}

```

and my vertex shader code :

```
#version 330

in vec3 VertexPosition;
in vec3 VertexColor;

uniform mat4 MV;
uniform mat4 MVP;

out vec3 Color;

void main()
{
    Color = VertexColor;

    gl_Position = MVP * vec4(VertexPosition, 1.0f);
}

```

I tried several combinations of code without any success. I'm lost. Does anyone can help me, please ?

Thanks very much in advance for your help.

# Answer
For me, this code looks flawed:

```
glm::mat4 model = glm::mat4(1.0f);
model *= glm::translate(model, glm::vec3(0.0f, 0.0f, 0.0f));
model *= glm::rotate(model, angle, glm::vec3(1.0f, 1.0f, 1.0f));

```

The modelviewmatrix you are creating seems to me to be like something as this:

M = I * T * (T * R)

(since glm::rotate(model, ...) creates the matrix T * R)

but I think you want to have something as this:

M = I * T * R

which would require the code ( = instead of \*= ):

```
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(0.0f, 0.0f, 0.0f));
model = glm::rotate(model, angle, glm::vec3(1.0f, 1.0f, 1.0f));

```
> 1 votes

# Answer
As Dirk explained, this code is incorrect:

```
glm::mat4 model = glm::mat4(1.0f);
model *= glm::translate(model, glm::vec3(0.0f, 0.0f, 0.0f));
model *= glm::rotate(model, angle, glm::vec3(1.0f, 1.0f, 1.0f));

```

and should really be:

```
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(0.0f, 0.0f, 0.0f));
model = glm::rotate(model, angle, glm::vec3(1.0f, 1.0f, 1.0f));

```

But for anybody wondering why, I'll try to explain it. When you call `glm::translate()`, `glm::rotate()`, or `glm::scale()` the first parameter you pass in is the matrix to perform the transformation on. So when the first example calls `glm::rotate()`, for example, it takes the `model` variable, which is passed in as a parameter, rotates it and then returns the new rotated matrix. But since the times-equal operator (\*=) was used, it set `matrix` equal to itself times the returned value, which produced unwanted results.
> 1 votes

---
Tags: opengl, transformation, glm
---


# Question
Title: FPS drop when detecting collision (sfml, c++)
So, I have this small class with a collision detection function in it, it's called every frame.

When I run the game I get around 8000 FPS, but when the collision function gets called it drops to 2000.

This is what the function looks like (only called 1 time per frame) The second one is just for overriding.

```
bool DetectCollision(sf::RectangleShape other)
{
    if (entityRect.getGlobalBounds().intersects(other.getGlobalBounds()))
    {
        // Handle collision here
        return true;
    }
    else
    {
        return false;
    }
}

bool DetectCollision(sf::Sprite other)
{
    if (entityRect.getGlobalBounds().intersects(other.getGlobalBounds()))
    {
        // Handle collision here
        return true;
    }
    else
    {
        return false;
    }
}

```

Not sure why the FPS drops that much, is this way of detecting collisions heavy for the pc? I'm running a pretty high-end pc.

# Answer
It can be expensive depending on what collision volumes you are using. This is why most of the geometry in games have multiple collision volumes like AABB to convex hull. Testing whether or not two AABB intersect can save a lot of time when objects don't collide as you don't have to perform that e.g. time-consuming convex hull collision detection to get a more accurate collision.

I don't think that's really the problem though, my first reaction was that you were using FPS to messure performance. You should really always use milliseconds per frame instead. 8000FPS = 0.125ms, while 2000FPS = 0.5ms. So 0.5ms - 0.125ms = 0.375ms added to each frame. Now that may or may not be a lot depending again of what collision you are doing.

Just to drive my point in further. If the game ran at 100FPS and you now added your collision calls to each frame it would only drop to 96FPS, not that much. And your probably wouldn't be so worried about it.
> 2 votes

# Answer
It's pretty much expected to see that kind of frame drop... 8000fps translates to 0.0000125 seconds of computation time, while 2000fps translates to 0.00002s. Subtracting those two values, the difference is as low as 0.000075s, which is way low compared to the 16 milliseconds time span you have to render at 60fps.
> 2 votes

---
Tags: c++, optimization, sfml, frame-rate
---


title: Why cannot I show Interstitial ads?

text:
# Question
Title: Why cannot I show Interstitial ads?
I have tried many things but I could not make interstitial ads display in Unity. I want to show interstitial ads after users select a wrong answer and before the score page ("Notice" scene) displays. Here is my code, I just copied relevant parts:

```
 using UnityEngine;
 using UnityEngine.UI;
 using System.Text;
 using System.Xml;
 using System.Collections;
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Xml.Serialization;
 using System.IO;
 using GoogleMobileAds;
 using GoogleMobileAds.Api;

 public class responder : MonoBehaviour
 {
     private InterstitialAd interstitial;

     private int gecis;

     public Text questionsorular;
     public Text responseA;
     public Text responseB;
     public Text responseC;
     public Text responseD;
     public Text infoResponses;
     public Text infoResponses1;
     public Text example;
     public Text dogrusayisi;

     private float corrects;
     private float questoesquestions;
     private float media;
     private int Notice;
 }

 void Start()
 {
     RequestInterstitial();
 }

 public void response(string alternative)
 {

     RequestInterstitial();

     if (alternative == "A")
     {
         if (responseA.text == infoResponses.text)
         {
             corrects += 1;
             nextQuestion();
         }
         else
         {
             Invoke("wrong", 1);
         }
     }

     else if (alternative == "B")
     {
         if (responseB.text == infoResponses.text)
         {
             corrects += 1;
             nextQuestion();
         }
         else
         {
             Invoke("wrong", 1);
         }
     }

     else if (alternative == "C")
     {
         if (responseC.text == infoResponses.text)
         {
             corrects += 1;
             nextQuestion();
         }
         else
         {
             Invoke("wrong", 1);
         }
     }

     else if (alternative == "D")
     {
         if (responseD.text == infoResponses.text)
         {
             corrects += 1;
             nextQuestion();
         }
         else
         {
             Invoke("wrong", 1);
         }
     }
 }

 void wrong()
 {
     ShowInterstitial();
     Application.LoadLevel("Notice");
 }

 private void RequestInterstitial()
 {
 #if UNITY_EDITOR
     string adUnitId = "unused";
 #elif UNITY_ANDROID
             string adUnitId = "MY ADS ID";
 #elif UNITY_IPHONE
             string adUnitId = "INSERT_IOS_INTERSTITIAL_AD_UNIT_ID_HERE";
 #else
             string adUnitId = "unexpected_platform";
 #endif

     // Create an interstitial.
     interstitial = new InterstitialAd(adUnitId);
     // Load an interstitial ad.
     interstitial.LoadAd(createAdRequest());
 }

 private AdRequest createAdRequest()
 {
     return new AdRequest.Builder()
             .AddTestDevice(AdRequest.TestDeviceSimulator)
             .AddTestDevice("0123456789ABCDEF0123456789ABCDEF")
             .AddKeyword("game")
             .SetGender(Gender.Male)
             .SetBirthday(new DateTime(1985, 1, 1))
             .TagForChildDirectedTreatment(false)
             .AddExtra("color_bg", "9B30FF")
             .Build();
 }

 private void ShowInterstitial()
 {
     if (interstitial.IsLoaded())
     {
         interstitial.Show();
     }
 }

```

Following code works perfectly for banner ads when I attached it to camera:

```
 using UnityEngine;
 using GoogleMobileAds.Api;

 public class Ads : MonoBehaviour
 {
     void Start()
     {
         BannerView adsObject = new BannerView(
                 "MY ADS ID", AdSize.SmartBanner, AdPosition.Bottom);
         AdRequest getAds = new AdRequest.Builder().Build();
         adsObject.LoadAd(getAds);
         }
 }

```

# Answer
> 0 votes
I finally did it!

```
 using UnityEngine;
 using UnityEngine.UI;
 using System.Text;
 using System.Xml;
 using System.Collections;
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Xml.Serialization;
 using System.IO;
 using GoogleMobileAds;
 using GoogleMobileAds.Api;

 public class responder : MonoBehaviour
 {
     private InterstitialAd adObject;

     private int gecis;

     public Text questionsorular;
     public Text responseA;
     public Text responseB;
     public Text responseC;
     public Text responseD;
     public Text infoResponses;
     public Text infoResponses1;
     public Text example;
     public Text dogrusayisi;

     private float corrects;
     private float questoesquestions;
     private float media;
     private int Notice;
 }

 void Start()
 {
     GetNewAds( null, null );
 }

 public void response(string alternative)
 {

     if (alternative == "A")
     {
         if (responseA.text == infoResponses.text)
         {
             corrects += 1;
             nextQuestion();
         }
         else
         {
             Invoke("wrong", 1);
         }
     }

     else if (alternative == "B")
     {
         if (responseB.text == infoResponses.text)
         {
             corrects += 1;
             nextQuestion();
         }
         else
         {
             Invoke("wrong", 1);
         }
     }

     else if (alternative == "C")
     {
         if (responseC.text == infoResponses.text)
         {
             corrects += 1;
             nextQuestion();
         }
         else
         {
             Invoke("wrong", 1);
         }
     }

     else if (alternative == "D")
     {
         if (responseD.text == infoResponses.text)
         {
             corrects += 1;
             nextQuestion();
         }
         else
         {
             Invoke("wrong", 1);
         }
     }
 }

 void wrong()
 {
     StartCoroutine(ShowAds());
     Application.LoadLevel("Notice");
 }

IEnumerator ShowAds()
    {
        while( !adObject.IsLoaded() )
            yield return null;

        adObject.Show();
    }

    public void GetNewAds( object sender, EventArgs args )
    {
        if( adObject != null )
            adObject.Destroy();

        adObject = new InterstitialAd( "AD UNIT ID" );
        adObject.AdClosed += GetNewAds;

        AdRequest GetAds = new AdRequest.Builder().Build();
        adObject.LoadAd( GetAds );
    }
}

```

# Answer
> 0 votes
Let's break this down. In your `response` function, you are doing two relevant things:

```
RequestInterstitial();
Invoke("wrong", 1);

```

I suspect what is happening is the first statement is trying to load a new ad, while the second one waits 1 second to display. If the network connection is within 1 second, the ad will display, otherwise, you won't see anything.

To test this, try removing the `RequestInterstitial` from the `response` function. It should work once. Then when you update the display, call `RequestInterstitial` to ensure that there is plenty of time to download the ad.

---
Tags: unity, c#, google-play-services, advertisements
---


# Question
Title: Enemy moving towards Player in a 2D setting?
i want to apologize if this seems so basic, but I'm having trouble having an Enemy move in my Player's Direction in a 2D Top-Down game.

I already saw a lot of other answers but they all use the `.LookAt()` and `.Forward` but i'm not using rotations so i cannot just move them in the direction they are looking at, i just need to move them along X and Y, and i managed to do a pretty horrible workaround :

`//I tried getting the difference between player and enemy positions, but this is relative, and slows down the closer it gets to the player.`

`Vector2 distance = new Vector2(player.position.x - enemy.position.x, player.position.y - enemy.position.y);`

`enemy.AddForce(distance * walkspeed);`

So, how could i make the Enemy move in the direction the Player is, but with a constant speed?

# Answer
To get a constant rate of movement for your *walkspeed*, you can normalize your distance between the player and the enemy.
A normalized vector still points to its original direction, however it has a length of 1, thus, getting you constant results when multiplying with your *walkspeed*.

The math behind it, for a vector *v* to its normalized version *vn*:

```
vn = normalize(v)
<=> v / length(v)
<=> v / sqrt(v.x * v.x + v.y * v.y)

```

In Unity, you can simply use the *normalized* property of a Vector. In your case, this would be:

```
Vector2 distance = new Vector2(player.position.x - enemy.position.x, player.position.y - enemy.position.y);
distance = distance.normalized;

```

If you multiply this vector with your *walkspeed* variable, it will always have a length of *walkspeed*, provided, that the initial distance is greater than 0.
> 5 votes

# Answer
Im really surprised nobody mentionned `Vector2.MoveTowards()`.

Here's the method definition:

```
public static Vector2 MoveTowards(Vector2 current, Vector2 target, float maxDistanceDelta);

```

you would use it as such:

```
Vector2.MoveTowards(player.position, enemy.position, someValueYouDetermine);

```

Moves a point current towards target.

> This is essentially the same as Vector2.Lerp but instead the function will ensure that the speed never exceeds maxDistanceDelta. Negative values of maxDistanceDelta pushes the vector away from target.
> 1 votes

---
Tags: unity, 2d, movement
---


title: Effective AI for 3D Motion

text:
# Question
Title: Effective AI for 3D Motion
I am developing a game in XNA and am trying to create an effective AI for the enemy and friendly spaceships but am having a hard time keeping the game effective without disadvantaging one side or the other (deliberately). My current setup is as follows:

1. Ship targets enemy based on proximity.
2. Ship changes direction and moves toward target, firing when in range. Ship fires single repeater weapon in the forward direction.
3. Ship will not change direction when closer than certain distance from enemy.
4. If you are directly following and shooting at a ship, the ship does not attempt to evade fire. (consequence of #3)
5. All ships have similar firepower.

I am trying to improve this system and am willing to rewrite if necessary. Most of the ships end up flying around each other, shooting but never hitting. I have thought of several ideas to improve it:

1. Once health drops significantly, ship will boost away from firing ship.
2. Some ships are randomly chosen to be equipped with torpedoes (maybe add aft firing?).
3. Make ships more wary of attacking cruisers (they tend to die quickly when attacking).

Does anyone have any other suggestions as to improve the AI of the ships? Does anyone have a completely different system of doing this?

# Answer
> 2 votes
## **Basic AI Steering Behaviours**

* **Seek** *(steer towards target, and accelerate)*
* **Flee** *(steer away from target, and accelerate)*

## **Smarter ai steering behaviours:**

* **Pursue** *(steer towards target's destination \[position+velocity\*amt\])*
* **Evade** *(steer away from target's destination \[position+velocity\*amt\] )*
* **Approach** *(steer towards target, but slow down once within a certain distance, and try to stay in that radius)*

## Even Smarter ai steering behaviours:

* **Evade Projectiles** *(Either evade their current position, or their destination)*

## Other ai behaviours

* **Shoot at Target's Destination**
* **Flocking**
* **Pathfollowing** *(set a specific path to follow with repeat or ping pong effects)*
* **Pathfinding** *(find path from one spot to another; A\* is fun)*
* **Formations**
* **Wander** *(if not doing anything, choose a destination, and go there)*
* **Idle** *(Wait for a new command)*

## AI Decision Handling

* **Target Aggro**
* **Target Tank**
* **Target Player**
* **Target Weakest**
* **Flee or Evade if low health**

## AI Balancing

* **Update in Intervals** *(Make new decision once per second, 2 seconds, every tick, etc)*
* **Awareness** *(Make multiple attention/awareness radii. Only react to certain objects within specific radii)*

---
Tags: xna, ai, path-finding
---


title: What is GLEW and how does it work?

text:
# Question
Title: What is GLEW and how does it work?
**I am looking for a beginner-friendly explanation**. The official website's explanation is too short and lead me to more questions than answers:

---

* What is GLEW?

GLEW developer's page says:

> The OpenGL Extension Wrangler Library (GLEW) is a cross-platform open-source C/C++ **extension loading library**. GLEW provides efficient run-time mechanisms for determining which OpenGL extensions are supported on the target platform.

---

* But what is an extension loading library?

OpenGL's wiki says

> An OpenGL Loading Library is a library that **loads pointers to OpenGL functions** at runtime, **core as well as extensions**.

---

* What does it mean to *load pointers to OpenGL functions*?
* What is an *extension*?
* What does it mean by "*core as well as extensions*"?

# Answer
Most compilers give you an OpenGL header that provides support for OpenGL 1.1, but most of the functions provided in that version of OpenGL have been long since deprecated, and lacks important features such as shaders and vertex buffer objects. GLEW is basically just a header (there is a source file that must also be compiled, but you can just include it in your project) that provides newer OpenGL functionality.

> What does it mean by extension?

Here's a link from OpenGL.org about them. They're just additional functions for OpenGL that aren't part of OpenGL. They provide functionality which may be useful, but you cannot guarantee that they're going to work on every computer since they are not part of core OpenGL.

> What does it mean to load pointers to OpenGL functions?

OpenGL is implemented by the graphics driver as a bunch of functions implemented according to the spec, not as a standalone library, therefore cannot be simply linked to your project.

You have to call a function (such as GetProcAddress, but it depends on the platform you're developing for) to get the function pointer at runtime from the driver for each OpenGL function.

GLEW exists because doing just that can be very difficult. It's much easier when you can just include a header and call one function during initialization, which is exactly what GLEW does. Plus, GLEW is cross-platform.

> What does it mean by "core as well as extensions"?

It means it supplies OpenGL functions as well as OpenGL extensions.
> 23 votes

---
Tags: opengl, glew
---


title: Confused about this Timer function C++

text:
# Question
Title: Confused about this Timer function C++
I am confused about the argument "m" of this function.

I also need to know how to make this work. I am working on a simple 2d game and I am really new to programming. I don't know how to make things work in this Timer() function. I want to animate an object in a specific direction. I know the coordinates of the direction but after a lot of hit and trial, my object moves in a random direction. I have used sin and cos for the movement. But my real problem is about the functionality of this Timer() function. Can anyone here help me about it? Any help will be appreciated.

```
float dt = 0, lastframe = 0;

void Timer(int m) {
    dt = (m - lastframe) / 1000.0;
    lastframe = m;

    glutPostRedisplay();
    glutTimerFunc(1000.0 / FPS, Timer, m + 1);
}

```

# Answer
> 1 votes
According, the value passed to timer function, is the one you provided when registering the timer as the third parameter. Read here for more information. It's mainly for the purpose of tagging different calls to timer functions, so that you can do different things based on tags.

If you want to keep track of actual time passed since last frame, you've got to keep track of time yourself; With mechanisms like std::chrono::high\_resolution\_clock.

---
Tags: c++, 2d, animation, software-engineering
---


# Question
Title: Blender model doesn't show up in monogame
I have a problem getting blender models to show in monogame on windows. Using latest monogame 3.4, fresh blender 2.76b, developing in Visual Studio 2010 using OpenGL Monogame template.

What I'm trying to do is to create a simple model in blender - a sphere, export it as FBX, getting it properly into Monogame Pipeline - here it compiles fine. But then it's invisible in the application. I load it this way:

```
model = Content.Load<Model>("MyBall");

```

I draw it this way:

```
model.Draw(Matrix.Identity, camera.View, camera.Projection);

```

Also tried other drawing method with enumerating meshes.

The code seems to work in general, because I can see a model which I downloaded from Internet. However I got one or two working, with tens of other downloaded models which don't work and tens which the Pipeline tool will not accept.

I can move around in my app to make sure I' m not inside a model. Also tried adding material in Blender but with no luck. But I'm still learning Blender.

Also tried Autodesk FBX converter, but didn't help anything.

Where's the catch?

# Answer
> 2 votes
Okay, found it. Used this to draw the model:

```
foreach (ModelMesh mesh in model.Meshes)
{
    foreach (BasicEffect modelEffect in mesh.Effects)
    {
        modelEffect.EnableDefaultLighting();
        modelEffect.World = Matrix.Identity;
        modelEffect.View = camera.View;
        modelEffect.Projection = camera.Projection;
        modelEffect.Alpha = 1;
    }

    mesh.Draw();
}

```

And the critical thing in this is to add `modelEffect.Alpha = 1`.

---
Tags: c#, monogame, blender
---


# Question
Title: Unity 5: Check if an object's collider contains the mouse click point
I am building a 2D turn-based RPG battle scene with Unity 5. The enemies are represented as 2D sprites with box colliders. In my script, the relevant enemy class is defined as:

```
public class EnemyView : MonoBehaviour {

    public SpriteRenderer _renderer;
    public BoxCollider2D _collider;

    void Awake() {
        _renderer = gameObject.GetComponent<SpriteRenderer>();
        _collider = gameObject.GetComponent<BoxCollider2D> ();
    }
}

```

And I have the following code grouping the enemy sprites together:

```
public class MainGUIView : MonoBehaviour {
    public EnemyView[] _enemyViews;
}

```

When a player clicks on an enemy, I would like to know the index of that enemy within the `_enemyViews` array. I thought of implementing this within `EnemyView` class but that class has no information about its index, so I am thinking of implementing `OnMouseDown()` within `MainGUIView` where I could iterate through `_enemyViews` to find the one whose collider contains the mouse click point, but I don't know how to write the code. Anyone can point me to some useful code snippet?

# Answer
You can use Dictionary to hold the index data.

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

Dictionary<int, EnemyView> _enemyViews;
// populate dictionary

// element access while looping
_enemyViews[i].first;   // gets the index
_enemyViews[i].second;  // gets the EnemyView object

```
> 3 votes

---
Tags: unity
---


title: Section cut through (solid) geometry

text:
# Question
Title: Section cut through (solid) geometry
I'm looking for image based (screen space) technique to render section cuts through arbitrary (solid) geometry. I found and studied image based CSG (Kirsch 05 / OpenCSG) but I found it to be perhaps a bit of a overkill for my case, where all I need is a section plane cut.

Above is a naive implementation using a `discard` in the fragment shader, but that obviously is not even half-way there as I need to close the gaps. Does anyone know of a technique/hack I could use?

# Answer
I assume by gaps you mean you want to render caps to the top. Not sure if this is still the preferred approach, but you can use clipping planes with stencils. An example would be here.

An alternative approach might be to render your object with just backfaces first. The problem is that your geometry has diagonal front faces on the corners which would probably cause artifacts since they'd render over the back face cap color. That said if you can remove those artifact front faces from your geometry it should work. The only big problem you might see with this approach is anti-aliasing artifacts on the edges depending on your AA technique.
> 1 votes

# Answer
To close gaps created from a plane cut, assuming otherwise closed geometry, you should be able to do it with just the depth buffer.

* Depth buffer contains front face depth after rendering the cut geometry.
* Render backfaces (using an inverted cull mode), thus selecting only the pixels that would appear on the gaps.
* Use plane normal instead of interpolated vertex normal for lighting.
* To generate planar texture coords and/or pixel position, in the shader:
    + Get view space position, intersect ray from (0,0,0) to this position with view-space plane to get the pixel view-space position.
    + Transform that position back to world space (by multiplying it with an inverse view matrix).
    + Generate coords from dot products between world space position and plane tangents (they can be arbitrarily selected, as long as they're 90 degrees apart from each other and plane normal).

As for those internal triangles, if they're overlapping (both front- and backfaces), some depth bias will be enough to remove them. Otherwise, I'd suggest removing them some other way.
> 2 votes

---
Tags: opengl, screen, intersection, csg
---


title: Load custom resources in Unity

text:
# Question
Title: Load custom resources in Unity
The situation is I work in my free time on one study project. I have resources of one game packed in it's own format. My intent was to use those with Unity without converting them into Unity's inner format.

But with brief analysis of Unity Api Reference I did not find anything that would help my in my efforts. Like I have custom binary files I would need to parse with Unity and upon that data create geometry, lights and so on using Unity's classes.

So I wonder if it's even possible? I would really appreciate if anyone would show make a hint on this subject

# Answer
> 1 votes
Almost any Unity component can be created completely code-based at runtime.

The documentation of the class Mesh has an example how to create a new 3d model just from binary data:

```
public class ExampleClass : MonoBehaviour {
    public Vector3[] newVertices;
    public Vector2[] newUV;
    public int[] newTriangles;
    void Start() {
        Mesh mesh = new Mesh();
        GetComponent<MeshFilter>().mesh = mesh;
        mesh.vertices = newVertices;
        mesh.uv = newUV;
        mesh.triangles = newTriangles;
    }
}

```

This code snippet does of course assume that the arrays `newVertices`, `newUV` and `newTriangles` are filled with the data read from your custom file formats. Any C# classes for file IO are also available from Unity, but when you want to work with the Unity asset management system and not against it, you might do well loading them as `TextAssest`s which (despite the name) also work very well for binary data.

It also assumes that you already have a game object which already has a MeshFilter component. You can also create that at runtime:

```
GameObject my3dObject = new GameObject("My 3d object");
my3dObject.AddComponent<MeshFilter>();

```

Other Unity components like Light have similar ways to create them completely code-based.

---
Tags: unity
---


# Question
Title: Removing seams between procedurally-generated spherical terrain tiles
I'm working on procedural planet generation project in Unity. To create a sphere, I use the following technique:

1. Create six planes arranged as faces of a cube
2. Normalize all vertices' positions to create a unit sphere
3. Multiply each vertices' positions by the height value obtained from an `IHeightsProvider` (3D simplex noise in this case) + the planet's `radius`.

All operations necessary for creating a mesh (create vertex positions array, triangle indices array, normals array) are performed in a separate thread for performance reasons. Vertices, triangles, and normals, encapsulated in a `MeshData` object, are assigned to Unity's `Mesh` object in the main thread.

The problem is, of course, seams between faces of the cubesphere:

These issues are due to the flawed normal computation algorithm, which only takes normals of triangles **in** the mesh into account, being not aware of the adjacent meshes. Ideally, I'd like to have normals computed regardless of adjacent meshes' presence (i.e no `SetNeigbors`), using the same `heightsProvider` used for obtaining the mesh's own vertices' heights.

I've been trying to figure it out myself, as well as extensively searching the web, for a few days so far, but the problem doesn't seem to become any clearer.

Here's my code for creating vertices, triangles and normals in a separate thread:

```
protected override void ThreadFunction (System.Object info)
    {
        int resolution = parameters.resolution;
        int numVertices = resolution * resolution;

        float minHeight = parameters.minHeight;
        float maxHeight = parameters.maxHeight;

        Quaternion faceRotation = parameters.rotation;

        // Create vertices
        // ---------------

        Vector3[] vertices = new Vector3[numVertices];

        int vertNum = 0;

        for (int x = 0; x < resolution; x++)
        {
            for (int y = 0; y < resolution; y++)
            {
                Vector3 posOnCube = GetVertexPosOnCube (x, y);
                Vector3 posOnUnitSphere = CubeToSphere (posOnCube);

                Vector3 samplePosition = posOnUnitSphere;
                float height = GetHeight (samplePosition);

                vertices[vertNum++] = posOnUnitSphere * height;
            }
        }

        this.meshData.vertices = vertices;

        // Create triangle indices array
        // -----------------------------

        int[] triangles = new int [(resolution - 1) * (resolution - 1) * 6];

        int triangleIndex = 0;
        int vertexIndex = 0;

        for (int x = 0; x < resolution - 1; x++)
        {
            for (int y = 0; y < resolution - 1; y++)
            {
                triangles[triangleIndex] = vertexIndex;
                triangles[triangleIndex + 3] = triangles[triangleIndex + 2] = vertexIndex + (resolution - 1) + 1;
                triangles[triangleIndex + 4] = triangles[triangleIndex + 1] = vertexIndex + 1;
                triangles[triangleIndex + 5] = vertexIndex + (resolution - 1) + 2;

                triangleIndex += 6;
                vertexIndex++;
            }

            vertexIndex++;
        }

        this.meshData.triangles = triangles;

        // Calculate normals
        // -----------------

        Vector3[] normals = new Vector3 [numVertices];

        for (int i = 0; i < meshData.triangles.Length; i += 3)
        {
            int ind0 = meshData.triangles[i + 0];
            int ind1 = meshData.triangles[i + 1];
            int ind2 = meshData.triangles[i + 2];

            Vector3 pos0 = meshData.vertices [ind0];
            Vector3 pos1 = meshData.vertices [ind1];
            Vector3 pos2 = meshData.vertices [ind2];

            Vector3 to1 = pos1 - pos0;
            Vector3 to2 = pos2 - pos0;

            Vector3 normal = Vector3.Cross (to1, to2).normalized;

            normals [ind0] += normal;
            normals [ind1] += normal;
            normals [ind2] += normal;
        }

        for (int i = 0; i < numVertices; i += 1)
        {
            normals [i].Normalize ();
        }

        this.meshData.normals = normals;
    }

```

# Answer
> 1 votes
The problem is your normals on the edges of your tiles, you can't calculate them without having the next tile in the range.

I got round this problem by generating a border row around my tile (or in my case voxel chunk) so that when i come to build meshes from that data I can correctly determine the real normals.

you might be able to solve this by simply doing this in the first loop pair ...

```
for (int x = -1; x < resolution + 1; x++)
        {
            for (int y = -1; y < resolution + 1; y++)
            {

```

More input based on comments below:

so the theory goes something like this ... i want a mesh that sits in the range 0 to 10 on each axis with all the right normal info, so here's how I would do it ...

```
Vector3[] positions = new [12 * 12 * 12];

// generate the full range
for(x -1 to 11)
  for(y -1 to 11)
      positions[ComputeIndex(x,y,z)] = ComputePos(x.y.z);

    // iterate over the range to generate mesh info
List<vert> meshInfo = new List<vert>;
    int currentIndex = 0;
    for(x 0 to 10)
      for(y 0 to 10)
        {
          var vert = new vert {
              pos = positions[ComputeIndex(x,y,z)],
              index = currentIndex,
              normal = ComputeNormal(x,y,z),
              uv = ComputeUv(x,y,z)
          }
          currentIndex++;
        }

// assuming a unity mesh is what we want
var mesh = new Mesh {
   vertices = meshInfo.Select(i => i.pos).ToArray(),
   normals = meshInfo.Select(i => i.normal).ToArray(),
   uv = meshInfo.Select(i => i.uv).ToArray()
};
mesh.triangles(meshInfo.Select(i => i.index).ToArray());

```

---
Tags: unity, procedural-generation, terrain, 3d-meshes, normals
---


# Question
Title: Camera movement and threshold not working
I have a platformer that is in progress, part of this has a camera which I only want to move when the character moves out of a certain threshold, to try to accomplish this I have the following if statement:

```
 if(((Mathf.Abs(target.transform.position.x))-(Mathf.Abs(transform.position.x)))>thres){
            x = moveTo(transform.position.x, target.position.x, trackSpeed);
            }

```

in unity/c#. In pseudocode it means

```
if((absolute value of player x) - (absolute value of camera x) is greater than the threshold){
move
{

```

however this does not seem to work correctly. it appears to work for the first couple of times the threshold is reached, however the distance between the camera and the player has to increase every time for the camera to move. I do not believe the movement of the camera is the problem, however the code for it is as follows:

```
private float moveTo(float n, float target, float accel) {
    if (n == target) {
        return n;
    }
    else {
        float dir = Mathf.Sign(target - n);
        n += accel * Time.deltaTime * dir;
        return (dir == Mathf.Sign(target-n))? n: target;
    }
}

```

}

# Answer
> 1 votes
i dont like

(Mathf.Abs(target.transform.position.x))-(Mathf.Abs(transform.position.x))

Instead I'd like

```
(Mathf.Abs(target.transform.position.x-transform.position.x))

```

try it

# Answer
> 0 votes
I don't have a direct answer for you, but good debugging will help. I suggest that you use Debug.Log in the Unity Editor. For example, log whether it has chosen to move, and if so where it has moved to. Often that gives way too much output, which is where I'd suggested throttling it, for example only log if Time.frameCount % 10 == 0. This will only log every tenth frame. Then reproduce your bug, pause the game, and look at the log.

# Answer
> 0 votes
Here's the problem:

In pseudo-code, what you're doing is this:

```
if ( abs(playerX) - abs(cameraX) > 5 ) // arbitrary threshhold value of 5
    moveCamera();

```

Let's take the case where the player is at 15, and the camera is at 100. It's obvious to you and me that in this situation, the camera is too far away and ought to move, but let's run the math:

```
abs(15) == 15
abs(100) == 100
15 - 100 == -85

```

-85 isn't greater than 5, so the camera won't move!

Your problem is that you don't want to be taking the absolute value of each position separately and then subtracting them; you want to be taking the absolute value of the *difference* between the two positions! That way, you'd get `abs(15-100) == 85` and `85 > 5`, so the camera would correctly move.

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


# Question
Title: How would i go about implementing portals into my game?
I don't mean to ask a broad question, so let me explain. I'm creating a 2D top-down design game and I'd like to implement "portals" to be able to switch between worlds. Each world is a level class, and at the moment portals are rendered as tiles, and changing world is handled in the player collision code. However, I have no way of determining which portal is dedicated to which level. I would perhaps also like to have the ability to lock portals until a player becomes a certain rank. I've tried to set up a portal class, and implemented it as entities that were spawned during level creation at the location of the portal tiles, and then all collision handling was passed to that class. It took in params of `currLevel`, `targetLevel`, `x` and `y`. When the player collided, it would change to the set `targetLevel`. However, when I ran the code and collided with the portal, the game just froze. There was no error output, ups was at 60 as standard and the fps was at about 3000 as standard. The terminal was also outputting as normal, but the game was doing nothing.

To conclude, I'd like to know if there is a better way to go about completing this? I may have just missed something.

Thanks

Here is the code im using to render it as a tile:

(Level class):

```
if (tiles[x + y * width] == Tile.col_portal)
        return Tile.portal;

```

(in Mob class, for player collision):

```
        if (this instanceof Player) {
            if (level.getTile(ix, iy) instanceof SpawnWaterTile) {
                Player.swimming = true;
                Player.canShoot = false;
            } else if (level.getTile(ix,iy) instanceof SpawnPortalTile) {
                Game.getGame().changeLevel(Level.level1);
            } else {
                Player.swimming = false;
                Player.canShoot = true;
            }
        }

```

EDIT: After attempting to reintroduce the portal class in the way that @Reg suggested, i had the following error:

Portal Class:

```
package com.ritcat14.GotYourSix.entity;

import com.ritcat14.GotYourSix.Game;
import com.ritcat14.GotYourSix.graphics.Screen;
import com.ritcat14.GotYourSix.graphics.Sprite;
import com.ritcat14.GotYourSix.level.Level;

public class Portal extends Entity {

    private int x = 0, y = 0;
    private Level currLevel = null, locationLevel = null;

    public static Portal Level1 = new Portal(1,1,Level.spawn, Level.level1);
    public static Portal Level2 = new Portal(2,1,Level.spawn, Level.level2);
    public static Portal Level3 = new Portal(3,1,Level.spawn, Level.level3);

    public Portal(int x, int y, Level currLevel, Level locationLevel){
        this.x = x;
        this.y = y;
        this.currLevel = currLevel;
        this.locationLevel = locationLevel;
        sprite = Sprite.portal;
    }

    public Portal(int x, int y, Level currLevel){
        this.x = x;
        this.y = y;
        this.locationLevel = Level.spawn;
        this.currLevel = currLevel;
        sprite = Sprite.portal;
    }

    public void update(){
        System.out.println(this);
        // --> null?? System.out.println(currLevel);
        System.out.println(currLevel.getClientPlayer());
        System.out.println(currLevel.getClientPlayer().getBounds());
        if     (this.getBounds().intersects(currLevel.getClientPlayer().getBounds())) {
          Game.getGame().changeLevel(locationLevel);
          remove();
        }
    }

    public void render(Screen screen){
        screen.renderSprite(x, y, sprite, true);
    }
}

```

The change level method works fine, the issue seems to be that the current level doesn't actually exist. This is how im adding the portals to the level in the `Level.spawn` level:

```
    public class SpawnLevel extends Level {

    public SpawnLevel(String path) {
        super(path, false);
    }

    protected void loadLevel(String path){
        try{
            BufferedImage image = ImageIO.read(SpawnLevel.class.getResource(path));
            int w = width = image.getWidth();
            int h = height = image.getHeight();
            tiles = new int[w * h];
            image.getRGB(0, 0, w, h, tiles, 0, w);
        }catch(IOException e){
            e.printStackTrace();
            System.out.println("Failed to load level file.");
        }
     generateLevel();
    }

     public void setPlayerLocation(){
      for (int i = 0; i < getPlayers().size(); i ++){
          getPlayers().get(i).setLocation(new Vector2i(5 * 16, 70 * 16));
      }
   }

  protected void generateLevel(){
    add(Portal.Level1);
    add(Portal.Level2);
    add(Portal.Level3);
    //no enemies!
  }
}

```

Any ideas? The currLevel is apparently null

# Answer
> 3 votes
There are several options I can think of for associating each portal with a level, but the one you tried already is worthy of another go. Since you seem to have the Level class sorted nicely with `Level.level1`, `Level.level2` etc., why not try a parent portal class with the different portals associated with the different levels in the same fashion? i.e. `Portal.portal1`, `Portal.portal2`, etc. (although if these are subclasses I would insist using caps). Then you can not only associate the different portals with their specific levels (in a manner which is easy to record), but they can define different appearances and permissions in their fields. Permissions can depend on the player rank, or as in other games, keys gained by the player, or events triggered in the environment. If I read you correctly, the code which was causing the freezing first time around is exactly this code which you have dispensed with, so have another bash at it, and stick it up if it gives more/the same problem.

---
Tags: java, 2d, rendering, world-design, tiles
---


# Question
Title: How to calculate a vector for multi-axis rotations from sphere coordinates?
I'm working on a SceneKit project in iOS, trying to rotate a sphere (representing a planet) so that a point at a given longitude/latitude coordinate is facing "forward" (i.e. that point moves to the {0,0} position). So for example, we're looking at Earth's {0,0} point, off the coast of Africa, but I need to know what rotation vector would have us looking at {37,-122}, aka San Francisco. Ideally, the planet would remain "naturally" oriented, with north remaining generally "up" from our perspective, but that's flexible.

I've got the animation working and I can rotate to a given longitude OR latitude using SCNVector4, but as soon as I try to rotate to a given longitude AND latitude, it gets wildly messed up. So I've been doing some research, and I've found some resources that seem to do exactly what I need, but to be honest they're a bit beyond me. I'm a complete newbie in the world of trigonometry and matrices, and it seems there's no way around this problem without them.

Can anyone help me understand how these concepts can take long/lat coordinates, and calculate a rotation vector? A method for creating a SCNVector4 would be perfect, but even just help with calculating the components individually would be greatly appreciated!

# Answer
> 1 votes
Ok, Here's what I got, with the understanding the goal is an axis-angle 4 vector representation, and the goal is provide that to something that can rotate the earth.

```
(Axis,Angle) CalcEarthAxisAngleRotationFromLatLong(float lat, float long) {
   if (lat == 0)
    return up, long;            // up is 'to the north pole'
   else if (long == 0)
    return cross(up, fwd), lat; // forward is 'to the 0,0 africa point', cross assume right hand coords
   else // what we need to do is compose the two pieces
    AxisAngle aaLat  = RotateEarthToLatLong(lat, 0);
    AxisAngle aaLong = RotateEarthToLatLong(0, long);
    ?? composableLat = f(aaLat);
    ?? composableLong = f(aaLat);
    ?? composedLatLong = Compose(composableLat, composableLong);
    AxisAngle aaLatLong = invF(composedLatLong);
    return aaLatLong;
}

```

?? are typically rotation matricies or unit quaternions, Compose is matrix or quaternion multiplication, and F and invF the associated conversion functions. As an example in quaternions:

```
?? = struct Quat {
    float s;
    Vec3  v;
}

f = QuatFromAxisAngle(Vec3 axis, float angle) {
    q.v = sin(.5*angle) * axis;
    q.s = cos(.5*angle);
    return q;
}

invF = AxisAngleFromQuat(Quat q) {
    axis = normalize(q.v);
    angle = acos(q.s)*2;
    return axis,angle;
}

Compose = QuaternionMultiplication(Quat q0, Quat q1) {
    Quat q;
    q.s = q0.s*q1.s - Dot(q0.v, q1.v);
    q.v = q0.s*q1.v + q1.s*q0.v + Cross(q0.v, q1.v);
    return q;
}

```

This is actually why people bother to use quaternions (or matricies), instead of axis angle, because they compose well.

Notes: You could go directly from lat,long to quaternions rather than needlessly converting to AxisAngle rep, I did so in the example just to build off of what you already had done, and show that the piece that is missing is 'how do i compose rotations' - which you alluded to in your question. (2) I might have the order wrong argument in Compose().

---
Tags: 3d, mathematics, rotation, vector, trigonometry
---


title: Different screen sizes?

text:
# Question
Title: Different screen sizes?
I have looked through all of the android docs and many stack overflow questions, and I have a question on supporting multiple screen sizes. If I have some drawables, I know I need to put them in folders like these:

But does android make these folders for me? When I try copy and pasting my images into the drawable folder, I get something like this:

With no directory names. So do I have to manually make those directories, and then **will android automatically pick the right image to use depending on the screen size?**

I have the same question for the layout. For example, I know that to support many screen sizes, I need to put the layout in many folders like this:

But right now, my layout is like this:

So must I manually create each layout folder, and then copy and paste my current layout into the new layout folder, and then go into each layout, and render it until it looks nice on the android design tab of the XML? **Then, will android pick out the best layout depending on the screen size for me?**

Thanks so much,

I have been delaying making my app compatible in different layouts because of these questions, I hope they can get answered!

# Answer
I recommend you read this first if you haven't already as it explains all about different resource folders: http://developer.android.com/guide/topics/resources/providing-resources.html

The most important fact is that it's all just about the name of the folder, so yes you could create the folder manually if you wanted to just following the naming scheme used in the article I gave you. However since you seem to be using android studio I'll show you how you can do it there since it has some built-in functionality for it.

Also yes, android will automatically get the right resource for you. If you have multiple different my\_circle.png files in different folders with different constraints, R.drawable.my\_circle with only return the image in the folder that matches the current device specifications. The exact algorithm it uses to select the resource is in the article.

First with any layout open you can click the top left button in the editor to change what layout you want to be working on as well as create new layouts.

Here is the "folder maker". You can select any constraint on the layout on the left, like if you what the layout only to be used if the user has a certain screen size, screen density, language, etc. Just add the ones you want and notice that it changes the directory name to match.

Now your new layout is available on the left. In the android view, the folder name of the layout/resource is in is given in parenthesis. If you do it this way android will automatically make a layout XML file for you, instead of just creating a folder and copying it over like you mentioned.

However it's still in it's own folder if you change to the project files view. This shows how the res folders/files are actually stored.

To create something similar for images or other resources, just right-click the res-folder and create a new android resource directory. You'll be presented with the same "folder maker" as before except that's it's no longer locked on type layout and you have to change the type yourself to e.g. drawable or whatever resource type you are adding. This will then create a drawable folder with the correct name for you to drag-and-drop your images into.

Here I created a folder using a size constraint of normal. Your may have to be in e.g. the project files view to be able to drag over files as the folder wouldn't show up in the typical android view. If you wonder how to change view, just click the drop-down on the top of the image.

Remember to **always** include a default resource folder, one with no constraints. Otherwise your app will crash when the constraint aren't met.
> 3 votes

---
Tags: java, android
---


title: Play videos with LibGDX

text:
# Question
Title: Play videos with LibGDX
Is there a way to play videos with LibGDX?

I want to put a video as my splash screen in Android, but I dont want to use the Android SDK, because I am using LibGDX and I am almost finished :/

# Answer
> 12 votes
Playing video with LibGDX has been defined as out of scope for the project. So **no**, you cannot play videos using LibGDX.

This does not preclude the possibility of writing code specific to Android to play videos though. It just means your application won't maintain the portability of LibGDX.

# Answer
> 20 votes
As Byte56 said, in libGDX you cannot play videos :( so i did this:

I created a new activity "SplashScreen"

```
public class SplashScreen extends Activity implements OnCompletionListener
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.splash);
        String fileName = "android.resource://"+  getPackageName() +"/raw/video";

         VideoView vv = (VideoView) this.findViewById(R.id.surface);
         vv.setVideoURI(Uri.parse(fileName));
         vv.setOnCompletionListener(this);
         vv.start();

    }

    @Override
    public void onCompletion(MediaPlayer mp)
    {
        // TODO Auto-generated method stub
        Intent intent = new Intent(this, libgdx.class);
        startActivity(intent);
        finish();
    }
}

```

In the "onCompletion" method, I use the intent to call my new activity where the "initialize" call for the libGDX engine to work

And a new layout for the videoView

```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <VideoView
        android:id="@+id/surface"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center" >

    </VideoView>

</LinearLayout>

```

# Answer
> -1 votes
This is the way to play: libname is "indiespot-media-0.8.09.jar" which you can get here.

How to use:

1. Download full zip
2. Copy lib folder in the root of project (ffmpeg will be opened by lib with path ./lib/ffmpeg/ffmpeg@os postfix@)
3.

```
player = new MoviePlayer(videoFile);
Texure playerTexture = new Texture(
  player.movie.width(),
  player.movie.height(),
  Pixmap.Format.RGBA8888) {

  @Override
  public void bind() {
    Gdx.gl.glBindTexture(0, player.textureHandle);
  }
};

```
4. use `playerTexture` as usual texture

---
Tags: android, libgdx, video
---


# Question
Title: How to calculate texture coordinates for a cube?
I was reading about texture mapping on 3D shapes in javafx where I came across this code,

```
static TriangleMesh createMesh(float w, float h, float d) {
if (w * h * d == 0) {
return null;
}
float hw = w / 2f;
float hh = h / 2f;
float hd = d / 2f;
float x0 = 0f;
float x1 = 1f / 4f;
float x2 = 2f / 4f;
float x3 = 3f / 4f;
float x4 = 1f;
float y0 = 0f;
float y1 = 1f / 3f;
float y2 = 2f / 3f;
float y3 = 1f;
TriangleMesh mesh = new TriangleMesh();
mesh.getPoints().addAll(
hw, hh, hd, //point A
hw, hh, -hd, //point B
hw, -hh, hd, //point C
hw, -hh, -hd, //point D
-hw, hh, hd, //point E
-hw, hh, -hd, //point F
-hw, -hh, hd, //point G
-hw, -hh, -hd //point H
);

mesh.getTexCoords().addAll(
x1, y0,
x2, y0,
x0, y1,
x1, y1,
x2, y1,
x3, y1,
x4, y1,
x0, y2,
x1, y2,
x2, y2,
x3, y2,
x4, y2,
x1, y3,
x2, y3
);
mesh.getFaces().addAll(
0, 10, 2, 5, 1, 9, //triangle A-C-B
2, 5, 3, 4, 1, 9, //triangle C-D-B
4, 7, 5, 8, 6, 2, //triangle E-F-G
6, 2, 5, 8, 7, 3, //triangle G-F-H
0, 13, 1, 9, 4, 12, //triangle A-B-E
4, 12, 1, 9, 5, 8, //triangle E-B-F
2, 1, 6, 0, 3, 4, //triangle C-G-D
3, 4, 6, 0, 7, 3, //triangle D-G-H
0, 10, 4, 11, 2, 5, //triangle A-E-C
2, 5, 4, 11, 6, 6, //triangle C-E-G
1, 9, 3, 4, 5, 8, //triangle B-D-F
5, 8, 3, 4, 7, 3 //triangle F-D-H
);
mesh.getFaceSmoothingGroups().addAll(
0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5
);
return mesh;
}

```

How did the calculate and set up the texture coordinates for the cube?

# Answer
> 1 votes
Texture coordinates can be whatever you want them to be.

Usually for simple shapes you want the scale of the texture (that is, how big the texels will be in world space) on all sides to be the same, which means for this cube that each face gets the same area of the cube texture. We can see that all the coordinates used are multiples of 1/4 on the x axis and 1/3 on the y axis, so presumably they're all 1/4 by 1/3 rectangles (I haven't checked). Texture coordinates generally run from 0 to 1 regardless of the pixel size of the texture; this allows you to substitute a different resolution of texture without changing the coordinates.

Presumably each face of the cube gets its own non-overlapping piece of the texture. You can arrange the faces on the texture any way you like, but usually one chooses arrangements which put at least some adjacent faces of the cube adjacent on the texture as well; if done as much as possible, this is a *net* of the cube. The division of the texture into 3-by-4 tiles suggests that this is the case; since a cube has six faces 3-by-2 would be more suited for an efficient packing.

Finally, you generally want to make sure that the texture coordinates are arranged in the same order for all faces (counterclockwise or clockwise) so that parts of the texture are not mirror-reversed, which makes painting the texture more inconvenient — unless your model actually has perfect mirror image sections (without any writing or such on them).

The above are just constraints to follow. There's lots of freedom beyond that.

If you're manually setting up coordinates as the above code does, then generally the way you start is by picturing one face of the model, and picking some region of the texture to go with it. Then you move along the vertices of the face and enter the corresponding texture coordinates, making sure that it's the right orientation. Then you do the same with adjacent faces in a consistent way, and continue until you've done all of the model.

---
Tags: graphics, javafx
---


# Question
Title: What are Hull, Domain and Geometry shaders used for?
I've done my fair share of 3D game programming for my (former) employer, and also in my own custom engines for my own indie games.

Initially, I started with Direct3D 9, and D3DX9, which pretty much did everything for me, and didn't require me to think in terms of shaders at all.

After that, I wrote my first Direct3D 9 shaders, but mostly used one very simple shader for everything I did.

In the most recent iteration of my game engine, I moved to Direct3D 11, and with that I created lots of shaders. I did GPU skinning, GPU calculated particles, lots of lighting and post processing effects, all in the GPU. Really cool stuff.

So far I have only used vertex and pixel/fragment shaders. Even though there are still lots of things I still haven't done, I believe I have a solid knowledge of what the vertex and pixel/fragment shaders do, and how that all fits into the entire 3D pipeline.

Catching up with more recent developments, I've become very interested with the newer shader stages. That is, the Geometry Shader, and even newer, the Hull and Domain shaders.

I have never used these stages, but from what I know, the Geometry shader, if enabled, is run after the vertex shader, once for each transformed vertex (or once per primitive?) and allows you to discard vertices (and primitives?), and create new ones (which I guess go back to the beginning of the pipeline?).

My guess is that the main use of the geometry shader would be to programatically generate geometry in the GPU. A common usage would be to create billboard quads based on a single vertex, but I don't really visualize many other common scenarios apart from generating fractals and other stuff you can generate 100% programatically.

As for the Hull and Domain shaders, it seems like they're related to tessellation (creating smoother surfaces out of rough surfaces?), and must be used together or not at all. The term "patch" also seems to be common in here.

Would anybody care to explain to me, in practical terms, what these new-ish shader stages are for, how they fit into the 3D pipeline, and in which cases should I consider using them?

# Answer
> 18 votes
**Hull & Domains**

The hull and domain shader stages are part of the tessellation pipeline of the GPU. They're generally used to compute highly-detailed surface geometry based on lower-detail input surface geometry, which is defined as triangles or quads (et cetera). The lower-detail input primitives are called "patches," and it's important to note that they may not represent *actual geometry* that will eventually exist (although they could). Think of more like the control points of a bezier curve, except for a surface.

The hull shader takes an input patch and produces an output patch (or patches; this is where subdivision of the patch would generally occur). Constant metadata about the patch can also be computed within the hull shader and output for processed by later stages of the pipeline.

The output of the hull shader runs through a (fixed function) tessellation stage which produces tiled, normalized domains of the appropriate type (e.g., quads or triangles).

The domain shader is executed against these domains in order to compute the actual vertex position of any given point in a domain that resulted from the aforementioned tessellation. The domain shader thus outputs a vertex position.

The tessellation phase occurs after the vertex shader stage in the pipeline.

**Geometry Shaders**

Geometry shaders are like simplified hull/domain shaders, in a way. They simply take input vertices and produce output vertices. For a given input vertex, many output vertices can be produced, so they can be used to "generate geometry."

The geometry shader stage occurs after the vertex shader, and after the tessellation stage.

**Uses**

The geometry shader can write to stream output buffers instead of being fed directly into the rasterization and fragment shading phase of the pipeline; this effectively means you can re-run the geometry produced by a combination of a vertex/hull/domain/geometry shader iteration back through the pipeline, to perform additional work in another vertex shader stage or whatever.

*What* you can use these for is a rather broad, effectively-unlimited topic, so I won't really attempt to address that. But as for some motivating reasons to consider using them... The big thing about these shader stages is that they let you get a potentially quite a lot of extra detail without paying the memory or bandwidth cost for all of it, all the time. And also to move processing from the CPU to GPU.

Terrain is a good example of where you might want to use some of this technology, as you generally need to see it both very close (as your character is standing on it) and very far away (the mountains in the distance) and being able to control where and how much detail you put into the terrain geometry "on the fly" via these shader stages is very powerful. The alternatives have historically been either paying a constant average cost for the terrain at all times (a lowest-common-denominator approach) or manually paging chunks of geometry for different levels-of-detail in and out of GPU memory, which is tedious and expensive.

Any similar situation where you might have a really broad range of levels-of-detail you need to support for some mesh or model that is also reasonably subdividable may be a candidate for doing something clever with these shaders as well. Not everything translates well to subdivision surface style optimization, though. You could probably use them for cloth and hair as well.

For further reading, including vastly more detail than I can reasonably remember or go into here:

---
Tags: shaders, tessellation, geometry-shader, hull-shaders, domain-shaders
---


# Question
Title: Javascript canvas check if all recs on the screen overlap a new one
So I know the AABB collision detection formula, however, this code does not work. Whenever I press space, a new square pops up. But this new square can spawn inside another, something that I do not want to happen. Here is a snippet of the code I think is going wrong:

```
var xTopsBotsYTopsBotsSquares = [];

//Makes a randint() function.
function randint(min, max) {

    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function checkForOccupiedAlready(left, top, right, bottom) {

    if (xTopsBotsYTopsBotsSquares.length == 0) {
        return true;
    }
    for (var i = 0; i < xTopsBotsYTopsBotsSquares.length; i++) {
        var data = xTopsBotsYTopsBotsSquares[i];

        if (data[0] <= right || data[1] <= bottom ||
            data[2] >= left  || data[3] >= top) {/*Do nothing*/}
        else {

            return false;
        }
    }

    return true;
}

//Makes a new square
function makeNewsquare() {
    var checkingIfRepeatCords = true;
    //DO loop that checks if there is a repeat.
    do {
        //Makes the square x/y positions
        var squareRandomXPos = randint(50, canvas.width - 50);
        var squareRandomYPos = randint(50, canvas.height - 50);

        //Tests if that area is already occupied
        if (checkForOccupiedAlready(squareRandomXPos,
                                    squareRandomYPos,
                                    squareRandomXPos+50,
                                    squareRandomYPos+50) == true) {

            xTopsBotsYTopsBotsSquares.push([squareRandomXPos,
                                            squareRandomYPos,
                                            squareRandomXPos+50,
                                            squareRandomYPos+50]);
            console.log(squareRandomXPos, squareRandomYPos, squareRandomXPos+50, squareRandomYPos+50);
            checkingIfRepeatCords = false;
        }
    }
    while (checkingIfRepeatCords == true);

}

```

# Answer
> 1 votes
This code:

```
if (data[0] <= right || data[1] <= bottom ||
    data[2] >= left  || data[3] >= top)

```

should be:

```
if (data[0] <= right && data[1] <= bottom &&
    data[2] >= left  && data[3] >= top)

```

RULE:
| | -----\>OR
&& --\> AND

---
Tags: collision-detection, javascript, html-canvas
---


title: Check collisions in Stage among actors

text:
# Question
Title: Check collisions in Stage among actors
My goal is to check collisions among the actors that are in the Stage.

My question is: is it necessary to maintain a list for each type of actor I have?

Doing that I get 3 problems, 2 bad design problems and 1 exception.

Design problems I don't like:

1. The Actors used by the player add bullets (another Actor) to the stage. I need to pass my Stage to these Actors as argument in order to add a bullet to the list of bullets, that is held by the Stage.
2. Each time I need to add an Actor to the Stage, I have to perform 2 add operations, one in the list and one directly to the Stage.
3. If I check collisions iterating over the lists and I find out that an enemy (another actor) is dead, I need to remove the enemy both from the stage and from the list, but I can't remove it from the list because I get "Concurrent modification exception".

Is there some common design technique to handle this stuff?

# Answer
> 1 votes
While not necessarily the best solution, this is how I have overcome these problems with my game engine

1. I personally don't have a problem with passing the Stage to an Actor. Also, if the parent actor is already part of a stage you can also get the stage by calling

Actor.getStage()

For your physics engine, I suggest that instead of having a list represent your physics engine, you should create a physics engine class that handles the registration/deregistration of physics objects. This way, you can have it act as a gateway so that the list doesn't get modified directly by an actor.

If you really don't like passing in your stage and physics engine to every actor, an alternative is to implement some sort of messaging system where the Actor creating the projectile sends a message saying, "Hey! I created a projectile and here it is" and then have your physics engine and stage register to receive these messages so they can add the projectile accordingly. This can be done via static message handler classes or with the observer pattern.
2. You have to let both your physics engine and stage know that a new actor was created somehow. I understand the desire to make them work off of the same list, but it is likely that you will want some Actors that are drawn by the stage that aren't participating in the physics engine (like a hud). Even though you are doing two adds, you are adding the same object to both lists and thus not increasing your memory footprint.
3. This is a limitation of Java. It really doesn't like you messing with a collection while you're iterating over it.

During my collision detection in the physics engine, if an Actor dies, I don't remove it right then. Instead, I mark a flag on the actor that it is dead. Then, the first step of my physics engine the next time around (before collision detection), is to go through my list and get rid of all of the dead actors. That way, you aren't modifying the physics list while you are looping through it and detecting collisions.

Sadly, there isn't a really elegant way to loop through a list while removing its objects in java. The usually approach is to either loop through a copy of the list while removing from the real list or to keep a list of objects to be removed and then loop over it, removing the objects from the real list.

---
Tags: collision-detection, libgdx, architecture
---


# Question
Title: Turning my main(int argc, char** argv) cpp file into a class doesn't work
So, I needed to access variables from my main.cpp file in another cpp file, and the best solution for that (to me) was to make the main.cpp file a class.

Like this : (sorry for long codes...)

```
#include <iostream>
#include <SFML/Graphics.hpp> // Always use / instead of \ since \ is windows only!
#include <string>
#include <Box2D\Box2D.h>

#include "Player.h"
#include "Enemy.h"

class Game
{
public:

    sf::RenderWindow window;
    sf::Font font;
    sf::Clock clock;

    /// The number of enemies that ius going to spawn.
    const static int num_of_enemies = 2;

    /// Array of enemies on the map.
    Enemy enemies[num_of_enemies] = {

        Enemy(sf::Color(255, 0, 0, 255), sf::Vector2f(150, 150), sf::Vector2f(20, 20)),
        Enemy(sf::Color(255, 0, 0, 255), sf::Vector2f(225, 150), sf::Vector2f(20, 20))

    };

    // Window variables
    int WIDTH = 1024;
    int HEIGHT = 720;

    sf::Clock timeBetweenFrames;

    int main(int argc, char* argv[])
    {
        std::cout << "Loading..." << std::endl;

        if (!font.loadFromFile("Res/Fonts/arial.ttf"))
            std::cout << "Could not load font : arial.ttf" << std::endl;

        sf::Text text("I am text, not bread.", font, 15);

        sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), "SFML Engine");

        Player player = Player(sf::Color(0, 255, 0, 255), sf::Vector2f(50, 50), sf::Vector2f(25, 25));

        std::cout << "Loading done" << std::endl;

        // Game Loop
        while (window.isOpen())
        {
            sf::Time time = timeBetweenFrames.getElapsedTime();
            //std::cout << (time.asSeconds()) << std::endl;

            timeBetweenFrames.restart().asSeconds();

            sf::Event event;
            while (window.pollEvent(event))
            {

                switch (event.type)
                {

                case sf::Event::Closed:
                    window.close();
                    break;

                }
            }

            if (window.hasFocus())
            {
                if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
                {
                    player.move(-1, 0);
                }

                if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
                {
                    player.move(1, 0);
                }

                if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
                {
                    player.move(0, -1);
                }

                if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
                {
                    player.move(0, 1);
                }

            }

            // Drawing
            window.draw(text);
            window.draw(player.getPlayer());

            for (int i = 0; i < num_of_enemies; i++)
                window.draw(enemies[i].getEnemy());

            window.display();
            window.clear();

        }

    }

};

```

However, when I try to launch the game, visual studio 2015 gives me this error :

```
1>------ Build started: Project: SFML_Game, Configuration: Debug Win32 ------
1>  main.cpp
1>MSVCRTD.lib(exe_main.obj) : error LNK2019: unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)
1>C:\Users\MyName\Desktop\C++ Projects\SFML_Game\Debug\SFML_Game.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

```

I did some research though, none of the answers on how to fix it worked on me.

---

**Here's a list of things I tried :**

* Changing subsystem to console
* Checked my linker settings (which seemed alright, I think....)

---

And I can't figure out more things that I need to do.

This has probably been asked before, though I can't seem to find anything that help my specific problem.

# Answer
> 0 votes
`int main ( int argc, char* argv[] )` must remain as a global function.

If you want to access information somewhere else that you declaring in your main.cpp you may want to use `extern`. Try this:

in your main.cpp:

```
int WIDTH = 1024;
int HEIGHT = 720;

```

in your other file

```
extern int WIDTH;
extern int HEIGHT;

```

---
Tags: c++, visual-studio
---


title: Ingame notification - Windows Phone

text:
# Question
Title: Ingame notification - Windows Phone
Im working on a simple game for windows phone. There is one item in the game where the player can click on a enemy and shoot him. Well there is a 1:2 chance for the user to shoot the enemy and when he fails I want to tell this to the user. A Popup would stop the gameflow so I don't really want that. What are other possible ways to do that ? It doesn't need to be a lot of text just "Miss !" or "You missed !".

# Answer
> 0 votes
You are probably not looking to use a system notification (like a toast), but rather using some type of in-game notification.

For something that simple and self-contained, I would suggest just having the text appear in red (you might want to fade in and out) somewhere on the screen. That way, the user will get the necessary information without being completely distracted.

# Answer
> 0 votes
I would suggest, exactly as you said, simple text. Take the word **"Miss"** and have it in red, just have it pop up next to the enemy quickly for a moment, animate it to allow the user to see it and have it quickly move out of the way. That way they don't lose attention on the enemy but they know what happened.

---
Tags: c#, windows-phone-8
---


title: Unity: Model Construction on the fly

text:
# Question
Title: Unity: Model Construction on the fly
*So, forgive me if some of the terminology is wrong, I am just getting started with Unity again and I can't remember the proper names. I'm also on my phone, so I didn't have unity in front of me when I posted this question.*

I am beginning work on a voxel based game. Everything in the game will be models constructed of 64 by 64 cubes. I would like to, with the code given, say, a 4096 bit array, be able to construct a model in the game with those cubes. I know that you can programmatically add models that you have imported into unity, but I want to make contiguous meshes programmatically, with highest performance being the goal. I do not want a certain amount of little 1x1 cube meshes positioned right next to each other, but specifically one model.

**Is this possible?**

# Answer
I would suggest checking out AlexStv's Voxel Tutorial. It's written for C# in Unity3d, has been iterated upon several times, and covers everything from generating the meshes and texture up through setting up collisions and integrating a first-person camera.
> 1 votes

---
Tags: unity, models, 3d-meshes, voxels
---


# Question
Title: Combining several animations into a single FBX
I'm trying to figure out a workflow for preparing character animations for Unity so that they are all combined in a single FBX file. The advantage as far as I see it is that it then uses only a single skeleton where multiple animation files would each have their own skeleton (which I think is unnecessary and would increase size considerably).

I've tried using Maya for this but haven't been successful so far. Then I tried Motionbuilder and I can get the animations (takes) together into a single file but many of the animations don't look right afterwards.

So I was wondering does anyone know of a solid workflow to achieve this? I'm having a hard time finding information about what I'm trying to achieve. This is probably a piece of cake for experienced animators but I'm just starting with animation now.

So how do you combine several animation FBX files into single one (whith either Maya, Motionbuilder, or 3DSMax) and make sure that the animations are all properly retained like they should? I'm sure there are some additional things to take care of but I don't know exactly what they are.

# Answer
> 3 votes
I'm a bit late on this, but perhaps you can still use it or someone else might come across it.

### Exporting

First of all, if the animation look wrong when imported into your game engine, it can be a good idea to bake your animation before exporting. Animation baking can also be done during FBX export in Maya, however I'm not sure it works as well as baking in Maya beforehand under Edit \> Keys \> Bake Simulation.

Using an extension, you can also setup clips for FBX, which is how you could then have all your animation in one Maya file and similarly export it one, see this link.

If you prefer using Motionbuilder for combining the clips and the re-exporting, try baking the animation before exporting.

### Setup in Unity/Game Engine

Now for optimisation. I'm assuming you're using Unity based on other questions you've asked...

AFAIK, Unity will handle optimisation if you name and use it correctly. Let's assume you have a character called Soldier. What I would then do, would be to import a simple T-Pose of this character with no animation on and name the file Solider.fbx. For the walk animation I would name it Solider@walk.fbx, jump Solider@jump.fbx etc (see documentation here).

This Unity will only use one file and the model avatar, and only use the animation from the other files and apply that to the avatar. It doesn't import a new model and skeleton with each fbx file you import. See the documentation on Creating the Avatar and their video tutorials on the subject on Unity's website.

---
Tags: unity, animation, 3dsmax, maya, mecanim
---


# Question
Title: Ball's velocity vector, reflect against a point
I need to calculate the new velocity vector when the ball collides with one of the paddle's corners.

Let **d** be the velocity vector of the ball, **r** the target velocity vector and **n** the surface normal used for reflecting the velocity vector.

I found that the formula to calculate the reflection vector is: **r=d−2(d⋅n)n**

My first thought was to create a vector using the coordinates of the paddle's corner and the ball's center, normalize it and use it as my surface normal n.

That way I have both d and n that I need to calculate the reflection vector.

But, after some more research I've come across the following article: Pool Hall Lessons: Fast, Accurate Collision Detection Between Circles or Spheres

which may be better since ball - ball collision is the same as the ball - point collision that I need.

The collisions are all elastic and forces like gravity and friction don't exist.

Is my approach wrong? If I end up doing this in any of the aforementioned ways, what are the advantages and disadvantages of each one of them?

EDIT: I forgot to mention that the post i linked doesn't contain any collision resolutions, but only collision detections, but it is what made me to think that searching for ball - ball collision resolutions is a better approach.

# Answer
> 1 votes
Your approach is equivalent to the approach linked in the article (they go on to collision resolution in later pages)except you assume that the paddle has infinite mass (i.e. the collision does not change the velocity of the paddle) and that the paddle is stationary (i.e. the balls speed does not increase after the collision).

Looking at the equations provided in the article the final velocities for the two objects are dependent on the masses of the two objects. If the second object is given an infinite mass then they become,

**v1**' = **v1** \- 2(a1 - a2) * **n**

and

**v2**' = **v2**.

Due to their definitions of the velocities **v1** and **v2**, a1 = **v1** . **n** and a2 = **v2** . **n**. Due to the assumption that the paddle is stationary a2 = 0 and so final results are,

**v1'** = **v1** \- 2(**v1****n**) * **n**

which is the same as you calculated.

Note here I have used bold to distinguish vectors from scalars (also assumed some knowledge of vector maths as you demonstrated it in your question but happy to explain if not clear).

---
Tags: vector, collision-resolution, transformation
---


# Question
Title: Strange artifacting with textures (Pseudo 3D)
I'm using SFML to make a pseudo 3d engine (Technically not software rendered since SFML uses OpenGL) and things are going rather swimmingly, but then I tried to make another wall, the picture says everything:

The artifact gets worse the closer you get to the wall on the left.

And the Code...

```
#include "Quad3B.h"

Quad3B::Quad3B() {
    pos = sf::Vector3f(0, 0, 1);
    size = sf::Vector3f(1, 1, 0);
    shape = sf::VertexArray(sf::Quads, 4);
    c = sf::Color::Red;
    color = true;
}

Quad3B::Quad3B(sf::Vector3f p) {
    pos = p;
    size = sf::Vector3f(1, 1, 0);
    shape = sf::VertexArray(sf::Quads, 4);
    c = sf::Color::Red;
    color = true;
}

Quad3B::Quad3B(sf::Vector3f p, sf::Vector3f s) {
    pos = p;
    size = s;
    shape = sf::VertexArray(sf::Quads, 4);
    c = sf::Color::Red;
    color = true;
}

Quad3B::Quad3B(sf::Vector3f p, sf::Vector3f s, sf::Color c) {
    pos = p;
    size = s;
    shape = sf::VertexArray(sf::Quads, 4);
    Quad3B::c = c;
    color = true;
}

void Quad3B::loadTexture(string path, sf::Vector2f ts) {
    color = false;
    tex.setRepeated(true);
    tex.loadFromFile(path);
    texp = sf::Vector2f(ts.x * tex.getSize().x, ts.y * tex.getSize().y);
}

void Quad3B::dr(sf::Vector3f camPos, sf::RenderWindow &window, float hw, float hh, float rat) {
    bool draw = true;

    shape[0].position = sf::Vector2f((((pos.x + camPos.x) * rat) / (pos.z + camPos.z)) * hw + hw, (-(pos.y + camPos.y) / (pos.z + camPos.z)) * hh + hh);
    shape[1].position = sf::Vector2f((((pos.x + camPos.x) * rat) / (pos.z + camPos.z)) * hw + hw, (-(pos.y + size.y + camPos.y) / (pos.z + camPos.z)) * hh + hh);
    shape[2].position = sf::Vector2f((((pos.x + size.x + camPos.x) * rat) / (pos.z + size.z + camPos.z)) * hw + hw, (-(pos.y + size.y + camPos.y) / (pos.z + size.z + camPos.z)) * hh + hh);
    shape[3].position = sf::Vector2f((((pos.x + size.x + camPos.x) * rat) / (pos.z + size.z + camPos.z)) * hw + hw, (-(pos.y + camPos.y) / (pos.z + size.z + camPos.z)) * hh + hh);

    if (color) {
        shape[0].color = c;
        shape[1].color = c;
        shape[2].color = c;
        shape[3].color = c;
    }
    else {
        shape[0].texCoords = sf::Vector2f(0, texp.y);
        shape[1].texCoords = sf::Vector2f(0, 0);
        shape[2].texCoords = sf::Vector2f(texp.x, 0);
        shape[3].texCoords = sf::Vector2f(texp.x, texp.y);
    }

    if (pos.z + camPos.z < 0) { draw = false; }
    if (draw) { if (color) { window.draw(shape); } else { window.draw(shape, &tex); } }
}

Quad3B::~Quad3B() { }

```

# Answer
> 3 votes
It seems you are projecting your 3D-coordinates into 2D-Space by yourself. So the 3D information is lost for any HW-acceleration. You need to supply 3D- information to your Positional Coordinates I think you can use sf::Vector3f and just use your z-coordinate as 3rd entry.

PS: Funny detail: you just implemented affine texture mapping which was the best thing people could do 20 years ago :)

---
Tags: opengl, 3d, sfml
---


# Question
Title: Calculating rotation matrix for an object relative to a planets surface in MonoGame
I have a 3D planet and I would like to place models on the planet and have them start with a base rotation relative to the planet surface at their location. So a model at the north pole will have zero rotation, and one at the south pole will be upside down etc.

I have some code that kind of works but not very well so i guess that there are errors with the math. I'm trying to calculate the Pitch based on the angle between the location and Y axis, and the Roll based on the angle between the location and X axis.

Can some one please help get the rotation calculation working?

```
public Matrix CalculateBaseRotation(Vector3 vLocation)
{
   // Calculate Up Direction (Assumes planet position is Vector.Zero)
   Vector3 WorldUp = Vector3.Normalize(vLocation);

   // Compute Dot Products relative to Y and X axis
   float Dot_A = Vector3.Dot(Vector3.UnitY, WorldUp);
   float Dot_B = Vector3.Dot(Vector3.UnitX, WorldUp);

   // Calculate Angles From Dot Products
   float Angle_A = (float)Math.Acos(Dot_A);
   float Angle_B = (float)Math.Asin(Dot_B);

   // When Z is negative, invert Angle A to prevent curve following S pattern
   // This seems hackish, there must be a more mathematically elegant solution
   if (WorldUp.Z < 0)
       Angle_A = MathHelper.TwoPi - Angle_A;

   // Invert Arc Of AngleB
   if (WorldUp.Y > 0)
       Angle_B = MathHelper.TwoPi - Angle_B; // Keeps curve to planet surface
   else
       Angle_B = Angle_B + MathHelper.Pi; // Prevent flipping upside down in southern hemisphere

   // Clamp Angles
   Angle_A = MathHelper.WrapAngle(Angle_A); // PITCH
   Angle_B = MathHelper.WrapAngle(Angle_B); // ROLL

   // Create Base Rotation Matrix
   // AngleA Should Be Second, AngleB Should Be Third
   return Matrix.CreateFromYawPitchRoll(0, Angle_A, Angle_B);
}

```

# Answer
Something like this is often easier if you avoid using angles.

The following assumes you know the world coordinates of the center of the planet and the world coordinates of the location on the planet surface that you want to place the object .

```
Matrix GetWorldMatrixForModel(Vector3 surfaceLocation, Vector3 planetCenter)
{
  Vector3 modelUp = Vector3.Normalize(surfaceLocation - planetCenter);
  Vector3 tempCross = Math.Abs(Vector3.Dot(modelUp, Vector3.Up)) > 0.1 ?   Vector3.Up : Vector3.Right;
  Vector3 modelRight = Vector3.Normalize(Vector3.Cross(ModelUp, tempCross));
  Vector3 modelForward = Vector3.Cross(modelUp, modelRight);

  Matrix modelWorld;
  modelWorld.Up = modelUp;
  modelWorld.Right = modelRight;
  modelWorld.Forward = modelForward;
  modelWorld.Translation = surfaceLocation;

  return modelWorld;
}

```
> 2 votes

---
Tags: xna, rotation, monogame
---


# Question
Title: Checking 2 instances of the same object in GameMaker
There are 2 blocks. If the player stands on a block, some sound should loop and when he gets off it should stop.

Problem is, The game checks both the objects and when player is on 1 block, obviously he is not on other, so checking this it stops the sound, never letting it play(sound).

```
if place_meeting(x, y-1, obj_player)
{
   if !audio_is_playing(snd_cart)
        {
             audio_play_sound(snd_cart, 10, true);
        }
}
else
    {
        audio_stop_sound(snd_cart)
    }

```

This is the code please help me on this

# Answer
A possible solution is to add a new property to your block object that store whether or not the player is on the block, then tweak the logic so the sound only starts/stops if the player gets on/off.

:Create

```
isPlayerOn = false

```

:Step

```
if place_meeting(x, y-1, obj_player) {
    if !isPlayerOn {
        isPlayerOn = true
        if !audio_is_playing(snd_cart) {
            audio_play_sound(snd_cart, 10, true)
        }
    }
} else {
    if isPlayerOn {
        isPlayerOn = false
        audio_stop_sound(snd_cart)

    }
}

```

(The reason for nesting the `if`s as I've done is to avoid unwanted side effects.)
> 1 votes

# Answer
Put this code on obj\_player and let the obj\_player check the collision and play the sound. Other turnaround would be global variables, but this is not a good solution.
> 0 votes

---
Tags: game-maker
---


# Question
Title: Mobile Game - Do I need visual feedback?
I am currently on a game for windows phone 8.1 where the user can use items. If the user tries to use a item which he doesn't own a sound gets played. If now a user plays without sound or listens to music it might be that he doesn't realize that he tries to use it without realizing why it won't work.

Should I make a visual feedback?

# Answer
You already answered your own question:

> If now a user plays without sound or listens to music it might be that he doesn't realize that he tries to use it without realizing why it won't work.

That's the most important reason.

Games feel better when audio and visual feedback are combined.
> 12 votes

---
Tags: user-experience, visualization
---