title: OUYA and Unity set up problems

text:
# Question
Title: OUYA and Unity set up problems
I'm having trouble with the Unity / OUYA plugin.

I'm using Unity 4 with the latest update on a Windows 7 machine.

When I open the starter kit and try to compile the plugin I get the following error:

> Picked up \_JAVA\_OPTIONS: -Xmx512M

And if I try to Build and Run I get this error:

> Error building Player: ArgumentException: Illegal characters in path.

I'm stumped, I've gone through lots of forum posts here and on stackoverflow and I can't seem to resolve it.

My environment variables look like this:

```
PATH - C:\Users\dave\Documents\adt-bundle-windows-x86_64-20130219\sdk\tools;
       C:\Users\dave\Documents\adt-bundle-windows-x86_64-20130219\sdk\platform-tools\

JAVA_HOME - C:\Program Files (x86)\Java\jdk1.6.0_45\

```

Everything in the OUYA Panel is white

Any ideas?

# Answer
In the latest version of the Unity plugin, the Java/Native plugin comes pre-compiled. So there's no longer the need to build the Java or native portion of the plugin in the OUYA Panel. Just import the Core plugin and you'll be ready to File-\>Build and Run for the Android platform.

You can find the latest Core plugin here: https://github.com/ouya/ouya-sdk-examples/releases/tag/Unity-OuyaSDK-Core

Most recently the core plugin adds support for your Unity plugin on Forge TV.
> 1 votes

# Answer
Don't have an OUYA so just a wild guess, but it might be a memory problem. Try checking https://confluence.atlassian.com/display/CONF29/Fix+Out+of+Memory+errors+by+Increasing+Available+Memory and see if that helps. Perhaps you have to increase the assigned memory by adding some parameter value.
> -1 votes

---
Tags: unity, ouya
---


title: c++ Opengl handle elements drawn

text:
# Question
Title: c++ Opengl handle elements drawn
I am currently working on a game and I want to know if there is any way of handling with the elements i am drawing . For example : if i draw in a loop 100 cubes , how can i show / hide the cube number 15 or 63 or n ... clicking I thought that initializing elements in a list would work , but i didn't find any property of it that could help.

```
GLuint cube;
cube = glGenLists(1);

 glNewList(cube,GL_COMPILE);

for(int i = -30; i < 3; i++) {
     for(int j = -30; j < 3; j++) {
        glPushMatrix();
        glTranslatef(i*2.0,0,j * 2.0);
           Dcube();

        glPopMatrix();
     }
 }
 glEndList();

```

***I googled a while for deleting elements after displaying them*** , like in minecraft , but i couldn't find anything useful(e.g: When **mouse - right click** -\> then create cube , and when **mouse - left click** -\> then delete the cube.. ) Some sugestions would be all i need .. ...Thank you.

# Answer
> 4 votes
The only way to not draw something is to, well, not draw it.

If your display list (a deprecated feature as glampert points out) draws 100 cubes and then a player "deletes" one of those cubes then your only option is to delete that display list and generate a new one.

With modern rendering techniques, you'd refill a vertex buffer with all the active cube instances. When a cube is added or removed you refill the buffer. That simple.

Given a simpler architecture with legacy techniques utilizing the "immediate" rendering API, just don't draw the element. In your loop, only draw the cubes that still exist. You can do this easily with an `if` statement:

```
// some global or something
int cubes[MAX_HEIGHT][MAX_WIDTH];

// drawing code
for(int i = -30; i < 3; i++) {
    for(int j = -30; j < 3; j++) {
        if(cubes[j][i] != EMPTY) { // IMPORTANT PART
            glPushMatrix();
            glTranslatef(i*2.0,0,j * 2.0);

            Dcube();

            glPopMatrix();
        }
    }
}

```

Again, that's a deprecated and highly inefficient way to draw things, but that's about as simple as you can get. Once you wrap your head around the basics you'll be able to learn the more modern and efficient ways to renders large numbers of voxels/cubes.

You'd also use that `cubes` array to determine what kind of cube to draw (dirt, stone, grass, etc.) as well as various other properties of each voxel.

# Answer
> 2 votes
You are using OpenGL Display Lists, which is a deprecated feature. One of the reasons they were dropped from the standard is that once created, a list cannot be modified. In your current setup, you have only two choices: 1) recreate the whole list every time something is changed; 2) just use direct immediate-mode drawing.

In the long run, a better option would be for you to switch to modern, shader-based OpenGL and use **Vertex Buffer Objects** instead. Performance will be *much better* and the restrictions of Display Lists no longer apply.

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


# Question
Title: Distance between two lines (textbook answer vs practical application)
I'm reading through "Mathematics for 3D Game Programming, and Computer Graphics" as a refresher, and leading in to some more complex real world problems down the line. However, one of the early chapters has a bit of math that seems overly complicated. This question deals with a problem from the textbook, that I believe the solution is far simpler than their recommended one.

The problem is to find the distance between two lines (in 2 or 3 dimensions).

Some set up:

1) Lines are set up parametrically as opposed to two points.

Line 1:

Line 2:

Where P = S + tV -- S is the starting point (say, A) and equals (1-t) * A

---

Now the book states to use this solution :

Expanded looks like:

Then the books next step is to reduce this, and take the derivatives with respect to time for both

and

Once the derivatives have been calculated. We move to a matrix form, and solve using some linear algebra.

---

My question is this, why would I use that series of steps when I already know the \[ x, y, z \] for both points using the parametric. With those values wouldn't the simpler solution be just to do:

Then:

Finally:

Is there some direct application of the former equations that I am missing (the book does not elaborate currently on its applications here)? I've had some discussion with other game developers, and we haven't found much a use case for the linear algebra set up.

---

Edit: (The linear algebra solution)

First both derivatives with respect to time:

Then in matrix form, solve for both t variables:

# Answer
Your `V = Vb - Va` is a function of two variables `t1` and `t2`, and so is your `sqrt(V·V)`. You cannot minimise that value without analysing a function of `t1` and `t2` of some sort, which is what the author does. It’s complicated because it’s a difficult problem, but it’s not *overly* complicated.
> 1 votes

---
Tags: linear-algebra
---


# Question
Title: Handle two different touch gestures at same time without overlapping
I'm trying to create a Character touch controls for 2d platform.

In my script Im using one horizontal swipe and hold touch gesture and one vertical swipe gesture without hold.Both are different methods called in `void Update ()`.

And here is my script :

```
void Update ()
    {

        HorizontalSwipe();
        VerticalSwipe ();

    }

    void HorizontalSwipe()
    {
        foreach (Touch FingerTouchx in Input.touches)
        {
            if(FingerTouchx.fingerId<1)//         FINGERID

            {
                //if(FingerTouchx.position.x < Screen.width/2)

                if(FingerTouchx.phase == TouchPhase.Began)
                {
                    FingerInitialPositionx=FingerTouchx.position.x;

                }

                else if(FingerTouchx.phase == TouchPhase.Moved)
                {
                    FingerMovedPositionx=FingerTouchx.position.x;

                    if(FingerMovedPositionx>FingerInitialPositionx)
                    {
                        charcter.transform.Translate(Vector2.right * speed * Time.deltaTime);
                    }

                    else if(FingerMovedPositionx<FingerInitialPositionx)
                    {
                        charcter.transform.Translate(-Vector2.right * speed * Time.deltaTime);
                    }

                }

                else if(FingerTouchx.phase == TouchPhase.Ended)
                {
                    FingerInitialPositionx=0f;
                    FingerMovedPositionx=0f;

                }

                else
                {

                    FingerMovedPositionx=FingerTouchx.position.x;

                    if(FingerMovedPositionx>FingerInitialPositionx)
                    {
                        charcter.transform.Translate(Vector2.right * speed * Time.deltaTime);
                    }

                    else if(FingerMovedPositionx<FingerInitialPositionx)
                    {
                        charcter.transform.Translate(-Vector2.right * speed * Time.deltaTime);

                    }

                }

            }

        }
    }

    void VerticalSwipe()
    {
        foreach (Touch FingerTouchy in Input.touches)
        {

            if(FingerTouchy.fingerId<1)      //         FINGERID

            {
                //if(FingerTouchy.position.y > Screen.width/2)

                if(FingerTouchy.phase == TouchPhase.Began)
                {
                    FingerInitialPositiony=FingerTouchy.position.y;

                }
                if(FingerTouchy.phase == TouchPhase.Moved)
                {
                    FingerMovedPositiony=FingerTouchy.position.y;

                }
                if(FingerTouchy.phase == TouchPhase.Ended)
                {
                    if(FingerMovedPositiony>FingerInitialPositiony)
                    {
                        charcter.transform.Translate(Vector2.up * speed * Time.deltaTime);
                    }
                    if(FingerMovedPositiony<FingerInitialPositiony)
                    {
                        charcter.transform.Translate(-Vector2.up * speed * Time.deltaTime);
                    }
                    FingerInitialPositiony=0f;
                    FingerMovedPositiony=0f;

                }

                else
                {}

            }
        }
    }

```

Problem:

1:When i swipe and hold horizontally the character moves fine but when i take my finger back it triggers the vertical swipe method.

2:When i try to swipe only vertically the horizontal swipe is also triggered.

3: The two swipe gestures are overlapping and triggered at same time on a Single touch.

Solution(Guess):Dividing the touch screen equally half and forcing horizontal touch gestures strictly on left side of touch screen and vertical touch gestures on right side.

But I'm beginner(You can see my coding style) and would like to know how to do it programatically. Im still learning.

# Answer
> 1 votes
You actually want to split screen into two to get gesture **Horizontal** and **Vertical**. So use `Screen.width` for this purpose. You are checking `position.y` in vertical, which is not correct. You have check `X` in either case. Here is modified code with 2 touches.

```
void Update ()
{
    HorizontalSwipe();
    VerticalSwipe ();
}

void HorizontalSwipe()
{
    foreach (Touch FingerTouchx in Input.touches)
    {
        if(FingerTouchx.fingerId<2)//         FINGERID

        {
            if(FingerTouchx.position.x > Screen.width/2)
            continue;

            if(FingerTouchx.phase == TouchPhase.Began)
            {
                FingerInitialPositionx=FingerTouchx.position.x;
            }

            else if(FingerTouchx.phase == TouchPhase.Moved)
            {
                FingerMovedPositionx=FingerTouchx.position.x;

                if(FingerMovedPositionx>FingerInitialPositionx)
                {
                    charcter.transform.Translate(Vector2.right * speed * Time.deltaTime);
                }

                else if(FingerMovedPositionx<FingerInitialPositionx)
                {
                    charcter.transform.Translate(-Vector2.right * speed * Time.deltaTime);
                }
            }

            else if(FingerTouchx.phase == TouchPhase.Ended)
            {
                FingerInitialPositionx=0f;
                FingerMovedPositionx=0f;
            }

            else
            {
                FingerMovedPositionx=FingerTouchx.position.x;

                if(FingerMovedPositionx>FingerInitialPositionx)
                {
                    charcter.transform.Translate(Vector2.right * speed * Time.deltaTime);
                }

                else if(FingerMovedPositionx<FingerInitialPositionx)
                {
                    charcter.transform.Translate(-Vector2.right * speed * Time.deltaTime);

                }
            }
        }
    }
}

void VerticalSwipe()
{
    foreach (Touch FingerTouchy in Input.touches)
    {
        if(FingerTouchy.fingerId<2)      //         FINGERID

        {
            if(FingerTouchy.position.x < Screen.width/2)
            continue;

            if(FingerTouchy.phase == TouchPhase.Began)
            {
                FingerInitialPositiony=FingerTouchy.position.y;
            }

            if(FingerTouchy.phase == TouchPhase.Moved)
            {
                FingerMovedPositiony=FingerTouchy.position.y;
            }

            if(FingerTouchy.phase == TouchPhase.Ended)
            {
                if(FingerMovedPositiony>FingerInitialPositiony)
                {
                    charcter.transform.Translate(Vector2.up * speed * Time.deltaTime);
                }
                if(FingerMovedPositiony<FingerInitialPositiony)
                {
                    charcter.transform.Translate(-Vector2.up * speed * Time.deltaTime);
                }
                FingerInitialPositiony=0f;
                FingerMovedPositiony=0f;
            }

            else
            {}
        }
    }
}

```

---
Tags: unity, unityscript, mobile, touch, control
---


# Question
Title: How to set up a game loop for a project targeting iOS?
I'm a fellow game programmer who's done many game engines in Game Maker 8.1, Visual Studio XNA and MonoGame with C#, and one in Java Android with Eclipse. I'm very used to C# and love it plus the VS environment.

Now I'm trying to develop games for the App Store for iPhone and iPad (using Xcode 7 with a Macbook running Yosemite 10.10.5). I don't yet have an actual iPhone to test with, but the simulator is working with the blank and example projects I've found.

By way of googling, this is what I've looked at so far:

http://codewithchris.com/xcode-tutorial/

http://www.raywenderlich.com/40293/learn-to-code-ios-apps-2-strings-arrays-objects-and-classes

There was also a Storyboard example which I did not like. My intuition is to not use a wizard for anything, and the Storyboard builder seemed a lot like Windows Forms when I can just use the XNA draw functions.

Neither of those tutorials was very helpful and now I'm paranoid that I'm on the wrong track. Now I'm asking myself questions like should I be using SpriteKit or SceneKit? Should I be using Swift insteada Objective-C?

The thing is, if I can figure out how to draw pictures in a game loop, then I think I'm all set. However, I think I understand that I'm gonna need at least one UIView or Scene. What I want is a `master_draw()` function that gets called 30 times per second in main.m, and in `master_draw()` I loop through all objects and call their individual draw functions. Same thing with a `master_update()` function.

And I also found this open source example: https://www.cocoacontrols.com/controls/1w-flappy

That example...I thought it would be the most helpful of all. But I couldn't find any game loop in it at all.

Am I on the right track? Does iOS stuff work totally different than a traditional game loop?

Specifically, I have 2 major questions:

* **What new project type should I chose?** Blank, Single-View, or Game?
* **How to set up a game loop? (if possible)**

What I'm thinking is something like this:

```
void master_update() // typically called 30 or 60 times per second
{
  foreach (GameObj G in ListOfGameObj)
    G.update(); // update all objects in the list of objects
}

```

and of course...

```
void master_draw() // typically called 30 or 60 times per second
{
  foreach (GameObj G in ListOfGameObj)
    G.draw(); // draw all objects in the list of objects
}

```

Where do I add that code and where do I call it? Is something like this possible in iOS or am i gonna hafta use a completely different architecture?

P.S. The kind of game I'm doing is a simple 2D puzzle where you hafta match up blocks. Nothing too fancy.

# Answer
For a 2D puzzle game for iPhone and iPad, SpriteKit would be the easiest way to do this. SpriteKit is made especially for developing 2D games. You don't have to bother creating a scene graph, how to draw images to the screen or how to create a game loop. It is already there, ready for you to use it.

Start with creating a new project from the *Game* template and choose SpriteKit. This will already provide you with a basic scene and handlers to create spinning space ships when tapping on the screen. (Just test it by running the game.)

Drawing an image is as easy as creating an `SKSpriteNode` object, setting its position and adding it as a child to the scene or some other node in the scene graph. E.g.

```
let pieceOfThePuzzle = SKSpriteNode(imageNamed: "puzzle")
pieceOfThePuzzle.position = CGPoint(x: 100, y: 200)
node.addChild(pieceOfThePuzzle)

```

would add the `pieceOfThePuzzle` to the node `node` at position (100, 200) and it will be automatically drawn in the next frame. SpriteKit will automatically find and load the correct image for you.

Also, there will already be an `update` method that is run before drawing the next frame. This should be enough for you to get started.

As for Swift vs. Objective-C: If you already have a preference for one of the languages, use that. If not, use Swift. Swift is newer, easier to learn and more powerful in my opinion.
> 2 votes

# Answer
1- Well, I have not a huge experience in IOS native development. But if you want it in environment like other Game Engines then I would recommend you to use SpriteKit. You can get start from this tutorial.

2- If you want to set Game Loop in normal `Objective-C` environment, you can set `NSTimer` with custom frequency like,

```
NSTimer myTimer =[NSTimer scheduledTimerWithTimeInterval:0.03
    target:self
    selector:@selector(gameLoop)
    userInfo:nil
    repeats:YES];

-(void)gameLoop{}

```

And it is a good practice to Deactivate this timer when you get done with this, by,

```
[myTimer invalidate];
myTimer = nil;

```
> 1 votes

# Answer
+1 for the answers so far, but I just don't like SpriteKit. I don't understand sprites that are apparently also objects and worse, are automatically drawn somehow. I need to see code. I need to see code that I actually wrote, or at least actually called the library function. Otherwise I feel like I don't have complete control over what is being drawn, when it's changed, when the object disappears even tho the object may not have been destroyed, etc. As a rule of thumb, a fully functional language such as Swift can do this without having to learn another language within a language (wizard or SpriteKit UI or something), and it's the way I've been programming for years.

Therefore I decided to answer my own question in the hopes that other programmers similar to me will get off to the right start.

Who am I? A C# programmer who's made many games/apps/simulations in XNA and MonoGame using Visual Studio. Up until a few days ago, I had never touched a Mac or iOS languages. I love C# and thought iOS programming in Objective-C would be similar. Boy was I wrong. And regarding other options, why use SpriteKit or SceneKit when you can just use the native draw functions? (called Quartz I believe, but that threw me off. Quartz is just the native Swift drawing library as far as I can tell.) That would be like learning another language within a language when you're already trying to learn Objective-C or Swift.

If that's who you are, then this answer is for you:

**Use this tutorial** to setup your new iOS game and learn how to draw. In particular, you want a "Single View App" (not "Game"!). The tutorial makes a new class called Draw2D that has the main drawing function. It shows how to draw primitives such as lines, and at the end it shows you how to draw pictures. Violla! No SpriteKit wizards necessary that you have no idea about anyway! Pretend the Draw2D class is your "main" class and put your main variables and object lists/arrays in there. This will make it very easy to reference all objects, which are created and stored in arrays or lists.

**Absolutely use the Swift language!** Do **not** use Objective-C! (This will force you to target iOS versions no earlier than 7, but that's definitely old enough to let a lot of phones run your game). Swift is native iOS code and similar to C# but with different arrangements in the syntax. Objective-C is basically stone-age C hacked to unreadable dangers. Just from looking at it, I'm pretty sure you can blow your own legs off by going out-of-bounds during file writes or array traverses...just like plain C. Yes this is my opinion, but if you're reading this answer, you're hopefully like me.

**Learn what ! and ? do.** Not even I am 100% sure yet, but basically, Swift does not allow objects to be null (nil) by default---unless you explicitly say they can with a '?' at the end of the variable name at instance declaration. Same thing with functions returning an object. Use '!' to force the language to not do any safe nil checking when accessing the object. For some reason the compiler is gonna require this on certain accesses to your object. Just be safe and always manually do `if (MyObj != nil)` first.

You need to **set up a NSTimer** to automatically call your draw function every x seconds. This is very important! **Don't skip this huge paragraph!** Find the code here or just copy this: `var timer = NSTimer.scheduledTimerWithTimeInterval(0.033, target: self, selector: "draw_now", userInfo: nil, repeats: true)`. Make sure the timer is a part of Draw2D. See here's the thing. For some reason, the custom UIView we created in the tutorial only gets called once or twice at the beginning, so we need a timer to call it again and again. I wanted 30 fps so I used 0.033 for the interval (so it will get called once every 0.033 seconds). But there's a trick to this. The timer needs to call a selector; it's the string parameter. **But don't make this your default drawRect() function!** Instead, make a new function called `draw_now()` like I did, so the NSTimer parameter should be "draw\_now", no parentheses, and in draw\_now() (a function of Draw2D) put this sole line of code: `[setNeedsDisplay()]`. Type that exactly, including the brackets. That's the trick! That code somehow forces the UIView to redraw itself by calling the `drawRect()` function. I have no idea why, but if you set up your timer to call drawRect() like I mistakenly did at first, it just doesn't work. drawRect() gets called again and again, and you can check that in the debugger, but things just don't get drawn for mysterious reasons having to do with bizarre and ungainly things called contexts. Anyway, you have to call a function with a single line of code: `[setNeedsDisplay()]`. And that code goes and does magical things to make the system call drawRect() with the right context. Many thanks to stackoverflow at this link for that code.

In my main draw function (drawRect()), the first thing I did was call `master_update()`, which is my own function I made. It basically loops through all the arrays of objects and calls their individual update functions. The point is, with this setup, **the timer effectively runs the update loop and the draw loop, which are therefore in sync.** I always want in-sync updates and draws in my games, though you may want it differently. Personally I've never found a reason to use variable draw rates, and keeping it in sync makes things so much simpler.

**Access the touch functions** so you can control what happens when a user touches the screen. Go to this youtube video and jump to 2:40, where he begins overriding the `touchesBegan` function. Make sure this overridden func is in your Draw2D class.

**Each class needs its own constructor, and Swift is picky about it.** I had trouble with this because Swift allows many weird types, such as `required`, `convenience`, `delegate`, and others. The one foolproof constructor I found was `required init?(parameter1: parametertype1, parameter2: parametertype2, etc)`. All my classes used this as the one and only constructor that the compiler did not complain about. Even Draw2D had this same single constructor, but it needed a weird parameter: `required init?(coder aDecoder: NSCoder)`. Not sure what that was all about. **However**, your constructor may need to call `super.init()` at the end, which may have its own parameters too. I think the super thing is for subclasses that inherit parent classes, so you have to call the parent's constructor too. This is apparently necessary before using `self` (which would be `this` in C#) in your constructor.

**Go here and learn about drawing points.** Not pixels. Points. They are different things in the Mac world. This is not how we do it on desktop PCs, but so far I haven't had much trouble. Apparently it's pretty useful to draw consistently to different devices with different screen resolutions. It gave me a fairly straightforward way to just scale everything to fit the screen, which is the quick and dirty way I wanted to support multiple devices for my first iOS game. By the way, you can do this with `var screen_width = UIScreen.mainScreen().fixedCoordinateSpace.bounds.width`, which gives you the width of the actual screen in points. (Unfortunately, this will force you to target iOS 8 and above, which means less iPhones will support your app. I have not yet found a different way to do this while staying compatible with iOS 7. **But according to this, it's not much to worry about.**) Then if you want a 20x12 grid, each square will be `screen_width/20`.

**Now you are finally ready to program 99% the same way you did in XNA and MonoGame!** All your objects have their own `update()` and `draw()` functions, and in the main update you just iterate through each object in your array and call `MyObj.update();` Same thing with the draw.

Keep in mind I'm using a Mac Book running Yosemite 10.10.5 on Xcode 7 with the Swift Language. Who knows what could happen, if anything, on later versions.
> 0 votes

---
Tags: ios, objective-c
---


# Question
Title: Storing color and position (height and width) in an array which can be changed accordingly (bubble shooter)
How can I store the colors and position (i.e the position of the balls in bubble shooter game) using an array? I first tried using a simple loop but I think it won't work when I need the balls to burst so the balls should be printed using arrays. Here is my simple code

```
DrawLine( 380 , 60 ,   mx ,  my,10,  colors[BLACK]);
DrawRectangle( 1,89 ,799,500 , colors[WHITE]);
DrawRectangle(0 , 0,330 , 90 , colors[WHITE]);
DrawRectangle(430, 0, 380  , 90  , colors[WHITE]);

int zig=0;

int wide1=25;
int high1=574;

for ( high1 ; high1>=80 ; high1=high1-50){
    for (wide1 ; wide1<=780 ; wide1= wide1+50 ) {
        DrawCircle(wide1 , high1 , 25 , colors[WHITE]);
    }
    zig=zig+1;
    if (zig%2==0){
        wide1=25;
    } else {
        wide1=50;
    }
}

```

# Answer
> 1 votes
Even if they looks like bubbles, they are exagons :

so you can use a bidimensional array as stated here to represent hexagons:

> The simplest way to represent a hex grid with a 2D array is to skew your axes: each row of hexes is offset by half a step more than the previous one. It doesn't matter whether each row is offset forward or backward, as long as you're consistent about it; below, each successive row is offset half a hex forward:

```
(0,0) (0,1) (0,2) (0,3) (0,4)

   (1,0) (1,1) (1,2) (1,3) (1,4)

      (2,0) (2,1) (2,2) (2,3) (2,4)

         (3,0) (3,1) (3,2) (3,3) (3,4)

```

See also Hexagonal Grids as reference.

---
Tags: collision-detection
---


# Question
Title: Google Games Services Display Orientation
I'm developing a game using LibGDX and I'm using `BaseGameUtils` to implement Play Games Services in it. It's working very well. But my game is in landscape mode, so when I call leaderboard or achievements it opens up in landscape mode. I don't want that. I want the games services to open in portrait only. There's no entry of BaseGameUtils in my manifest file and I checked the Android Manifest file in BaseGameUtils module, but there's no `<activity>` in there.

How can I change the orientation when games services is displayed?

# Answer
Try `setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);` in your activity.
> 0 votes

---
Tags: android, libgdx, google-play-services, orientation
---


# Question
Title: Is my collision-free location script working?
I've recently been learning C# and I wanted to take one of my 2D tutorials to Unity.

I reached a step where I need to spawn my new sprite into a collision free location. I've followed direction - generated random location, calculating Vector2s using the location and collider, and then used a while loop to check Physics2D.OverlapArea using my 2 vectors.

But, because I'm still only just learning C#, I'm finding it difficult to know if I have actually written my code correctly. Is there any simple way of being able to figure this out? Using Debug or something?

```
Vector3 spawnLocation = new Vector3 (Random.Range (minSpawnX, maxSpawnX),
                                     Random.Range (minSpawnY, maxSpawnY),
                                     -Camera.main.transform.position.z);
Vector3 spawnPoint = Camera.main.ScreenToWorldPoint (spawnLocation);
Vector2 lowerLeftCorner = new Vector2 (spawnPoint.x - teddyBearColliderHalfWidth,
                                       spawnPoint.y - teddyBearColliderHalfHeight);
Vector2 upperRightCorner = new Vector2 (spawnPoint.x + teddyBearColliderHalfWidth,
                                        spawnPoint.y + teddyBearColliderHalfHeight);
while (Physics2D.OverlapArea (lowerLeftCorner, upperRightCorner) != null)
{
    spawnPoint.x = Random.Range(minSpawnX, maxSpawnX);
    spawnPoint.y = Random.Range(minSpawnY, maxSpawnY);

    lowerLeftCorner = new Vector2 (spawnPoint.x - teddyBearColliderHalfWidth,
                                   spawnPoint.y - teddyBearColliderHalfHeight);
    upperRightCorner = new Vector2 (spawnPoint.x + teddyBearColliderHalfWidth,
                                    spawnPoint.y + teddyBearColliderHalfHeight);
}
Debug.Log (Physics2D.OverlapArea(lowerLeftCorner, upperRightCorner));

```

I was trying to use a debug at the end there, but it doesn't seem to continue running every single time that there's a spawn, so I am still unsure if it is working. I'm terribly sorry for my nooby code. Feel free to direct to me some place else if you feel I need to do so.

# Answer
Of course you can check the syntax automatically using an IDE like Visual Studio. However, without some more work the only measure of correctness is "does it do what you expect?" If it doesn't, then you would debug to find out why.

Of course, you can take it a step further and apply Unit Testing. This is where you write code that sets up scenarios where you know there will be an expected result. For example, if you had a method like

```
int Add(int left, int right) { return left + right; }

```

you could write unit tests like

```
bool TestAdd() { return Add(2, 2) == 4; }

```

You then run all these tests in a separate mode and take note of which ones fail, or you can use an external project that links in your code to run all the methods. Most Unit testing APIs like NUnit provide decorations so their test engines can automatically extract, run, and gather results from your tests.

Check out "Unit Tests By The Book" part 1 and part 2 on the Unity Blog.
> 1 votes

# Answer
Work Smarter not harder! For this you can do a simple trick. Drop empty `GameObjects` in the environment where you want to spawn your sprite. Take them in a public `List` or `Array` and Spawn at the random `GameObject's Transform` of `List` or `Array`. For visibility drop cubes instead of empty GameObjects and after setting them disable their mesh and colliders.
> 1 votes

---
Tags: unity, collision-detection
---


title: Very less vertical transformation

text:
# Question
Title: Very less vertical transformation
Im using pretty basic code here

```
charcter.transform.Translate(Vector2.up * speed * Time.deltaTime);

```

Im using rigidbody 2d and I'm creating a platformer. When i press the button the character transforms very little in y axis.

# Answer
> 1 votes
Why are you not using Physics when you have rigidbody? Try

```
float _jumpForce = 200;
charcter.GetComponent<Rigidbody2D>().AddForce(new Vector2(0,_jumpForce));

```

---
Tags: unity, rigid-body-dynamics, jumping
---


# Question
Title: What is the most efficient technique for range detection?
I have a bunch of patrolling enemies that fire projectiles when the player is in projectile range - a specific radius. Which method is the most efficient and elegant?

1. overlapSphere
2. sphereCast
3. triggers
4. square magnitude
5. anything else?

I am using Unity.

# Answer
> 1 votes
I haven't actually done any profiling, but the off-hand guestimate based on the way the physics engine should be optimized and some knowledge on the approximate complexity of various operations, my suggestion is:

Because you have *one* player, it will be very cheap for each of your enemies to check the square magnitude during their update tick. Very very cheap. Although it does go against the idea that the enemies shouldn't always know where the player is. But for a quick-and-dirty check prior to more intensive checking, it will work.

However, this won't necessarily be good for objects that have to check against multiple actors. E.g. an automatic door that opens whenever a guard patrols by it, or the player gets near. Or in a game I'm working on, guards that attack any intruder. And the player isn't always the only intruder (nor are the other intruders necessarily friendly to the player!). So what I do is:

1. first do a overlapSphere. overlapSphere is cheap. The physics engine is likely performing a squareMagnitude call on every collider in the scene (there are other optimizations, such as maintaining a quadtree of the scene, so it doesn't have to check *every* collider, just some, as well as having a good layer mask; a bitwise AND will be faster than squareMagnitude) and returns a list of the ones that passed.
2. For every collider returned, do a frustum check. This will vary by enemy, some can only see in front of them, some can see in all directions, but not very far up and down (e.g. can't see above themselves), another can only see above and below, but not horizontally. This is pretty cheap.
3. Finally, on the remaining colliders, perform a raycast. Raycasts are expensive (relative to any of the above methods), but super accurate. sphereCast (and capsuleCast) also falls into this category, but is more useful for knowing if an object of a given size will reach. Good for knowing if an AI can walk down a narrow passage or fit under a low hang. But a small sized sphere in a sphereCast might be "friendlier" to the player than a raycast, as it means they can peek out around corners a little more (the larger the sphere the more they can peek out).

You can get away with a lot of raycasts in a frame without bogging down the FPS, but you definitely don't want every enemy performing a raycast on every ally every frame. Its just not needed. As the game I'm working on is a stealth game, I actually perform 5 raycasts: one against the center of the player (as you're going to be doing) and then four more towards approximated corners of the player's bounding box (relative to the enemy's view direction), which does the opposite of the spherecast I mentioned earlier: it makes it tougher on the player to stay out of sight. I have other mechanics in place to avoid this being harshly punishing (not only does the player have to be visible, the AI needs to perform a successful ID verification to recognize the player as hostile and the results are cached for a couple of seconds, avoiding even more raycasts: the raycast is irrelevant if the AI already "knows" that the player isn't hostile!).

All of this said, however:

Unless you're seeing a problem with frame rate, you're likely performing a premature optimization. For your usage, overlapSphere (followed by a raycast so things don't try to shoot through walls, assuming that's relevant) will be the best. Cheap enough and accurate enough to be good enough.

Watch your profiler and make optimizations based on where the lag is *coming from*. Often it will be from something you don't expect. (Hint: manage your garbage well).

# Answer
> 0 votes
I have used Raycasts in most cases, this is because it applies well in a lot of cases, fast rendered, exact, and easy to debug.

Raycast documentation

Little tutorial on Raycasting

Although I find that using some of your above called options a good choice in some situations like; \- Whenever I build a maze like game, I use triggers to trigger doors/events. \- With a racing game I mostly use overlapping colliders to detect it, since this would be less aggresive on your performance and racing games aren't always known for the best collision detection (not including multi million games like GRID.)

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


# Question
Title: All GameObjects and Models are Transparent
Whenever I create a new game object its completely transparent, with the Mesh Renderer selected.

This is really frustrating as I am new to Unity and Google offers no solutions.

# Answer
> 2 votes
I suspect your Default-Material is somehow messed up. The little preview in the lower right looks wrong.

Try this:

In Unity, go to `Assets > Create > Material`. Make sure the Shader is set to "Standard" and the Rendering Mode is set to "Opaque". Now select your cube and apply the material in Element 0 of the `MeshRenderer`'s "Materials" list.

Also, I see you have an Editor folder. Check if you have any Editor scripts that are adjusting materials. If this doesn't work, I'd re-install Unity because everything else looks correct.

---
Tags: unity
---


title: How to Detect Mesh Segmentation?

text:
# Question
Title: How to Detect Mesh Segmentation?
I have a mesh like this (it's all a single mesh):

How I can figure out that the one floating piece is completely disconnected from the rest of the mesh?

# Answer
As Jaakko Lipsanen said above, it's likely much simpler to detect this elsewhere in your code (from raw voxel data, or from the code that mutates the world).

However, if you *do* decide to work from mesh data alone, as long as you're not trying to compute this on a per-frame basis, there are lots of ways to do this.

Normally you'd check for connectivity using breadth- or depth- first search. However in the case of a mesh, you typically do not have the data in a convenient form for that. I.e., to do a BFS/DFS you'd want to start at a vertex and traverse one or more of its edges, but given a vertex you don't directly know the edges. What you *do* know is the triangles.

To leverage this, I think instead of a normal graph connected-ness search, I think I would solve this using something similar to a flood fill. https://en.wikipedia.org/wiki/Flood\_fill

(I believe there's a proper name for the algorithm below that is not 'flood fill', but I can't recall what it is right now, and Google's not helping.)

**Approach overview:**

* Iterate over all triangles
    + Assign vertices to a "connected set" according to the following:
        - If the vertices are all unassigned, create a new set and assign them to it.
        - If only one vertex has been assigned, assign all of them to that set.
        - If there are two or three sets represented,
            * pick one to be the new merged set ID,
            * assign all the vertices to it,
            * do bookkeeping to merge all the vertices into that set.

Here's an **unoptimized, uncompiled, untested** partial implementation. Set merging can be made O(1), but for clarity using an O(n) merge. The HashSets aren't necessary in a tighter implementation, but again, clarity. Overall with the O(n) merge, this is O(n^2). That might be fine if the meshes are small-ish and you're not running it often.

O(1) merge is pretty straightforward - just stop overwriting setIDs every iteration, and instead maintain set ID equivalence hashsets. Then if you need, you can make one final pass to rewrite all the ids to one per "set set", which would still be O(n).

```
private void determineMeshConnectedness(Mesh mesh){
    // setIDs records which set each vertex belongs to
    // at the end of the algorithm
    // 0 means unassigned
    int[] tris = mesh.triangles;
    int[] setIDs = new int[mesh.vertexCount];
    int nextSetID = 1;
    HashSet<int> activeSetIDs = new HashSet<int>();
    HashSet<int> triSetIDs = new HashSet<int>();

    for(int i=0; i<(tris.Length-2); i+=3){
        triSetIDs.Clear();

        // get the sets this triangle touches
        triSetIDs.Add(setIDs[tris[i]]);
        triSetIDs.Add(setIDs[tris[i+1]]);
        triSetIDs.Add(setIDs[tris[i+2]]);

        // ignore 'unassigned' set
        triSetIDs.Remove(0);

        if(triSetIDs.Count == 0){
          // create new set, assign all vertices to it
          createNewSet()
          activeSetIDs.Add(nextSetID);
          setIDs[tris[i]] = setIDs[tris[i+1]] = setIDs[tris[i+2]] = nextSetID;
          nextSetID++;
        } else if(triSetIDs.Count == 1){
          // assign each vertex to the single set found
          IEnumerator<int> hse = triSetIDs.GetEnumator();
          hse.MoveNext();
          setIDs[tris[i]] = setIDs[tris[i+1]] = setIDs[tris[i+2]] = hse.Current;
        } else {
          // merge the sets, store set they were merged into
          int combinedSet = mergeSets(triSetIDs);
          setIDs[tris[i]] = setIDs[tris[i+1]] = setIDs[tris[i+2]] = combinedSet;
        }
    }

    // At this point, activeSetIDs should contain the list of connected mesh IDs
    // And setIDs marks which set each vertex belongs to

    // do whatever with this information
}

// lots of ways to do this
// this one is O(n) in the number of vertices
// returns the set ID everything was merged into
private int mergeSets(HashSet<int> triSetIDs){
    IEnumerator<int> hse = triSetIDs.GetEnumerator();
    hse.MoveNext();

    // choose to merge into first set ID, arbitrarily
    int finalSet = hse.Current;

    // update now-dead set IDs to new set
    for(int i=0; i<setIDs.Length; i++){
        if(hse.contains(setIDs[i])){
            setIDs[i] = finalSet;
        }
    }

    // remove dead sets from active list
    while(hse.MoveNext()){
        activeSetIDs.Remove(hse.Current);
    }

    return finalSet;
}

```

Hope this helps. Let me know if you find any bugs, or if it doesn't work at all!
> 2 votes

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


# Question
Title: Math.Clamp won't limit my position until movement is ceased
The program is in a top down view, with Y going up (or forward depending upon how you see it), and X going from left to right based on the camera view. I am attempting to set the minimum and maximum values of my main character's x/y-axis movement through the float "clamp", under the struct "Mathf".

When my ship passes the minimum/maximum value on either axis, it doesn't stop it. If you release the movement key after passing the point, the character will appear directly on the minimum/maximum point that was passed. See the gif below.

Gif here http://gph.is/22fdHv4

Below is the current script running for both player movement and the boundary, attached to the main character.

```
using UnityEngine;
using System.Collections;

public class ShipMovement : MonoBehaviour {

public float xMin;
public float xMax;
public float yMin;
public float yMax;
public float speed = 2f;
public float shotSpeed = 4f;
public float nextFire1;
public float nextFire2;
//Animator anim;
public GameObject shot;
public Transform shotSpawn;
public float fireRate = 0.25f;

void Start () {

//anim = GetComponent<Animator> ();
}

void FixedUpdate () {

        GetComponent<Rigidbody> ().position = new Vector3 (
            Mathf.Clamp (transform.position.x, xMin, xMax ),
            Mathf.Clamp (transform.position.y, yMin, yMax),
            0.0f
        );

        if (Input.GetKey (KeyCode.W)) {
        transform.Translate (Vector2.up * speed * Time.deltaTime);
        //anim.SetBool ("moving", true);
    }
        if (Input.GetKey (KeyCode.S)) {
        transform.Translate (Vector2.down * speed * Time.deltaTime);
        //anim.SetBool ("moving", true);
    }
        if (Input.GetKey (KeyCode.A)) {
        transform.Translate (Vector2.left * speed * Time.deltaTime);
        //anim.SetBool ("moving", true);
    }
        if (Input.GetKey (KeyCode.D)) {
        transform.Translate (Vector2.right * speed * Time.deltaTime);
        //anim.SetBool ("moving", true);
    } else {
        //anim.SetBool ("moving", false);
    }

    if (Input.GetKey (KeyCode.Space) && Time.time > nextFire1)
    {
        nextFire1 = Time.time + fireRate;
        Instantiate(shot, shotSpawn.position, shotSpawn.rotation);
    }

    if (Input.GetKey (KeyCode.X) && Time.time > nextFire2) {
        nextFire2 = Time.time + fireRate;
        Instantiate (shot, shotSpawn.position, shotSpawn.rotation);
    }

    if (gameObject == null) {
        Application.Quit ();
      }
   }
}

```

Although I am not sure, I suspect it may have something to with the way I am controlling the movement. I have had issues with what I have written in the past, especially with animations and moving left/right while also moving up/down. (Hence why I have all of the animation code commented out, and I am using a Capsule instead of a ship).

If anything else is needed, I can provide it.

# Answer
> 1 votes
Set the position after you calculate that it is inside your bounds. This will also account for pressing multiple keys at the same time.

```
Vector3 newPosition;

if (Input.GetKey (KeyCode.W)) {
    newPosition = transform.position + Vector2.up * speed * Time.deltaTime;
    //anim.SetBool ("moving", true);
}

GetComponent<Rigidbody> ().position = new Vector3 (
    Mathf.Clamp (newPosition.x, xMin, xMax ),
    Mathf.Clamp (newPosition.y, yMin, yMax),
        0.0f
);

```

# Answer
> 1 votes
**Updated**

I can observe more than one reason. May be **Before After**, may be this is due to `vector3.x` or `vector3.y` cannot be modified in c#.

First of all kindly change `FixedUpdate` to `Update`. And from now please don't get inputs in `FixedUpdate` otherwise you will get Jerks in getting input. Now Replace your whole `FixedUpdate` to these lines of code.

```
void Update(){

    transform.position = new Vector3(Mathf.Clamp(transform.position.x + Input.GetAxis("Horizontal") * speed,xMin,xMax), Mathf.Clamp(transform.position.y + Input.GetAxis("Vertical") * speed,yMin,yMax), transform.position.z);

    if (Input.GetAxis("Horizontal") || Input.GetAxis("Vertical"))
        anim.SetBool ("moving", true);
    else
        anim.SetBool ("moving", false);

    if (Input.GetKey (KeyCode.Space) && Time.time > nextFire1){
        nextFire1 = Time.time + fireRate;
        Instantiate(shot, shotSpawn.position, shotSpawn.rotation);
    }

    if (Input.GetKey (KeyCode.X) && Time.time > nextFire2) {
        nextFire2 = Time.time + fireRate;
        Instantiate (shot, shotSpawn.position, shotSpawn.rotation);
    }

    if (gameObject == null) {
        Application.Quit ();
      }
}

```

# Answer
> 0 votes
Well. That's because you clamp the values *before* accounting for the keys being pressed. So the position is clamped to the bounds, then the player moves out of bounds.

---
Tags: unity, c#, 2d
---


# Question
Title: Help With Rotating Turret and Muzzle Flare Sprites
I am making a top down game that involved tanks rotating their turrets and firing at other tanks.

I have the turrets rotating independently of the tank itself about the center. However, I am now trying to rotate a muzzle flare sprite animation around with the turret.

I am struggling with keeping the muzzle flare at the end of the barrel when the turret rotates.

Here is the two sprites lined up at position (0, 0):

And here is the position I would like the muzzle flare to be at:

The problem is, the muzzle flare does not maintain the offset (45, 8) when the turret rotates.

I have tried using the equations:

x2 = x * cos(theta) - y * sin(theta)

y2 = x * sin(theta) + y * cos(theta)

Where x = 45 and y = 8.

But I have had no luck.

Where is my math wrong?

# Answer
I assume your flare is positioned correctly at the coordinates (45, 8) with respect to the origin of the tank turret. The problem then should be that the flare does not move along with the turret even though it's orientated correctly. You need to offset the flare with the same offset as the tank turret after rotation.

Example pseudo-code:

```
tx, ty;  // Turret's points.
fx, fy;  // Flare's points.

// Offset the flare with respect to the turret's origin.
fx = fx + 45;
fy = fy + 8;

theta; // The angle the turret is rotated by.

// Rotate both the turret and the flare.
txr = tx * cos(theta) - ty * sin(theta);
tyr = tx * sin(theta) + ty * cos(theta);
fxr = fx * cos(theta) - fy * sin(theta);
fyr = fx * sin(theta) + fy * cos(theta);

wtx, wty; // Turret's world coordinates.
tx = txr + wtx;
ty = tyr + wty;
fx = fxr + wtx;
fy = fyr + wty;

```

Generally speaking if you want to attach something to something else so that it transforms (moves, rotates, scales, etc.) with the object it's attached to. What you do is you transform your attached object to where you want it to be relative to the original object, and make sure this object is not transformed by any means. Then when you perform a transformation on the original object you also perform a identical transform on the attached object.

Or said specifically. First move and rotate the flare to where you want it on the tank, this is your *new flare*. Whenever you rotate and move your tank, apply that movement and rotation to your *new flare* as well. This gives the illusion of the flare sticking to the tank.

If you wanted to rotate the turret around the turret's center; here is one easy solution. First position the flare without changing the turret or do anything different from above. Then if you want to rotate the turret around a point A, just move the turret so that the point A is at the origin, then do the rotation. And remember any transformation you do to the turret you also do to the flare, so move and rotate the flare by the same amount.

You could say that the flare inherits its transformation from its parent, the turret in this case. If your world were more complex, like the flare had a sparks animation attached to it, then the sparks would inherit its transformation from the flare, which again gets its transformation from the turret which probably gets its transformation from the tank. So you get a tree-structure of parents and children with the world being the root node. So whenever the tank moves 1 unit right, so does the turret, and in turn the flare, and in turn the sparks. So it all moves together. If you rotated only the turret, only its children would be affected, and their children again, and so on... (the flare and the sparks, here)

Note: Remember that all coordinates and rotations in the children are defined in their parent's space, which may or may not be the world/root.
> 0 votes

---
Tags: mathematics, rotation
---


# Question
Title: How do I stop my timer when I close my game?
**Background:**

**I have a background service with a timer. It opens up a new activity when 20 seconds are over.**

Currently, my app is using `componentCallbacks2` to detect when the user has pressed the home screen, or has left the app, and on detection, I stop the timer, so that the activity doesn't get called.

But, for some reason, `componentCallBacks2` does **not** get called when the user just closes out of the app:

Here you can see the user closing an app. **For some reason, my app doesn't stop its processes when the app is closed.** And, the timer continues to run. **This results in the activity popping up on the users screen after 20 seconds, even though the user isn't in the app.**

How can I detect if the app has been closed so that I can stop the timer? I have read on this topic in many other sources, and those sources just say to use the `onStop` method. **I can't do that, because the `onStop` gets called whenever there is a change in activities**

So, where should I stop the timer?

---

Image source.

# Answer
From Android documentation:

> An operation running on an IntentService can't be interrupted

Anyway, there is still a solution based on preventing the launch if your app is closed:

**1/ In your app**

Pass your application pid in the "extra" part of the Intent used to launch the background task.

To get you app pid :

```
android.os.Process.myPid();

```

**2/ In the background task process**

When your task is finished (the 20 seconds have passed), check if the app is still runnning before launching the Activity

```
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> pids = am.getRunningAppProcesses();

for (int i = 0; i < pids.size(); ++i)
    if (pid == pids.get(i).pid) {
        // Launch your activity because your app is still runnning
    }

```

assuming that the variable "pid" is the pid that came in the intent extra data.
> 1 votes

---
Tags: java, android
---


title: Object orbiting a 3d sphere

text:
# Question
Title: Object orbiting a 3d sphere
I'm developing in libgdx java/android but not using any high-level environment like Unity.

I have a sphere at \[0,0,0\], with a PerspectiveCamera looking at it. Through the main game loop I have managed to have the camera orbiting the sphere in different directions. However, what I want to do is have a stationary camera and have 3 objects orbiting the sphere on their own accord, and their own orbital plane. Have been looking all day and struggled to get this working.

Eventually, I want to link the camera to always be above one of the orbitting objects, but that's at a later stage.

I also want to be able to have these objects orbitting on their own "forwards" direction, but able to change their direction over time. Say, from their top-down view, they each have a heading 0-359 degrees.

Anyone lend a hand with this? I've tried using 2D X/Y maps transposing onto mercator projections and then converted to spherical coordinates; I've tried Vector3 and `setFromSpherical()`; I've tried looking at Quaternions, and just got lost.

It's a relatively simple thing I'm trying to do, multiple orbiting objects around a sphere (radius 3, origin \[0,0,0\]), but just getting my initial approach wrong.

**EDIT:**

After talking the situation through, I have two options: I either keep track of the orbiting objects with theta/phi as to their position around the sphere, or just calculate the amount by which to rotate based on the object's direction (0-359). On further talks with DMGregory, the latter option would introduce orbital instability/divergence with roudning errors so I have decided to change my requirement to the following:

* Keep track of the object's position based on 2x360 degree values for azimuth and polar, called theta and phi. The two coordinates are used to locate the object at any point in orbit around the sphere, but I need to be able to still "move" the orbital object "forwards" and thus change theta/phi accordingly, allowing the direction to still be changed.

Many thanks,

# Answer
The parametric equations of circular motion are:

```
circle_x = radius * cos(rate * time + phase) + center_x
circle_y = radius * sin(rate * time + phase) + center_y

```

So all you really need to do is rotate this into an arbitrary 3D plane.

You can do this by providing two orthonormal basis vectors (meaning they are perpendicular and have a length of 1) u and v, and forming a weighted sum of them using the equations above as weights, essentially trading the fixed x & y axes for the axes of your choice:

```
orbit_position = circle_x * u + circle_y * v

```

This is equivalent to forming a rotation matrix or quaternion describing the orientation of each orbital plane and using it to transform an orbit in some simple reference plane, like

```
orbit_position = rotation * (circle_x, circle_y, 0)

```

You can choose u and v (the orientation of the orbit plane) however you like. One simple approach for polar orbits would be:

u = (cos(longitude), 0, sin(longitude)) v = (0, 1, 0)

By construction these are orthonormal, and allow you to rotate the orbits freely along one axis as you describe. All orbits of this form cross above two poles of the sphere (though you can avoid collisions by adjusting the phase or radius parameters)
> 2 votes

# Answer
Thanks DMGregory. I had to reply to my question rather than comment on your reply, as I need 50 rep to comment.

I can understand in theory what you're describing, however just having an issue applying that in my code.

Say I have the following `move()` method which is called every frame. It is used to calculate the new positions of just one object that will eventually orbit the sphere:

```
public void move(float delta) {
    //Check for keys
    if(Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
        this.objectDirection -= 5;
    }
    if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
        this.objectDirection += 5;
    }
    if (this.objectDirection > 360) {
        this.objectDirection = 0;
    }
    if (this.objectDirection < 0) {
        this.objectDirection = 360;
    }

    ....
}

```

I am storing the position of my object in `object3DPosition` which is a Vector3 type (in java libgdx), so say initially \[0,0,-5\]. Later after this 3D vector has been rotated, I set the posiiton of the object with:

```
modelInstanceObject.transform.setToTranslation(object3DPosition);

```

Now it's the inbetween bit which I'm struggling with. I'll use your code in the middle part "...." such as:

```
float speed = 1; //to adjust
//The parametric equations of circular motion:
double circle_x = RADIUS * Math.cos(Math.toRadians(delta * speed)); //+ center_x (rotate about origin anyway)
double circle_y = RADIUS * Math.sin(Math.toRadians(delta * speed)); //+ center_y (rotate about origin anyway)

//Rotate this into an arbitrary 3D plane.
Vector3 u = new Vector3(1,0,0);
Vector3 v = new Vector3(0,1,0);

//Vector3 orbinPosition = u.mul(circle_x) + v.mul(circle_y);
Vector3 orbitPosition = u.scl((float)circle_x).add(v.scl((float)circle_y));

//set new position
object3DPosition.set(orbitPosition);

```

Not sure If that's the correct implementation, however movement is still not as expected.

Many thanks
> 0 votes

---
Tags: libgdx, 3d, mathematics, orbit
---


# Question
Title: Collision problem with multiple tiles (rectangles)
**I think that I found what the problem is, see below**

So I'm working on a collision system and I use multiple tiles in my project, each with a collision box. The player also has a collision box.

I'm testing this collision method so it's not done yet (very basic). I had another collision method in the past but it only worked for one tile and used a lot of booleans so I decided to make a new method.

This is my collision method in my `SpriteManager` class:

```
public void Collision(List<PlayerMovement> playerCollision, List<TileSprite> tileCollision)
{
    // For each sprite in the tileCollision list
    foreach (TileSprite t in tileCollision)
    {
        // For each player (head, body, legs) in the playerCollision list
        foreach (PlayerMovement p in playerCollision)
        {
            if (p.collisionRect.Intersects(t.bCollisionRect))
            {
                // Collision methods
                player.CollisionPlayer(p, t);

                // TileBase collision method not used in this test version
                tileBase.CollisionBlock(t);
            }

            if (!(tileBase.bCollision.Any(c => player.collisionRect.Intersects(c))))
            {
                p.ground = false;
            }
        }
    }
}

```

I basically need to place the player outside the collision block of the tile (now with testing version only above the tile), but when there are multiple tiles next to each other, then the overlapping rectangle changes because it's a simple variable (see below).

This is my collision method in my `PlayerMovement` class:

```
public override void CollisionPlayer(PlayerMovement p, TileSprite t)
{
    rect2 = Rectangle.Intersect(p.collisionRect, t.bCollisionRect);
    p.position.Y = p.position.Y - rect2.Height;
    p.jumping = false;
    p.ground = true;
}

```

You can see that it's really simple (for now). I make a new rectangle that consists of the intersection of the tile rectangle and the player rectangle and then I subtract the `rect2` (new rectangle) height from the player position.

This works fine when the player collides with one tile, but he rapidly jumps up and down one pixel (position - lag, not performance) when he collides with more rectangles at the same time. I think this is because the collision method makes a new `rect2` and overwrites the old one because the `rect2` is only an overlapping of 2 rectangles. But I do not know how to fix this.

Images:

(**NOTE**: These images are the lagging behavior of the player when he collides with two tiles at the same time. The right image is how it should be. (it is like this with one tile))

**PROBLEM**: I think the problem is that only **ONE** overlapping rectangle is being made because the collision saves the overlapping rectangles all in the same variable (not in a list or an array, so it is overwritten). The problem I have now is that I don't know how to expand the overlapping rectangle to two or more tiles **OR** how to make multiple overlapping rectangles for this collision method.

# Answer
**I found the answer to my own problem:**

I now use 4 different colliding rectangles on the player (and one base rectangle). Each rectangle represents a different side of the player so I can see on which side he collides with a block.

Then I calculate the difference in height (y) or width (x) and I return the position of the player with that x, y.

**Images:**

-\> This is the player on two tiles.

-\> This is the player on two tiles with the colliding boxes visual.
> 0 votes

---
Tags: c#, collision-detection, visual-studio
---


title: Calculate Jump Limits

text:
# Question
Title: Calculate Jump Limits
My question is in a similar vein to this question, I am creating a pre-mapped pathfinding solution much akin to how Ash Blue was for my 2D platformer-style game (in XNA). As part of the process, I have to be able to 'neighbor' nodes in the pathfinding algorithm. To be able to do this, I need a procedural manner to precalculate the maximum capabilities of motion from a given game object at a given location. I am having a difficult time with one specific aspect of this: I cannot, for the life of me, figure out how to test whether or not a game object will be able to successfully jump to a given platform from where they are standing. I know there's a way to express this in some manner of equation, but I cannot find what the proper equation would be, it's probably in the vein of projectile physics, but the answer eludes me. If anybody can shed some insight into the matter, I would be very grateful.

# Answer
I tried to tackle this myself but got stuck, fortunately math.stackexchange came to the rescue with this question.

**Summary**

Given a particle which starts at position `(0,0)` and is fired at velocity `v_max` the maximum range it can achieve is,

```
x_max = Sqrt(v_max^4 / g^2 - 2 * v_max^2 * y_fin / g)

```

where `g` is the acceleration due to gravity (for earth `g ~ 9.81`) and `y_fin` is the final height of the particle (e.g. the height of the platform it needs to reach. This maximum range is achieved when the particle is fired at an angle,

```
theta = Atan( (1 - 2 * y_fin * g / v_max^2)^(-1/2) )
      = Atan( Sqrt(1 / ((1 - 2 * y_fin * g / v_max^2)) ),

```

where `Atan` is the inverse `tan` function.

**Note**

If desired I can explain in more detail how to achieve this result (as after seeing the approach in the linked question I was able to solve it myself) it requires knowledge of differentiation and trigonometric identities but is not too difficult.
> 1 votes

---
Tags: physics, path-finding, jumping
---


# Question
Title: Intellisense with PhaserJS Library in Visual Studio Code
I am trying to use Visual Studio code along with PhaserJS but am confused about why the isn't working.

I've read through http://www.johnpapa.net/intellisense-witha-visual-studio-code/ am think I am doing it correctly but still don't get auto-complete. When Phaser gets a green underline and lightbulb, the bulb doesn't include a create reference so I created one above manually.

# Answer
> 1 votes
Try pointing Visual Studio Code to the TypeScript definition:

`/// <reference path="../../../phaser/typescript/phaser.d.ts" />`

You will likely have to correct the path, of course. That got rid of the green underline for me, and now tab completion and CTRL+SPACE works.

---
Tags: javascript, phaser
---


# Question
Title: Can I use the idea of grappling hook and wingsuit from just cause 3 and use it in my game?
I really liked the idea of grappling hook and wingsuit, and I am inspired by it.And I have already created the model,texture,animation,script which are required for it by myself.So,my simple question is that can I use it in my game?

# Answer
> 1 votes
Grapling hooks have been used before just cause 3. Think of the legend of zelda series. Wingsuits have been used in ssx, and are quite similar to the delta hanger in far cry.

This is like asking 'can I use cars in my game or will rockstar, the maker of gta, sue me?'. Yes, you can use them. Just make everything yourself. Don't use anyone elses models, textures or code or any other property without their approval.

Ideas are not property.

Fyi: I'm not a lawyer. Technically, anyone can sue you for pretty much anything. Even if you win, going to court is expensive.

---
Tags: copyright
---


# Question
Title: How can I "squeeze" a game object when it is pressed between two others?
I am trying to "squeeze" a game object when it's pressed between two other objects (e.g., "squeezer 1" and "squeezer 2," below) that continue to move towards eachother.

I wish to reduce width of the object so that total area of the game object is maintained *while still being between the two squeezers*.

How can I achieve this effect?

# Answer
This effect is very easy to produce in Unity using a couple of Box Colliders, and some basic math. The effect will ressemble the following:

This is a very simple model for this problem. First you need 3 gameobjects added to your scene. Each object will contain a BoxCollider2D and a RigidBody2D with gravity removed.

The blue boxes just have a simple update method to move them in a static direction, for the purpose of the demo.

The orange box, checks if a collision is currently occurring. If it is colliding, Unity automatically stops the objects from overlapping each other, as they already have a BoxCollider2D attached.

The only thing you need to do, is determine if the box is being pushed on both sides. If it is only being pushed on one side, then do nothing. If it is being pushed on both ends at the same time, then you adjust the size of the box, while retaining its total area.

So to start, calculate the total area of your orange box:

```
public float Area;
bool PushedLeft, PushedRight;
float ForceLeft, ForceRight;

void Start () {
    Area = transform.localScale.x * transform.localScale.y;
}

```

Then, determine if it is being pushed on both ends at the same time:

```
void OnCollisionStay2D(Collision2D coll) {

    //Check all points of contacts occuring on this object
    for (int i = 0; i < coll.contacts.Length; i++) {

        //Is the collision occuring to the left of box?
        if (this.transform.position.x > coll.contacts[i].point.x)
        {
            //Is it pushing in? or pulling out?
            Vector2 diff = coll.contacts[i].point - coll.contacts[i].normal;
            if (diff.x < 0)
            {
                PushedLeft = true;
                ForceLeft = 0.1f;
            }
        }
        //collision occuring to the right of box
        else if (this.transform.position.x < coll.contacts[i].point.x)
        {
            //Is it pushing in? or pulling out?
            Vector2 diff = coll.contacts[i].point - coll.contacts[i].normal;
            if (diff.x < 0)
            {
                PushedRight = true;
                ForceRight = 0.1f;
            }
        }
    }
}

```

Then, if it is being pushed on both ends, Squeeze it so that it alters its shape:

```
void Update () {

    //Adjust box if being squeezed
    if (PushedLeft && PushedRight) {
        float squeezeForce = ForceLeft + ForceRight;
        float x = transform.localScale.x - squeezeForce * Time.deltaTime;
        float y = Area / x;
        transform.localScale = new Vector2 (x, y);
    }
}

```

Hoping this helps out someone else that would like to figure out this problem.
> 27 votes

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


title: FollowPath steering behavior

text:
# Question
Title: FollowPath steering behavior
I'm having a problem with AI movement in my top-down game. AI builds path and than moves using libgdx *FollowPath* (this problem is still actual) steering behavior. I have some solutions, but can't guess whitch is better(or I even need other solution). FollowPath params:

```
followp = new FollowPath<Vector2, LinePathParam>(this,
            new LinePath<Vector2>(path));
    followp.setPredictionTime(0.08f);
    followp.setArriveEnabled(true);
    followp.setArrivalTolerance(0.001f);
    followp.setDecelerationRadius(40f);
    followp.setTimeToTarget(0.1f);

```

**Problem**. Character doesn't move straightly according to the path - cuts corners through obstacles. **Solution 1**. Find right proportion between character speed/acceleration, character size, obstacles size. Curent parameters: *maxLinearSpeed = 100; maxLinearAcceleration = 150; maxAngularSpeed = 15; maxAngularAcceleration = 30; characterRadius=40; obstacleSize=120 (width and height)*. But if acceleration and speed are too big, character will move like "on rails" and even sticks on corners. Too small - character will be skidding.

**Solution 2**. Write own FollowPath steering behavior, whitch requires character to get close enough to *every* point of the path (without using *predictionTime*,that prevents sticking, but allows cutting corners) and using Arrive on every point of the path, that won't allow skidding.

**Solution 3.** Use RaycastObstacleAvoidance with FollowPath together(Priority steering). Here comes another problem: cause of raycasting character shakes (especially when it needs to turn around near wall or just target is near wall). Probably, it is solved by usage of lower angular acceleration (causes skidding).

# Answer
> 1 votes
## Example Solution - Car Game

We have our map and on each of the corners of said map, there is a small circle and a turning angle. The AI will check if the car's collision box is within this circle; it will have a small delay then gradually turn the car towards the turning angle of the corner. Depending on the difficulty these variables will be changed (High = Small delays, Faster turning toward angle etc.).

This will allow for the AI to be able to turn single corners but now what if the road forks and there are 2 possible directions, the car would only be able to go in one allowing the player relatively easy driving as they will have one empty road. Here there are multiple solutions but here are 2 that I've thought of:

* The circle will be paired with the number of forks instead and each time a car reaches the circle, a random number will be generated and depending on this number, the car will turn toward that turn using the aforementioned method.
* You could have an array of angles that each of the turns has. Whenever the car reaches the point, it finds the distance between the car's current bearing and the angle in which the turn is and whichever is shortest is picked by the AI and the car will turn toward it.

Sorry for the lack of detail, written in a hurry but I hope it helps! ~ Ammar T

---
Tags: java, libgdx, path-finding, steering-behaviors
---


# Question
Title: Why do my .wav sound effects delay before playing the first time on iOS?
First off, I'm using Unity 5.2.3. I have a bunch of .wav sounds that I play like this:

```
     Debug.Log(m_audioAssets.m_soundBanks[(int)m_currentSoundBank].m_multiplier[data].loadState);
     m_multiplierSource.clip = m_audioAssets.m_soundBanks[(int)m_currentSoundBank].m_multiplier[data];
     m_multiplierSource.Play();

```

The Debug.Log is just there temporarily, to verify that the sounds' loadState is "loaded". It is, every time they play. But the first time they play on my iPhone, there is a noticable delay before they start. After playing the first time, they work fine.

What am I supposed to do to get these sounds to preload properly? I have their "Preload Audio Data" boxes checked in the import settings, and they're set to "Decompress on Load".

# Answer
It was not the sound. It was the score `Text` object updating, which has a problem on iOS if your font is set to Dynamic. Lesson: always check the profiler before trying to fix performance issues.

The big spike in the image is the first call to changing the score, and you can see that `Font.CacheFontForText` takes a long time.
> 2 votes

---
Tags: unity
---


title: Unreal Engine Player Quality

text:
# Question
Title: Unreal Engine Player Quality
I had to force Unreal to use my integrated graphics card because VR wasn't working with my NVidia card.

When I did this, the framerate dropped terribly and it popped up a dialogue "Frame rate's bad, would you like to lower quality?" Which I said yes to.

Now, I've set it to use my NVidia card again, but it's stuck in this low quality state. It seems to be tied to the engine, not the project. All my 4.9 projects run in this garbage state, but my 4.10 projects are fine.

How can I reset the engine player settings for 4.9?

# Answer
> 3 votes
I figured it out.

Window\>Toolbar if you don't already have the toolbar up.

Settings\>Engine Scalability Settings\> Whatever scale level you like. Evidently, that dialogue set this value to Low. I put it back up to Epic, and it's all good.

---
Tags: graphics, rendering, unreal
---


title: Clearing memory from variables?

text:
# Question
Title: Clearing memory from variables?
So, I've heard of the `delete` keyword, which clears variables that use the `new` or `new[]` keywords.

I have a class called `Box`, which I made a object of in my `main.cpp`.

What if I want to clear a variables memory in my `Box` object, from my `main.cpp`?

I've tried adding the `new` keyword to the variables, but the variable types has no default constructor so I can't use it on them :

```
b2Body* body = new b2Body;

```

Is there any way to clear the memory of a variable that looks like this :

```
b2Body* body = nullptr;

```

(note that when I want to clear it, it has assigned a value to it.)

---

Example : In minecraft when an item is dropped on the ground, and it disappears after some time, I'm guessing it's texture variables, animations, stats etc is not saved?

This is what I want to do.

I want to remove the memory of a variable I no longer need to use.

# Answer
A great tutorial on constructors and destructors in C++ is this one.

Summary:

```
//Constructor uses binary scope operator on itself but with parameters
ExampleClass::ExampleClass(void) {
    std::cout << "Creating example class!" << std::endl;
}

//Destructor also has parameters with binary scope operator but it's an alternate version.
//This version uses the '~' character after the operator to signify that it's a destructor.
ExampleClass::~ExampleClass(void) {
        std::cout << "Destroying example class!" << std::endl;
}

```
> 1 votes

---
Tags: c++, box2d
---


# Question
Title: Stopping Animations For Player In Java Using Slick2D
I have a problem with stopping animations for a player in Slick2D. I have tried many solutions to the problem and have looked up a couple of resources but I am still stumped by the fact that it is not working. Here's the code I have for my class:

```
public SpriteSheet playerSS = null;
protected InputHandler inputHandler;
public float playerX, playerY = 250f;
private Animation sprite, runningAnimationLEFT, runningAnimationRIGHT, runningAnimationUP, runningAnimationDOWN;
private int duration = 200;

public Game (int stateID) {

}

@Override
public int getID() {
    return Main.game; //GAMESTATE = 1
}

@Override
public void init(GameContainer gameContainer, StateBasedGame stateBasedGame) throws SlickException {
    playerSS = new SpriteSheet("res/player_sprite_sheet.png", 50, 75);

    // ANIMATIONS
    runningAnimationDOWN = new Animation();
    runningAnimationDOWN.setAutoUpdate(true);
    runningAnimationDOWN.addFrame(playerSS.getSprite(1, 0), duration);
    runningAnimationDOWN.addFrame(playerSS.getSprite(0, 0), duration);
    runningAnimationDOWN.addFrame(playerSS.getSprite(2, 0), duration);

    runningAnimationLEFT = new Animation();
    runningAnimationLEFT.setAutoUpdate(true);
    runningAnimationLEFT.addFrame(playerSS.getSprite(1, 1), duration);
    runningAnimationLEFT.addFrame(playerSS.getSprite(0, 1), duration);
    runningAnimationLEFT.addFrame(playerSS.getSprite(2, 1), duration);

    runningAnimationRIGHT = new Animation();
    runningAnimationRIGHT.setAutoUpdate(true);
    runningAnimationRIGHT.addFrame(playerSS.getSprite(1, 2), duration);
    runningAnimationRIGHT.addFrame(playerSS.getSprite(0, 2), duration);
    runningAnimationRIGHT.addFrame(playerSS.getSprite(2, 2), duration);

    runningAnimationUP = new Animation();
    runningAnimationUP.setAutoUpdate(true);
    runningAnimationUP.addFrame(playerSS.getSprite(1, 3), duration);
    runningAnimationUP.addFrame(playerSS.getSprite(0, 3), duration);
    runningAnimationUP.addFrame(playerSS.getSprite(2, 3), duration);

    sprite = runningAnimationDOWN;
}

@Override
public void update(GameContainer gameContainer, StateBasedGame stateBasedGame, int delta) throws SlickException {
    inputHandler.updateKeyboardRelay(gameContainer);
    if (inputHandler.keyUP) {
        sprite = runningAnimationUP;
        sprite.update(delta);
        playerY -= delta * 0.1f;
    } else {
        // Stopping Animation goes here.
    }
    if (inputHandler.keyDOWN) {
        sprite = runningAnimationDOWN;
        sprite.update(delta);
        playerY += delta * 0.1f;
    } else {
        // Stopping Animation goes here.

    }
    if (inputHandler.keyLEFT) {
        sprite = runningAnimationLEFT;
        sprite.update(delta);
        playerX -= delta * 0.1f;
    } else {
        // Stopping Animation goes here.

    }
    if (inputHandler.keyRIGHT) {
        sprite = runningAnimationRIGHT;
        sprite.update(delta);
        playerX += delta * 0.1f;
    } else {
        // Stopping Animation goes here.

    }
}

@Override
public void render(GameContainer gameContainer, StateBasedGame stateBasedGame, Graphics graphics) throws SlickException {
    sprite.draw(playerX, playerY);
}

```

How would I go about stopping the animation from playing over and over again once the movement key is lifted? i.e. If someone presses the 'W' key the player does an animation going upwards, but if the user stops using the 'W' key how would I make it so that the animation stops playing as well?

# Answer
I had a similar problem in my game. I used a simple `boolean` flag called `isMoving` that checked would default to false at the start of each render loop and would only become true if the player was pressing any of the keys.

## Example

```
boolean isMoving;

public void update(BlahBlah parameterHere) {
    isMoving = false;

    if(keyispressed) {
        isMoving = true;
        // Other code
    }

    if(isMoving) {
        // Draw animation based on direction, direction can be stored in enum
    } else {
        // Draw static sprites based on direction, direction can be stored in enum
    }
}

```
> 0 votes

---
Tags: graphics, software-engineering, slick
---


title: Write error log on crash in libGDX?

text:
# Question
Title: Write error log on crash in libGDX?
I've been having problems building my game. I've built it successfully before, until I added the `LuaJava.dll` and `LuaJava.jar` files (so I can use Lua in my game).

Now, it just briefly opens with black screen and immediately closes. Even though it works just fine in Eclipse.

What I used to do before, was set my `jar` file in my assets and it would just work fine. But now, it refuses to work, and I have no idea what the error is.

Is there a function I can call to output the error into a log file?

# Answer
I don't know about writing an error log on crash, but all Android apps already log to the built-in logger. You just need an app like CatLog to view them.

Although verbose, you can usually filter by namespace (and see logs only related to your application). Eclipse does something similar with the built-in log viewer.

This is the only log viewer I used when I worked on my libGDX games.
> 3 votes

# Answer
## Solution 1

What I do to log errors is to surround my `render()` method with a `try` and `catch` block that catches the default `Exception` class. This writes a simple time-stamped log file. It can be implemented like this (Java 7+ Only):

```
@Override
public void render() {
    try(BufferedWriter writer = new BufferedWriter(new FileWriter(new SimpleDateFormat("ddMMyyHHmmss").format() + ".log") {
        //Code here
    } catch(Exception e) {
        writer.write("ERROR:\n");
        writer.write(e.getMessage());
        writer.close();
    }
}

```

## Solution 2

You can run the program on the console using the `java -jar {jarname}.jar` command on the command line to see the error log.

Hope this helps! ~ Ammar Tarajia

P.S: On Windows, to navigate to the correct directory, just do the `cd` command then the folder. (Don't include the drive code!)
> 0 votes

---
Tags: libgdx
---


title: Libgdx crash on dispose()?

text:
# Question
Title: Libgdx crash on dispose()?
Whenever I try to manually call the dispose method in one of my screen my game just crashes.

My dispose looks something like this

```
@Override
public void dispose() {
    battletheme.dispose();
    renderer.dispose();
    bg.dispose();
    enemy.dispose();
    dialouge.dispose();
    GameTools.fontText.dispose();
}

```

and I use

```
this.dispose();

```

When I switch to another screen, otherwise my memory begins to pile up. Is there any reason for this?

EDIT: My spritebatch called "renderer" seems to crash on dispose, any reason?

# Answer
> 1 votes
The `dispose()` function is made to be called at the end of the program's life cycle. You calling `renderer.dispose()` is manually garbage-collecting the `renderer` and this most likely works by setting it to `null` which will, in turn, cause the JVM to respond by destroying the object. You are probably trying to re-access the `renderer` object after it's destruction and failing by causing a `NullPointerException` which is produced when a variable contains a `null` value due to the fact that you can't use `null` to do anything as `null` means nothing :)

Hope this helps! ~ Ammar Tarajia

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


title: libgdx FollowPath proper usage

text:
# Question
Title: libgdx FollowPath proper usage
I'm developing top-down rpg game and got some problems using https://libgdx.badlogicgames.com/gdx-ai/docs/com/badlogic/gdx/ai/steer/behaviors/FollowPath.html

I have a path (picture 1), in this case 2 points - corner and target.
Pic.1
Then I try to make the character move (passing my path to *libgdx FollowPath Steering Behavior*).

```
private FollowPath<Vector2, LinePathParam> followp= new FollowPath<Vector2, LinePathParam>(this, new LinePath<Vector2>(astar.findPath(position, target)),0f,0f);

```

(astar.findPath(position, target) - function that returns Array of points(path). Experimenting with 3rd and 4th parameters (passOffset and predictionTime) made it worse.) And it gains such result (purple line on Picture 2).

Pic.2
But how can I get such result (green line on Picture 3)?
Pic.3

# Answer
## Solution

I posted an example scenario answer on the linked post but I thought that maybe I should provide a more direct answer on this page.

So, as you can see, the green line seems to bend toward the normal then bend away again toward the final position. To do this, we can use two LibGDX `Circle` instances with the same radii - being large enough for the first point at the turn's edge to be where you want the turning to start.

So now we have two points with two radii, now what? Well, we check when the entity reaches the center of the circle and then makes a small delay of around half a second. After this delay, the line will start to bend towards the vertical normal line and will move simultaneously.

Eventually, it will reach the normal and stop bending but then it will reach the edge of the second circle that surrounds the end point. As it reaches this point, it will again have a small delay of around a quarter of a second then start to bend toward the end point and again move simultaneously. After reaching the correct angle it will continue to move in that direction till it reaches the point.

Well, I've talked about moving on an angle but how do we achieve this? Simple really, (I'm in 9th grade / Year 10 and I know this) we use the equation of the line or `y=m*x+c` in which `y` represents the Y coordinate on the screen depending on the gradient `m` and starting at the intercept `c` but this is basic straight-line graph calculus and this has 2 turns. Assuming we go by the calculus rules of dimensional naming conventions, 1D = straight-line, 2D = quadratic, 3D = cubic etc., then this would be a cubic function graph since there are 3 different line equations but to do cubic function graphs. I'm not sure of those but here's a link: Click me!

Hope this helps!
> 3 votes

---
Tags: java, libgdx, ai, path
---


# Question
Title: How to find a material through a raycast in Unity 5?
I have an empty object with a script on it and I want to be able to move the empty over other objects and then have it print out the name of the material for the triangle that it's hovering above. (Its for something else, but I only need help getting to that stage, I can do the rest from that point). I found this on the topic but the answer is very vauge. I finished steps 1 and 2 but I can't figure out number 3. Here is my code so far...

```
void Update (){
        Ray ray = new Ray(transform.position, new Vector3(0, -100, 0));
        RaycastHit hit;

        if(Physics.Raycast(ray, out hit)){
            print ("Triangle Index: " + hit.triangleIndex);

            Mesh mesh = hit.collider.gameObject.GetComponent<MeshFilter>().mesh;

            print ("Submesh Count: " + mesh.subMeshCount);
        }
    }

```

Could someone show me how to finish it off so that when I move the empty over different objects, it would print out the name of the material per triangle?

Thanks, Matthew

# Answer
I'd recommend testing empirically to confirm, but the second answer at this link says that triangle data for submeshes is indexed sequentially in order of submesh index. That means all the triangles for submesh 0 have lower indices than those in submesh 1, etc...

So, you can iterate over the submeshes until you find the one your triangle belongs within:

```
MeshCollider collider = hit.collider as MeshCollider;
// Remember to handle case where collider is null because you hit a non-mesh primitive...

Mesh mesh = collider.sharedMesh;

// There are 3 indices stored per triangle
int limit = hit.triangleIndex * 3;
int submesh;
for(submesh = 0; submesh < mesh.subMeshCount; submesh++)
{
    int numIndices = mesh.GetTriangles(submesh).Length;
    if(numIndices > limit)
        break;

    limit -= numIndices;
}

Material material = collider.GetComponent<MeshRenderer>().sharedMaterials[submesh];

```

This is pretty ugly, but still neater than the accepted answer at that link, which visits every triangle to test if it's the one the ray hit. ;)
> 5 votes

---
Tags: unity, raycasting, materials
---


title: SFML dynamically loading images

text:
# Question
Title: SFML dynamically loading images
So I'm screwing around with c++ and SFML, when I thought to myself the following:

If the images are compiled into the executable, with enough sprites for the game, memory might become a problem at some time? I might have misunderstood how images are loaded, but they aren't in the release directory so they must compiled and put into memory when the executable is loaded?

# Answer
The images are not saved *in* the executable.

You store the path to the files in the executable. And the files are typically in the folder of the exe.

When you use Visual Studio, the exe might be in a folder, while the "environment" folder that the exe will look in to find files could be in another (the "Working Directory").

Your images could be in the "working directory" while the exe is in another directory.

This really depends on your setup and your needs (and your Visual Studio configuration).
> 0 votes

---
Tags: c++, sfml, image, loading
---


title: Make Camera Bounds

text:
# Question
Title: Make Camera Bounds
I'm new here and I have a question. (Help me Google Translate). At first I make camera from this video.

First video

*First script (CameraController)*

```
using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

    public PlayerController player;

    [Header ("Привязка камеры")]
    public bool isFollowing;
    public float xOffset;
    public float yOffset;

    // Use this for initialization
    void Start () {
        player = FindObjectOfType<PlayerController>();

        isFollowing = true;
    }

    // Update is called once per frame
    void Update () {
        if (isFollowing)
            transform.position = new Vector3 (player.transform.position.x+xOffset, player.transform.position.y+yOffset, transform.position.z);
    }
}

```

Second video

*Second script (CameraFollow)*

```
using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour {

    private Vector2 velocity;

    public float smoothTimeY;
    public float smoothTimeX;

    //public GameObject player;
    public PlayerController player;

    public bool bounds;

    public Vector3 minCameraPos;
    public Vector3 maxCameraPos;

    // Use this for initialization
    void Start () {

        //player = GameObject.FindGameObjectsWithTag ("Player");
        player = FindObjectOfType<PlayerController>();

    }

    // Update is called once per frame
    void FixedUpdate () {

        float posX = Mathf.SmoothDamp (transform.position.x, player.transform.position.x, ref velocity.x, smoothTimeX);
        float posY = Mathf.SmoothDamp (transform.position.y, player.transform.position.y, ref velocity.x, smoothTimeY);

        transform.position = new Vector3 (posX, posY, transform.position.z);

        if (bounds)
        {
            transform.position = new Vector3(Mathf.Clamp(transform.position.x, minCameraPos.x, maxCameraPos.x),
                                             Mathf.Clamp(transform.position.y, minCameraPos.y, maxCameraPos.y),
                                             Mathf.Clamp(transform.position.z, minCameraPos.z, maxCameraPos.z));
        }
    }
}

```

I want to do like in second video, but when my hero died. He becomes invisible. How to fix it?

MyProject

Thanks in advance!

**UPDATE:**

*Script(LevelManeger)*

```
using UnityEngine;
using System.Collections;

public class LevelManeger : MonoBehaviour {

    public GameObject currentCheckpoint;

    private PlayerController player;

    public HealthManager healthManager;

    [Space(10)]
    [Header ("Штраф")]
    public int pointPenaltyOnDeath;

    // Use this for initialization
    void Start () {

        player = FindObjectOfType<PlayerController> ();

        healthManager = FindObjectOfType<HealthManager> ();
    }

    // Update is called once per frame
    void Update () {

    }

    public void RespawnPlayer()
    {
        ScoreManager.AddPoints (-pointPenaltyOnDeath);
        Debug.Log ("Player Respawn");
        player.transform.position = currentCheckpoint.transform.position;
        healthManager.FullHealth ();
    }
}

```

# Answer
Change the `Z` position of `Checkpoint` gameObject from `-10` to `0`.

This is because your MainCamera has clipping planes with `0.3` to `1000` and you are spawning your `Hero` even behind the `Near Plane (Clipping plane)`.

**`Clipping Planes`** are the attributes of `Camera` to let `Camera` know that `From` where `To` where `Camera` has to render all stuff.
> 1 votes

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


# Question
Title: Why don't objects far away from the camera experience floating point issues?
In Kerbal Space Program, a space exploration game made with Unity, Floating origin technique is used to overcome the floating point precision issues. While in map view, the world (a scaled space with miniature celestial bodies) is recentered around the camera every frame so glitches don't occur when viewing unsafely distant planets. But when such planets are observed from an 'unsafe distance' (more than 10 000 units in scaled space), they're still rendered normally. Why don't floating point issues occur?

# Answer
I'm fairly sure floating point rounding errors don't mean that an object will be absolutely rendered incorrectly when far away.

It just means that the probability of the sun being exactly where it is supposed to be is smaller the farther away from the origin it is.

However, you might not be able to notice if the sun is at the wrong place with an error of 10 km for instance. Since the sun jumping between 10 km is hardly noticeable from earth. It wouldn't even move a single pixel.

You also have to take into account that Kerbal uses many cameras to render a single scene. Three, if I remember correctly. One for the cockpit or ship, one for the landscape, and one for celestial objects. These cameras have individual near/far rendering planes.

I hope this answers your question.

This video goes into greater detail: https://youtu.be/mXTxQko-JH0?t=399
> 2 votes

---
Tags: unity, floating-point
---


title: Fixed-Timestep still updating too fast

text:
# Question
Title: Fixed-Timestep still updating too fast
I'm trying to figure out if I'm approaching my simple fixed-timestep implementation correctly, following examples such as: Gaffer (without RK4), and DeWitters

Currently, I have a game object which contains position and velocity data members, with position calculated by

```
 position = position + (velocity * dt)

```

However, unless the velocity is set to a value of two decimal places, the update makes the position change in an instant (e.g. Velocity = 0.05 works, but this does not seem logical; to me Velocity should be \>0?; even a value of 0.5 makes the update appear instant). Therefore, I have come to the conclusion that I have implemented by game loop incorrectly.

Note, I'm using SDL and C++, however the following is all Psuedocode:

```
bool quit = false;
World world;

Uint32 frameTime = SDL_GetTicks();
double accumulator = 0.0;
const double dt = 1.0 / 60.0;
int fCount = 0;
while(!quit){
    fCount = 0;
    double newTime = SDL_GetTicks();
    double nextFrameTime = newTime - frameTime;

    if(nextFrameTime > 0.25)
        nextFrameTime = 0.25;

    frameTime = nextFrameTime;  //Line of error, should be frameTime = newTime
    accumulator += nextFrameTime;

    while(accumulator >= dt){
        world.Update(dt);  //A simple counter revealed Update being called 15-16 times during this loop
        accumulator -= dt;
        fCount++;
    }
    //fCount is equal to 15 when dt = 1.0/ 60.0, fCount = 8/9 when dt = 1.0/30.0
    double interpol = accumulator / dt;
    world.Render(interpol);
}

```

If there isn't any apparent issue with this code then perhaps I have messed up my position/physics calculations based on Update(dt).

Any help is appreciated

# Answer
> 3 votes
I assume `GetTicks()` is standard SDL. In which case when I look at the documentation is says "Get the number of **milliseconds** since the SDL library initialization." However all your calculations seems to be in seconds. So if you treat the output from `GetTicks()` as being seconds you are gonna effectively be running 1000 times faster. Or you would if it weren't for this line `if(nextFrameTime > 0.25)`.

So you either have to change all your other calculations to be in milliseconds, e.g. `dt = 1000.0 / 60.0;`, or convert the output from `GetTicks()` to seconds by dividing it by 1000. That way all numbers related to time will be in the same unit and can be directly compared, added and subtracted easily.

Also this line `frameTime = nextFrameTime;` should be changed to this `frameTime = newTime;`. frameTime should store the previous frame's start time so you can calculate the elapsed time for the frame from that.

---
Tags: c++, sdl, timestep
---


# Question
Title: Is it possible to interpolate different sprites?
I can interpolate different animations based on position, rotation, and scale. I want to do the same for different sprites, automatically.

For example, lets say I have a soda can being crushed. I have 2 sprites: One is the soda can uncrushed, and one is the soda can fully crushed. I want to only use those 2 sprites, and have Unity automatically transition from the normal can to the crushes can.

How can I do this without making a bunch of key frames in between?

# Answer
> 0 votes
There is no perfect way to achieve the effect you are after.

But there are some ways to interpolate frames between animations to smooth them out in other software and then import the interpolated frames into Unity. However, please note that the more frames you have, the better the interpolation will work. Using only two frames will result in a strange blending effect.

One way, is to use the free package with After Effects ReelSmart Motion Blur

Here is the result of ReelSmart applied to many stock motion frames.

---
Tags: unity, animation, sprites, interpolation, blending
---