title: Cant jump from ground collision

text:
# Question
Title: Cant jump from ground collision
I have a character that starts in the air and applying gravity to it to collide with platforms in my level. At the start, the character gradually gains speed descending until it collides with a platform. After colliding, I display text letting me know if collision is detected (character touching the ground is true). But when I push the 'W' key, the character doesn't jump. It's worth noting that there is no dedicated ground zero as the level has platforms at different heights.

```
void Player::update(const std::vector<std::string>& layerData, float deltaTime)
{
    // check if player touches ground
    mOnGround = collideWithLevel(layerData);

    if (mInputManager->isKeyDown(SDLK_w)) // press W to jump
    {
        jump(deltaTime);
    }

    land(deltaTime);
}

void Player::jump(float deltaTime) // problem
{
    if (mOnGround)
    {
        mVelocity.y = mJumpPower * deltaTime;
        mOnGround = false;
    }
}

void Player::land(float deltaTime)
{
    if (!mOnGround)
    {
        mVelocity.y += mGravity * deltaTime;
        mPosition.y += mVelocity.y;
    }

    if (mOnGround)
        std::cout << "On ground" << std::endl; // fires
}

```

# Answer
you are probably checking for collisions after moving the player, so the character get's stucked in the ground, you have to check if there will be a collision before moving the player and move it if there's no collisions detected.

```
if(player.y - velocityY >= 0){
    player.y -= velocityY;
}else{
    player.y = 0;
}

```
> 1 votes

# Answer
It looks to me like you are not setting the velocity when jumping large enough (although this depends on `mJumpPower` and `mGravity`).

You jump function at the moment is,

```
void Player::jump(float deltaTime) // problem
{
    if (mOnGround)
    {
        mVelocity.y = mJumpPower * deltaTime;
        mOnGround = false;
    }
}

```

In this function you set that the horizontal velocity after a jump is proportional to `deltaTime` (which I assume is the time between frames or physics updates). To me this does not make sense as the velocity after a jump should be independent of the FPS or the physics update rate. Instead try something like this,

```
void Player::jump(float deltaTime) // problem
{
    if (mOnGround)
    {
        mVelocity.y = mJumpPower;
        mOnGround = false;
    }
}

```

If there is another reason for including this `deltaTime` then please feel free to correct me, however I cannot see what it is doing here.
> 1 votes

---
Tags: c++, physics, jumping
---


title: Libgdx - when / how to save data

text:
# Question
Title: Libgdx - when / how to save data
I'm making a simple 2D game in libgdx, and now I'm at the point where I have to save data. I already have a mechanism to save the data itself. The problem is that I don't know when/where the procedure to save the state should be executed. Should it be executed in dispose method? Or pause method? Save the state every time the player dies doesn't seem very efficient to me. Anyone can give me tips about this? Thanks in advance.

# Answer
Make sure the player never loses progress. That means saving when the player has achieved some sort of waypoint rather than when the game is exited or when the player returns to the main menu or something like that.

In the *Pause* method you're supposed to keep enough information to successfully recover after a *Resume*, this can be different from other saves where you save for example completion of a level.

In my games I try to save during the transition between levels. But this is of course different if you have the sort of game where the player has to reach a save-point.

Saving on every death doesn't seem like it's that often (unless you expect your players to die every second or so), but I wouldn't do it unless the death is part of the state that needs to be persisted. For example if they only got three lives to complete the game then you need to save on each death or users will be able to kill the game process when they die to get an unlimited number of lives.

The Android Design Principles (which, granted are more geared towards application development rather than game development), state that you should "Never lose my stuff".
> 0 votes

---
Tags: android, libgdx, savegame
---


# Question
Title: Distinguish touch gestures for distinct horizontal and vertical commands
In my script below I'm using horizontal and vertical swipe gesture to move the character but both gestures are called on a single touch.

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

void HorizontalSwipe()
{
  foreach ( Touch FingerTouchx in Input.touches ) {
    if( FingerTouchx.fingerId < 1 ){  //         FINGERID
      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.phase == TouchPhase.Began)
        FingerInitialPositiony = FingerTouchy.position.y;

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

        if(FingerMovedPositiony > FingerInitialPositiony)
          charcter.transform.Translate(Vector2.up * speed * Time.deltaTime);

        if(FingerMovedPositiony < FingerInitialPositiony)
          charcter.transform.Translate(-Vector2.down * speed * Time.deltaTime);
      }

      if(FingerTouchy.phase == TouchPhase.Ended) {
        FingerInitialPositiony = 0f;
        FingerMovedPositiony = 0f;
      }
    }
  }
}

```

Whats wrong here? My game character moves in the swipe direction along with continuous jumps.

What I want to achieve is that the character should move horizontally with one touch gesture and vertically(jump) with another touch gesture.

For example: the gesture made on the lower left corner of the touch screen should only consider horizontal movement and make the character move left or right, while the gesture made on the lower right corner should consider only the vertical movement and make the character jump. I'd like to achieve something similar to what's in Leo's Fortune.

# Answer
The biggest issue is that you're attempting to detect both horizontal and vertical swipes in separate functions but at the same time. When one happens, the other might also happen (unless you swipe at a perfect angle).

Swipe detection is a problem that's been solved before although the link you posted in the comments makes it look like vertical swipes should be individual swipes and left/right is more of a swipe and hold sort of deal.

You'll want to first combine the logic for the swipe, figure out what direction it is, and then handle it appropriately. Here's a modified version of a basic swipe detection script:

```
public class SwipeHandler : MonoBehaviour {
    private float m_startTime  = 0.0f;
    private Vector2 m_startPos = Vector2.zero;

    private bool m_swiping = false;
    private bool m_holding = false;
    private float m_minDist  = 50.0f;
    private float m_maxTime = 0.5f;

    void Update () {
        if (Input.touchCount > 0){
            foreach (Touch touch in Input.touches) {
                switch (touch.phase) {
                case TouchPhase.Began :
                    m_swiping = true;
                    m_startTime = Time.time;
                    m_startPos = touch.position;
                    break;
                case TouchPhase.Canceled :
                    m_holding = false;
                    m_swiping = false;
                    break;
                case TouchPhase.Ended :
                    DetectSwipe(touch);
                    m_holding = false;
                    break;
                case TouchPhase.Moved :
                    DetectSwipe(touch);
                    break;
                case TouchPhase.Stationary :
                    DetectSwipe(touch);
                    break;
                }
            }
        }
    }

    void DetectSwipe (Touch touch) {
        float totalTime = Time.time - m_startTime;
        float totalDist = (touch.position - m_startPos).magnitude;
        if (m_holding || (m_swiping && totalTime < m_maxTime && totalDist > m_minDist)) {
            Vector2 direction = touch.position - m_startPos;
            Vector2 swipeType = Vector2.zero;
            if (Mathf.Abs(direction.x) > Mathf.Abs(direction.y)) {
                // Horizontal:
                swipeType = Vector2.right * Mathf.Sign(direction.x);
            }
            else{
                // Vertical:
                swipeType = Vector2.up * Mathf.Sign(direction.y);
            }

            if(swipeType.x != 0.0f){
                 m_holding = true;
                 if(swipeType.x > 0.0f){
                     // HANDLE RIGHT SWIPE
                 }
                 else{
                     // HANDLE LEFT SWIPE
                 }
            }
            if(swipeType.y != 0.0f ){
                 m_swiping = false;  // <- THIS MAKES THE DIFFERENCE
                 if(swipeType.y > 0.0f){
                     // HANDLE UP SWIPE
                 }
                 else{
                     // HANDLE DOWN SWIPE
                 }
            }
        }
    }
}

```
> 3 votes

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


# Question
Title: How can I extrude a regular, grid-based 2D shape to 3D?
I have a list of vertex coordinates which encircle several 2D areas. Orthogonal lines only, but not necessarily convex areas... similar to PCB traces of conductive copper areas. I want to draw them like solid objects in 3D using OpenGL, but I'm still very new to 3D and struggling.

Please point me how to do this. I've managed to draw the outline only using `GL_LINE_STRIP`, but when I try `GL_QUAD_STRIP` or `GL_TRIANGLE_STRIP`, the list of coordinates is not properly ordered for triangle strip and the fact the areas are not convex prevent me from doing a simple triangular tessellation.

These are the 2D shapes:

I'd like to render them like this:

# Answer
> 1 votes
There are three parts to solving this;

1. tessellating the concave polygons into triangles (opengl cannot draw concave polys). This will be the 'top' surface
2. displacing (extruding) the the set of triangles along an appropriate vector, this will become the 'bottom' surface
3. generating the 'sides' of the volume, by joining up the *outside* edges of top & bottom surfaces

## Part 1 - Tessellation of top surface

The simplest answer for concave polygon tessellation with no holes is EAR clipping.

{v3,v0,v1} & {v1,v2,v3} are ears, {v0,v1,v2} is not an ear (v3 lies inside {v0,v1,v2}), {v2,v3,v0) is not an ear (the interior angle at v3 is \> π) . An EAR of a polygon is a triangle formed by three consecutive vertices V0, V1 and V2 for which V1 is a convex vertex (the interior angle at the vertex is smaller than π radians), the line segment from Vi0 to Vi2 lies completely inside the polygon, and no vertices of the polygon are contained in the triangle other than the three vertices of the triangle. A polygon of 4 or more vertices always has an ear. So our approach is to find an ear, chop it off, repeat until there is only one ear left (triangle);

```
do until num vertices of P is 3
    find an ear vq,vr,vs
    add vq,vr,vs to list of triangles
    remove vr from polygon
end do
add last 3 vertices to triangle list

```

Draw this list as a GL\_TRIANGLE\_LIST

There are more efficient approaches to polygon triangulation(https://en.wikipedia.org/wiki/Polygon\_triangulation), but the ear method is by far the simplest.

## Part 2 - Generate bottom surface

Copy all the vertices found in part one and add your extrusion vector to each of them. This becomes your 'bottom' surface. The extrusion vector is a vector (typically) at right angles to your initial polygon. The length of the extrusion vector depends on how long your extrusion needs to be.

## Part 3 - Generate sides of extrusion

Take each edge of your original concave polygon. Add the extrusion vector to the edge's two end points. This generates 4 points (2 original end points and 2 'extruded' end points) These form a rectangle\*, which will be one of the sides of the extrusion. These can be drawn as GL\_QUADS or GL\_TRIANGLE\_STRIP depending on order.

\*assuming a right angle extrusion vector.

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


# Question
Title: How can I automatically fit elements in libGDX layouts?
Recently I wanted to use libGDX's `Table` to show four buttons. But my table doesn't fit on the stage:

Here is the code I used:

```
table.add(new GameButton("1"));
table.add(new GameButton("2"));
table.add(new GameButton("3"));
table.add(new GameButton("4"));
table.align(Align.bottom);
table.setFillParent(true);
stage.addActor(table);

```

(`GameButton` is a `TextButton` subclass with a special `TextButtonStyle`.)

When I change `table.add(new GameButton("1"));` to `table.add(new GameButton("1")).width(Gdx.graphics.getWidth() / 4);`

I get this result:

Does `Table` (or another libGDX layout class) have functionality to auto-fit elements like in the second picture? Or I should always add some width/height options after adding element?

# Answer
Got it!

As Josh Petrie said, we should use `.expand().fillX()` after adding each button. After that we should override `getMinWidth()` method for GameButton class (for example, with `return 0`). As result, you get correct layout!
> 0 votes

# Answer
You probably want to check out the `fillX()` (and `fillY()`) methods on the table, documented here.

The fill methods cause a widget to be sized to the cell subject to the minimum and maximum size constraints of the widget itself. You'd probably want to do something like `table.add(new GameButton("1")).expand().bottom().fillX();`
> 0 votes

---
Tags: java, libgdx
---


# Question
Title: How to draw a sprite at a floating point xy coordinate with interlaced drawing?
I have a 2D game made in MonoGame (XNA 4.0 framework). Here's what I want to do:

* draw a 2d image at a floating point xy coordinate such as 125.5, 300.12 (and do NOT round them to an int).
* the image is automatically "interlaced", which means the picture is shaded correctly around the borders so that it looks like it's actually a fraction of the way across pixels, and not aligned exactly on pixels.

How do I do this? Is there a standard library for this?

P.S. the game I'm working on eventually needs to work on Mac and Linux as well, so please don't give me any dead-end solutions.

# Answer
Any of the `Vector2 position` draw overloads.

```
SpriteBatch.Draw (Texture2D, Vector2, Color)
SpriteBatch.Draw (Texture2D, Vector2, Nullable<Rectangle>, Color)
SpriteBatch.Draw (Texture2D, Vector2, Nullable<Rectangle>, Color, Single, Vector2, Single, SpriteEffects, Single)
SpriteBatch.Draw (Texture2D, Vector2, Nullable<Rectangle>, Color, Single, Vector2, Vector2, SpriteEffects, Single)

```

Combined with any of the filtering options with the exception of Point based ones. (Linear is the default)

TL DR: Use the default sampling state and specify a non integer location in the draw call
> 2 votes

---
Tags: 2d, xna-4.0, monogame, graphic-effects
---


# Question
Title: What is the fastest way of drawing simple, textured geomtries and keeping the depth test?
I'm looking for a **fast** way to draw simple 3D geometries - that will consist of up to 10 vertices. Each of them will have a texture (though varying between geometries). I also want to store the fragment depth for depth testing.

There will be no lighting and only very simple transformations (this actually is for isometric game).

So far what I did was trying to achieve top performance using OpenGL for drawing simple quads (what the problem actually boils down to). For my machine (from around 2008), I had the following results:

* Using immediate mode 4800 quads took 120ms
* Using vertex arrays and VBOs this took around 40 ms

What I see as a problem is the bottleneck of glDraw\* calls. I want to somehow get below 4-5 ms , as there will be really a lot of objects on the screen. Any ideas about how could (or perhaps couldn't) achieve that?

# Answer
I suggest you create a huge array in cpu side that will be linked with a vertex buffer in the gpu side.

At each frame you fill that array with the vertices coming from all your meshes. So you'll be able to batch a certain amount of draw calls.

The trick is to sort your objects, first by shader, then by z it by texture, depending if you have transparent objects.

In order to change your textures at the right moment, you'll have to use a stack of objects containing the number of vertices to draw and the common material parameters for these vertices.

Even best if you can interleave vertices position with uvs in the huge array.

Hope this helps.
> 3 votes

---
Tags: opengl, rendering, performance, geometry
---


# Question
Title: OnCollisionEnter is called over and over again
Currently I'm trying to let the player place a GameObject in the world. You can imagine this like a RTS game where you can place a building you have just build.
My problem now is, in order to avoid that the new GameObject intersects with another I check for collisions. For this my GameObjects have a BoxCollider (MeshCollider did not work) and a non kinematic RigidBody.
The first tests looked promising but now I'm facing a problem I can't quite explain: Sometimes, but not always OnCollisionEnter and OnCollisionExit are called over and over again, even when both objects are not moving. They overlap and stay that way. I had guessed that they always only get called once.
My Unity version is 5.3.0f4.

Further information: Each of my GameObjects have a guid so I can identify. They get generated when the GameOject is created. The debug output in OnCollisionEnter and Exit look like this:

> OnCollisionEnter from 593b209f-cc63-4d31-9911-34c5f69ac224
> Collided with: 77e05881-2adb-459d-a134-8205cf4e3327
> OnCollisionEnter from 77e05881-2adb-459d-a134-8205cf4e3327!
> Collided with: 593b209f-cc63-4d31-9911-34c5f69ac224
> OnCollisionExit from 593b209f-cc63-4d31-9911-34c5f69ac224!
> OnCollisionExit from 77e05881-2adb-459d-a134-8205cf4e3327!

And then the same output again.

I'm happy for any hints and help. :)

# Answer
> 1 votes
Since I couldn't get it to work with OnCollisionEnter I've switched to using OnTriggerEnter instead which works fine for now. It only has a problem when the model is rotated 180° but that is another question.
To work with triggers the following steps have to be done (most of it was done in the same way with OnCollisionEnter):

* Add RigidBody that has isKinematic set to true.
* Add Collider (MeshCollider works too) that is Convex and a Trigger

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


# Question
Title: How can I handle markup sequences in a libGDX TypeWriter implementation?
I've implemented my own TypeWriter for text that looks like this

```
public static String GetWords(String text, float wordCount)
{
    float words = wordCount;
    // loop through each character in text
    for (int i = 0; i < text.length(); i++)
    {
        if(i == text.length() - 1 && SceneHandler.lineFinished == false){
            SceneHandler.lineFinished = true;
        }
        words--;
        if (words <= 0)
        {
            return text.substring(0, i);
        }
    }
    return text;
}

```

I decided I wanted to do markup as well, so that means color codes and such. Problem is that the TypeWriter also goes through the color code (The \[COLOR\] and the \[\] part) so you get something like this

```
[
[Y
[YE
[YEL
[YELL
[YELLO
[YELLOW
*nothing*
(Actually yellow) T

```

Does anybody have any idea how I could fix this or approach this problem?

# Answer
While you're looping through each character in the input text, if the current character is the start of a markup block (that is, the `[` character), then enter a nested loop to extract all the characters up to and including the closing token (the `]`). Parse them, issue whatever instructions you need to actually turn the text yellow to the rest of your system, and then parse the next character and feed it out of the function normally.
> 1 votes

---
Tags: libgdx, fonts
---


# Question
Title: Why not draw a custom font with lines and/or polygons?
Reasons/advantages I see:

1. More flexible procedural animation.
2. Completely custom font.
3. Performance (no texturing or high-poly)?
4. No assets (unless data-driven).
5. Multi-resolution compared to sprite fonts / sprites.

Downsides I see:

1. Effort and time to define every character.
2. Effort and time to implement the general code.
3. Future localization pain.

Example: https://youtu.be/Tz7L-92Bo-M?t=2m13s

1. Is this unreasonable and why?
2. Will I get a rendering performance win compared to sprite fonts on common multi-core mobile devices?

# Answer
> 2 votes
Because it's a lot of effort for very little gain. Ignoring for the moment the difficulty of creating a nice, atheistically-pleasing collection of glyphs in the first place, looking at your list of "pros:"

> More flexible procedural animation.

This depends on the kind of animation you're talking about. There's really no advantage here if you're just moving the text around, rotating it, scaling it, making it go in sine wave patterns, et cetera. If you want to deform the actual glyphs in some interesting and unusual way, then sure.

> Completely custom font.

Not sure why this is an advantage over using an existing, time-tested font.

> Performance (no texturing or high-poly)?

Probably not actually an advantage; probably either a wash, or a net loss. Rendering text via quads is *really* cheap. Rendering it via a bunch of lines or triangles converted from some likely vector-based description of glyphs? Not so much.

> No assets (unless data-driven).

Not really. You have to store the description of your custom collection of lines/vertices that represent the glyphs somewhere. This is not really any different from storing an existing font (TrueType, et cetera) or pre-rendered sprite texture.

> Multi-resolution compared to sprite fonts / sprites

Compared to sprites, perhaps, but only if you're storing the font glyphs in a vectorized format... which is sort of what existing font formats store things as. You can achieve the same thing by using font rendering APIs like FreeType or CoreText to render text to textures on the fly; this can be done very fast and supports not only a effectively infinite range of resolutions and scales but all the other really nice stuff like kerning and ligatures that those APIs provide.

---

On the other hand, every single one of your cons is pretty spot on. So basically, it's a ton of work, and in most cases all the gains you'd realize you could also realize by not completely pre-baking your sprite fonts (instead using FreeType/CoreText/et cetera).

---
Tags: rendering, performance, fonts, spritefont
---


title: Random AI Movement

text:
# Question
Title: Random AI Movement
So I'm creating a zombie game where the zombies are passive and just walk randomly all over the area when player is not near. My question is: how would I make zombies move randomly? I code in C#. Basically, there is a town filled with zombies that just wander around the area (walk randomly everywhere slowly) until the player is seen or is very near. Thanks.

# Answer
You would need to implement two AI states: Seek & Wander The zombies will have to have an attention radius.

```
if player is within the attention radius
    seek(player)
else
    wander()

```

In each wander behaviour you will want to have a location for it to wander to. If you have a complex area you would want to have the zombie follow a specified path. Which I would suggest to use A\* to create the paths.

```
function wander()
    if path is empty
        findPath(randomPoint)
    else
        seek(path.NextNode.position)

```

To be able to steer towards a point you want to use the dot product. Here is what I use to steer towards a point:

```
function seek(point)
    fwd = normalize(getForwardVector())
    diff = normalize(point - this.position)
    dot = dot(fwd, diff)
    this.rotationalVelocity.y = dot * this.rotationalSpeed;
    this.velocity = fwd * this.wanderSpeed;

```

If you want to make the zombies even more dumb you could test if the `dot` product of the fwd, and diff vectors are greater than 0. That means the zombie is facing the player. If it less than or equal to 0 then don't seek the player.
> 3 votes

# Answer
For random movement, define variable radius, which is the greatest distance that the zombie can go at a moment, and some sort of time variable which is how long they will stand there. Generate a vector with distance less than radius, and angle of which you want the zombie to move. Then, wait a random amount of time, and repeat. Of course, this is a very simple and "stupid" ai. Like mentioned above, A\* would probably be the way to go with randomly generated obstacles to make paths.

Good luck
> 1 votes

---
Tags: unity, c#, movement, ai, random
---


# Question
Title: Pygame making Snake, need help with generating fruit with a random color
This is my function for generating an apple, I want it to generate a random color each time the snake eats it.

```
    def AppleGenerator():
        fruit_colors = [crimson,powderblue,yellow,hotpink,orange,darkorchid,lime]
        x = random.randrange(1,6)
        return fruit_colors[x]

```

This is when I call it, AppleX, AppleY, and size are just the dimensions of the rectangle. The problem is that the 'apple' just flashes random different colors from the list and doesn't stick to one color.

```
 pygame.draw.rect(gameScreen,AppleGenerator(),[AppleX,AppleY,size,size])

```

By the way, the reason why I didn't just simply do

```
def AppleGenerator():
   fruit_colors = [crimson,powderblue,yellow,hotpink,orange,darkorchid,lime]
   return random.randrange(fruit_colors[0],fruit_colors[6])

```

is because the colors are tuples, and randrange() only accepts integers.

# Answer
You're calling the `AppleGenerator()` function every time you draw the fruit, so each time you draw it, that function gives it a new random colour.

You need to only call it whenever the fruit is created, then store the colour result and pass that in instead.

Something like:

```
// Get colour (call this once per apple)
apple_colour = AppleGenerator()

// Draw the appple (call this every frame)
pygame.draw.rect(gameScreen, apple_colour, [AppleX,AppleY,size,size])

```
> 1 votes

---
Tags: python, pygame
---


title: Unity 2D Alpha cutout layer for Sprites

text:
# Question
Title: Unity 2D Alpha cutout layer for Sprites
I'm trying to make a simple Fog of War effect for my 2d game, similar to these:

.

I want to have a sprite layer of black and then have a sprite to cut out itself from the black layer, leaving a part of the black sprite transparent. And if I have two cut out sprites they will blend like the image I linked.

Anyone got any ideas?

# Answer
> 1 votes
You need to write a shader, in which you pass two textures:

* camera rendertexture
* grayscale mask of light and shadow

You can get the second one in rendertexture from the second camera that uses OnPreCull method to adjust some render settings and reverts all back on OnPostRender. Or using second camera's Culling Mask.

In the shader you blend the two textures pixel by pixel and render the result to screen.

You can also read my post about rendertextures and rendering from a shader to screen: Unity3D - override main camera rendering for compositing effect.

# Answer
> -2 votes
There are two hacks to achieve this effect

1) Make a big black sprite with a hole cut out in the middle. Make this sprite be on top of everything.

2) Change the material of all sprites to Sprite-Diffuse. And add a light source as the child of the player.

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


# Question
Title: Calculating Linear force required to hit a specific vertex on a parabola
The idea is a user presses somewhere on the screen and the program will fire an object in a parabola shape from a defined start position that has it's vertex where the user touched the screen.

I have managed to use the two points I have to get the quadratic equation in vertex form, and converted it to standard form ok but I don't know how to get the values required for setLinearVelocity vx and vy in corona sdk.

Current code is:

```
-- given vertex and another point find the parabola formula in vertex form
-- y=a(x−h)2+k
local y, a, x, h, k, xh
h = event.x
k = event.y
x = xStartPos
y = yStartPos

-- solve for a
xh = (x - h) * (x - h)
y = y + (k * -1)
a = y / xh

-- convert to quadratic formula
-- y = ax^2 + bx + c
local b, c
b = -2 * a * h
c = a * (h * h) + k

local vx, vy = -- calculate something here
proj:setLinearVelocity( vx,vy )

```

# Answer
Quick note: I don't know lua, however I am fairly good at maths/physics and please bear with me if I cover ideas you are already familiar with.

For any object under the force of gravity the horizontal component of the velocity, `vx`, will remain constant throughout the motion.

In this picture the red dots are made at equal times, so the ball travels equal distances in the `x` direction every tick (so `vx` is constant) whereas it does not in the `y` direction.

**The following does not answer your question directly but is useful so I have left it in**

It is possible to solve the problem, given a starting position `(x0, y0)` and a final position `(xf,yf)` what velocity does the object need initially to reach the final point. This can be solved using equations of motion, defining `(vx,vy)` as initial velocities, `T` as the time to complete the motion and `g` as the acceleration due to gravity,

```
xf = x0 + vx*T               // This has no acceleration part as it is zero for x
yf = y0 + vy*T - g*T^2/2

```

solving these two equations gives

```
vy = vx * (yf - y0)/(xf - x) + g * (xf - x0)/(2 * vx).

```

Now this is not a complete solution as you know the motion is parabolic but it takes **three points** to define a parabola. So you are going to need to choose either the time it takes for the particle to reach its final spot or the velocity in the x direction.

**Actual answer**

You choose that the final point `(xf,yf)` to be the vertex of the parabola, this does in fact introduce a third constraint, as you mentioned in the comments, this time on the velocity in the `y` direction.

As you found in the linked question the `vy` required is given by,

```
vy = sqrt(2 * g * (yf - y0)).

```

You can then use the equation above for `vy` in terms of `vx` to solve for `vx` which gives,

```
vx = (xf - x0) * sqrt(g / (2 * (yf - y0))).

```
> 9 votes

# Answer
George has answered this correctly - I just wanted to include the working code in case someone needs it in future. I did not need to convert the values to a quadratic equation in the end

The extra sums in the code such as dy * 30 is to convert between pixels and metres and back again, and were a major cause of being unable to convert the maths to code.

```
local dy = (yf - y0) * 30
local dx = (xf - x0) * 30
local t = 1 / display.fps
local a = t * t * -9.8

vy = math.sqrt(2 * a * dy) * display.fps * -1
vx = dx * math.sqrt(a / (2 * dy)) * display.fps

local startingVelocity = { x=vx,  y=vy}

```
> 0 votes

---
Tags: physics, mathematics, lua, corona-sdk
---


# Question
Title: How to determine what color will be written into single pixel framebuffer?
I thinking about rendering into single pixel (1x1) framebuffer. For example we have two triangles which covers whole NDC area, one is green second red.

What color will be written to 1x1 framebuffer? As far as I understend graphic API (no matter which) tries to put whole scene in to given framebuffer, in our example, into single pixel. But I can't figure how GPU will choose what should be written into that pixel.

# Answer
If I understand your question right you want to know how the gpu rasterizes polygons from vectors to pixels?

This image shows how Direct3D chooses what pixels to draw, I don't know how OpenGL does it but I imagine it must be something similar.

A pixel is drawn if it's within all edges and/or passes the *top-left* rule which state that the center of the pixel must lie on the top edge (if present) or on the two left edges (if there is no top edge there may be two left edges, otherwise there's only one).

If we take your example of two triangles, one green, one red, then the single pixel will be the color of the triangle containing most of it.
> 4 votes

---
Tags: opengl, directx, rendering, gpu, frame-buffer
---


# Question
Title: Resolving collisions with float precision errors
I'm facing a problem when I try to resolve the collision between two units using floats as positions of the units in my game.

I am detecting the collisions using the SweptAABB algorithm and if there is a collision I fix it by using the normalized collision time that the SweptAABB function returns. Something like this:

```
collisionTime = SweptAABB(unitA, platform)
fixedPosition = (currentPos - previousPos) * collisionTime;

```

This generally works fine but not always, due of the floats precision errors the fixedPosition can result in a VERY SMALL overlap. For example: suppose that the fixedPosition for the Y axis should be 12.345234 to avoid the collision but instead of getting that value (after multiplying by the collisonTime) I get something like 12.345239 (a difference of 0.000005) and when eventually the overlap method is executed it will still detecting the overlap:

```
public boolean overlap(AABB b) {
    Vector2 distance = new Vector2(b.position).substract(position);

    return Math.abs(distance.x) < (extents.x + b.extents.x)
        && Math.abs(distance.y) < (extents.y + b.extents.y);
}

```

So I decided to start changing the code so that I can get the face of the box that collides and use simple arithmetic addition of the positions instead of multiplication but this also fails for the same reason. For instance, suppose this:

```
// unitA collides with unitB at this point in the X axis:
float unitB_Face_X = 0.7466669f;
// since position is defined at the center of the unit I move unitA to the right:
float unitA_Fix_X = unitB_Face_X + 2;

```

But unitA\_Fix\_X will result in a slightly different value (2.746667) that will eventually be detected as an overlap.

Just a clarification: My game is like Super Mario Bros, a 2D platform. I dont need fine precision, two decimals places (or one) is more than enough for my game world (each unit character has 1f for width and 2f for height).

I think that there must be a correct way to deal with this kind of problem (every 2d platform game out there has solved this problem). I have only think in one solution: Use integers instead of floats for the position of every unit in my game. I cannot avoid floats completly because of deltaTime (also libgdx uses them for the sprites positions and rendering), but I think I can make the integer conversion at the begining of each frame by doing something like this:

```
float fPos = unitA.velocity * deltaTime;
int intPosition = (int)(fPos * 1000);

```

And use the intPosition for detecting and resolving the collisions. After that I will have to convert it back to float for rendering the sprites.

Is this a bad approach? I dont want to shoot my self in the foot. Thanks in advance.

# Answer
Common practice dealing with imprecision of floats is to introduce Epsilon to all "near-zero" checks e.g.:

```
const float Epsilon = 0.00001;
public boolean overlap(AABB b) {
    Vector2 distance = new Vector2(b.position).substract(position);

    return Math.abs((Math.abs(distance.x) - (extents.x + b.extents.x))) > Epsilon
        && Math.abs((Math.abs(distance.y) - (extents.y + b.extents.y))) > Epsilon ;
}

```

Fixed precision(as you suggested) could be solution too, but it basically requires you to implement whole new numeric type - and as always lot of extra code(untested by year of usage) can, and probably will, lead to bugs and errors. If you find it more comfortable and you are willing to risk spending several extra hours in debugger, there is no reason not-to go for it.
> 1 votes

---
Tags: java, collision-detection, libgdx, collision-resolution, aabb
---


title: How to make my Object Zig Zag

text:
# Question
Title: How to make my Object Zig Zag
I have an object in 3D space with a certain height (y) component that I wish to remain constant.

The object is a rigidbody, kinematic, affected by gravity and a trigger. So I tried this method following a similar StackOverflow answer:

```
public class ZigZagSun : MonoBehaviour
{
private Vector3 pos1 = new Vector3(0f, 1.1f, 0);
public float speed = 1.0f;
public float amplitude = 8.0f;
float t = 0f;
//resets position of the ZigZagSun
void Awake()
{
    transform.position = pos1;
}
// moves object from pos1 to pos 2
void Update()
{
    pos1.x = amplitude * Mathf.Cos(t);
    pos1.y += speed * Time.deltaTime;
    t += Time.deltaTime;
}
}

```

However instead of moving my Object remains still in space at (0,1,0) I am wondering what exactly it is that I have done wrong? is it to do with the object being static?

# Answer
> 0 votes
Did you forget to update the position on each frame? Something like this should do it:

```
void Update()
{
    pos1.x = amplitude * Mathf.Cos(t);
    pos1.y += speed * Time.deltaTime;
    t += Time.deltaTime;
    transform.position = pos1;
}

```

# Answer
> 0 votes
When you call `transform.position = pos1;` you set the transform to a *copy* of the current values of `pos1`, not to a *reference*. Changing `pos1` afterwards doesn't do anything.

To move the object, either write the changed position back to the transform component with `transform.position = pos1;` or even better just use `transform.Translate`:

```
void Update()
{
    transform.Translate( new Vector3 (
        amplitude * Mathf.Cos(t),
        speed * Time.deltaTime,
        0.0f
    ));
    t += Time.deltaTime;
}

```

Note: this makes the object move in a cos(t)² curve, not a cos(t) curve, but I wanted to keep it simple to show you the concept.

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


# Question
Title: Saving data in the local computer with cocos2d-js
Making a game with cocos2d-js, is there a reliable way to create saved data in my local computer? I see that there is `cc.sys.localStorage` but it is removed if the user clears the browser's cache or when they simply use another browser.

# Answer
> 1 votes
With JavaScript you don't have a way to persist things transparently other than local storage. I don't know anything about cocos2d but this is really a question about JS. If you really need something persisted you have a couple options.

First you can fake your browser into thinking you want to download something, you can do this by using a library like https://github.com/eligrey/FileSaver.js. You won't have any control over where the saved file lives on the machine though and likely won't be able to read it back in unless you have the user navigate to it themselves.

The second option is just to accept localStorage's limitations. Depending on what you are trying to achieve this is probably a good way to go, just know that not all browsers support it and the amount of data you can store is limited.

The third option is to use a server to handle saving the file. I know you asked for how to store something locally, but I think this is your best bet unless you can't require an internet connection. You can write your own or use something like Firebase which is awesome and has a free tier that is pretty solid.

# Answer
> 1 votes
Most web browsers implements kind of JS Sandbox that blocks any interaction with the real machine, JS just has power over the webkit/gecko/... layer that works like a "virtual machine", that's all, any interaction with the host is blocked by default.

Anyways there are ways to interact with the OS layer and the filesystem via JS via some tweaking like creating an browser plugin, tweaking and compiling your own browser to build a bridge between the browser engine and the host or using webkit standalone implementations like nodejs/nwjs.

Most mobile games that are built in JS uses a hibrid implementation that runs the JS code in a embedded browser in a native aplication, some of them has it's own API to access the ANDROID/IOS API allowing the interaction with the device from JS.

So no, you can't get control of the filesystem without a third app/plugin/... from a webpage.

To store raw data in a device there are some options, the well-knonw coockies, the localStorage and the sessionStorage, but you can't write permanent files.

IMHO, To get rid of your problem i would give a option to the user to download the .sav file (a .json with all the data you want to store) and give him the option to load from a .sav file.

(.sav is just an example, the extension doesn't matters)

hope this helps.

---
Tags: javascript, web, cocos2d-x-js
---


# Question
Title: Leapfrog integration vs Euler integrator
I am looking at various integration methods for my n-body simulation and I'm slightly confused about actual implementation of leapfrog integration.

According to the wikipedia page leapfrog method is defined like this:

When I imagine how to code it, i come up with something like this:

```
while true:
    dt = time since last frame

    for every object:
        object.position += object.velocity * dt

    for every object:
        acceleration = object.calculate_acceleration()
        object.velocity += acceleration * dt

    render()

```

But this is Euler integration, right?

So moving the initial velocity back by one half step makes a first order method into a second order method? But for me a small change of initial velocity is not important, it will be set as a random value anyway...

Why I won't just use velocity verlet: This is for a game where tens of thousands particles fly around affected by forces roughly resembling gravity. I'd like to keep amount of data stored in every partile as low as possible to improve cache locality, which is why I don't want to use a method that requires storing acceleration (and recalculating it would be too slow).

# Answer
The leapfrog method works by using a variable at a non-integer time step to determine the new value of a different variable.

<sub>(source: drexel.edu)</sub>

So the new position values are calculated using the velocity half a time step ahead of the position. This is done for the same reason that a similar method is used in the mid-point method (however the leapfrog method has some advantages i.e. it is reversible and hence useful for oscillating systems).

If you want to run the leapfrog method one possible way is using,

```
while true
    dt = time since last frame

    for every object:
        // If first time object is moved determine velocity at midpoint
        if object.firstmove
            object.velocity += acceleration * dt / 2
        object.position += object.velocity * dt

    for every object:
        acceleration = object.calculate_acceleration()
        object.velocity += acceleration * dt

    render()

```

So the objects store the velocity not at the given time step but at time step + 1/2.

**Potential problems**

Since you are not storing the velocity at a particular time step but instead at time step + 1/2 any processes which use this velocity for calculations may not be correct.

This is also true for the acceleration, the leapfrog method assumes that the acceleration does not depend on the velocity. So the acceleration only depends on the position, hence the velocity 'leaps' over the position.

However, if your `object.calculate_acceleration()` function uses the velocity then it will not be a true leapfrog method as the velocity will be leaping over itself and you will be using information both from the current time step and the time step + 1/2.

Example; friction in the form of drag is often dependent on `velocity^2` (as one would expect the faster the object the larger the drag).

**Other notes**

The added line in my code snippet is simply changing the initial velocity to the new time step. If this is not important then you simply return to the normal Euler integration

**On the order of the method**

According to wikipedia the leapfrog method can also be written as,

which is a second order method. These equations can also be used to perform your integration and may be easier to understand. Again note that here the acceleration cannot depend on the velocity otherwise the second equation becomes much more complicated.
> 7 votes

---
Tags: physics, integration
---


# Question
Title: On Android, why would you handle expansion files yourself instead of using Google Play?
Why aren't all Android games using Google Play's ability to serve their expansion files? Why some are handling it themselves inside their apps?

# Answer
> 1 votes
Since I cannot comment, but still would like to supplement Hamza Hasan's answer, it is correct that the Play Store allows for only 100MB now (which would then require an OBB extension file), but a good reason why you would handle these yourself instead of storing it on Google is the total control over it: even though it's very simplified, uploading any new version to the Play Store can take some time, so you could host your expansion in your own server and drive the updates yourself, with almost no delay for patches. It can be really useful for online games and such, but it comes with a caveat: your server won't always be better than Google's, in terms of speed, so unless you're rocking a premium AWS, there's a chance you'll get overloaded, and that unfortunately happens a lot with amateurish multiplayer games on Android when they are fetching big updates.

# Answer
> 2 votes
APK expansion file is due to oversize of apk build. When ever you get 50+ mb size of apk, you have to split it into main APK and OBB expansion file. Now as far as your last part of question is concern, other games have their own servers to minimize and optimize their game, with respect to size and performance. For example a game has 50 levels. But in initial downloaded build you will have starting 10 levels. When you get at 11th level, next 20 levels will be downloaded in minimum time, otherwise all 50 levels will take time to download, that will make bad impact in user experience. Hope you understand.

**Update:**

APK files have a maximum file size, based on the Android version your APK supports:

100MB - APKs that target Android 2.3 and higher (API level 9 or higher)

50MB - APKs that target Android 2.2 and lower (API level 8 or lower)

Source link

---
Tags: android, google-play
---


# Question
Title: Pixel Shader from Visual Studio Graphics Diagnostics
i want to check my pixel shader variables in graphics diagnostics but unfortunately when i click start debugging in pixel history (mentioned below), a new tap will open and says source is not available. am i have to do anything before start debugging my shader in graphics diagnostics tool ?

Thanks

just to mention that, I use DirectX 11 and C++

# Answer
The reason was because of my .fx shader instead of .hlsl files.
> 0 votes

---
Tags: shaders, directx11, hlsl, visual-studio, c++
---


# Question
Title: Trouble GamePad input on iOS but works perfect on Android
I am having trouble getting input from on iOS devices (iPhone 6 Plus and iPad). Here is my code,

```
    if (Input.GetKey (KeyCode.JoystickButton14))// A
    {
        chr_show = "A";
    }
    if (Input.GetKey (KeyCode.JoystickButton13))// B
    {
        chr_show = "B";
    }
         ...........................................

    if (Input.GetKey (KeyCode.JoystickButton11))// Select
    {
        chr_show = "SELECT";
    }

```

And in OnGUI()

```
    GUI.Label (new Rect(0,0,100,100), "Pressed Button : "+chr_show, guiStyle);

```

Code works perfect on Android device. I also have tried following:

```
        if (Input.GetButton ("JSButton"))// JSButton
        {
            chr_show = "JS Button 14";
        }

```

Please Help Me!

# Answer
> 0 votes
Have you validated that the gamepad gets connected on device? The following page in the manual uses a script to check that the controller connection was a success. Use GUI to display the connection.

http://docs.unity3d.com/Manual/iphone-joystick.html

Next step is to validate the button configuration.

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


# Question
Title: How to implement rotating rectangle around circle in libGDX Box2D?
I want to implement rotating rectangle around cicrle in such way, that circle has no rotation, and rectangle has, and I could myself control rotation of this rectangle (I mean set its angular velocity). All object's are Box2D `Body` objects. Here is picture, what I want to have:

In my case rectangle touches circle, but I think it doesn't matter.

At first I tried to do it with two `Fictures` for same `Body`, but there was a problem with rotation: I couldn't have one ficture with rotation and another without.

I think, it should be somehow connected, but I don't know what exactly `Joint` I should use.

I tried to use `DistanceJoint`, but there was a problem, that I couldn't control Rectangle: when I even linear velocity of rectangle to 0 in `render()` method it continued to rotate.

Maybe are there another solutions?

P.S. It's important, that Cicrle should be `DynamicBody`, not `StaticBody`.

# Answer
> 3 votes
You can achieve this using a `RevoluteJoint` to anchor the "*motor*" to a point in the world, and a `WeldJoint` to anchor the rotating box to the "*motor*".

In my example I've used two **static** bodies, one for the circle that shouldn't move, and one for a small box inside the circle that will serve as the anchor point in the world.

The dynamic `rotator` `Body` is attached to the `anchorBody` using the `RevoluteJoint` and then the `box` (which is also dynamic) is welded to the `rotator` (which serves as the engine) using a \`WeldJoint'.

The result looks like this;  Sorry about the artifacts, the gif capture seems to be broken.

Full source for the above looks like this;

```
package com.bornander.androidstudiosandbox;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.Shape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.physics.box2d.joints.RevoluteJointDef;
import com.badlogic.gdx.physics.box2d.joints.WeldJointDef;

public class MyAndroidStudioSandboxGame extends ApplicationAdapter {
    World world;
    OrthographicCamera camera;
    Box2DDebugRenderer renderer;

    @Override
    public void create () {
        camera = new OrthographicCamera(100, 100);
        camera.position.set(0,0,0);

        world = new World(Vector2.Zero, true);

        renderer = new Box2DDebugRenderer();

        Body visibleCircle = createCircle(5, 0, 0);
        visibleCircle.setType(BodyDef.BodyType.StaticBody);

        Body anchorPoint = createBox(2, 2, 0, 0);
        anchorPoint.setType(BodyDef.BodyType.StaticBody);

        Body rotator = createBox(4,4,0,0);
        rotator.setType(BodyDef.BodyType.DynamicBody);

        Body box = createBox(4,4,8,0);
        box.setType(BodyDef.BodyType.DynamicBody);

        RevoluteJointDef revoluteJointDef = new RevoluteJointDef();
        revoluteJointDef.initialize(anchorPoint, rotator, anchorPoint.getWorldCenter());
        revoluteJointDef.enableMotor = true;
        revoluteJointDef.motorSpeed = 20;
        revoluteJointDef.maxMotorTorque = 50;

        WeldJointDef weldJointDef = new WeldJointDef();
        weldJointDef.initialize(rotator, box, rotator.getWorldCenter());

        world.createJoint(revoluteJointDef);
        world.createJoint(weldJointDef);

    }

    private Body createBox(float w, float h, float x, float y) {
        BodyDef nodeBodyDefinition = new BodyDef();
        nodeBodyDefinition.type = BodyDef.BodyType.DynamicBody;
        nodeBodyDefinition.position.set(10, 10);

        PolygonShape shape = new PolygonShape();
        float density = 1.0f;
        shape.setAsBox(w / 2.0f, h / 2.0f);

        Body body = world.createBody(nodeBodyDefinition);
        body.setUserData(this);
        body.setTransform(x, y, 0);
        final FixtureDef nodeFixtureDefinition = createFixtureDefinition(shape, density);

        body.createFixture(nodeFixtureDefinition);
        shape.dispose();

        return body;
    }

    private Body createCircle(float r, float x, float y) {
        BodyDef nodeBodyDefinition = new BodyDef();
        nodeBodyDefinition.type = BodyDef.BodyType.DynamicBody;
        nodeBodyDefinition.position.set(10, 10);

        CircleShape shape = new CircleShape();
        float density = 1.0f;
        shape.setRadius(r);

        Body body = world.createBody(nodeBodyDefinition);
        body.setUserData(this);
        body.setTransform(x, y, 0);
        final FixtureDef nodeFixtureDefinition = createFixtureDefinition(shape, density);

        body.createFixture(nodeFixtureDefinition);
        shape.dispose();

        return body;
    }

    private static FixtureDef createFixtureDefinition(final Shape shape, final float density) {
        final FixtureDef nodeFixtureDefinition = new FixtureDef();
        nodeFixtureDefinition.shape = shape;
        nodeFixtureDefinition.friction = 1;
        nodeFixtureDefinition.density = density;
        nodeFixtureDefinition.restitution = 0.1f;
        return nodeFixtureDefinition;
    }

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

        world.step(Gdx.graphics.getDeltaTime(), 4, 4);
        camera.update();

        renderer.render(world, camera.combined);
    }
}

```

---
Tags: libgdx, box2d
---


# Question
Title: What is an OO way for my input layer to act upon objects?
I'm building a top-down RPG specifically to practice Object Oriented thinking and design. I am keeping in mind coupling, single-responsibility, and so forth. One design issue that's been bugging me is how to ultimately have objects talk while maintaining the loosest coupling possible. As an example, I'm designing the input class now, which will be made up of two layers, like so:

The conundrum is that I don't know how to bridge that gap between Input and HeroActor, which is initialized from the PlayState class, which is also where the hero.update() method is called. Let's say Keyboard has just executed

```
public void keyPressed(KeyEvent e) {
    switch(e.getKeyCode()) {
        //Some cases

        case KeyEvent.VK_UP:
            //Assume InputEvent.INPUT1 is a defined enumeration in InputEvent
            inputHandler.passInput(InputEvent.INPUT1);
            break;

        //Some more cases
    }
}

```

I've basically landed here:

```
public class Input {

    public void passInput(InputEvent e) {
        switch(e) {
            //Some cases

            case InputEvent.INPUT1:
                ????????????????????

            //Some more cases
        }
    }

}

```

My ideas have been:

* Pass a reference to the instance of HeroActor to the Input object, then have Input directly call the moveUp() method on the HeroActor instance.

```
case InputEvent.INPUT1:
    actor.moveUp();

```

My instinct tells me this is bad OO design as it tightly couples the two classes.
* Make the instance of HeroActor global and basically do the same as above. Even worse OO design.
* Write a registerInput(Input inputHandler) function in the Actor class, like so:

```
public class HeroActor extends Actor {

    //Existing fields and methods

    private Input inputHandler;

    public void registerInput(Input inputHandler) {
        this.inputHandler = inputHandler;
    }

```

Still, then the HeroActor would have to poll the inputHandler every frame to find out if any actions have applied to it.

I'm in the same situation trying to figure out how to write the collision engine without passing it specific references to the player's HeroActor instance or the dozens of EnemyActor instances in the PlayState constructor.

Any help would be greatly appreciated. My request is not for specific code, but rather common techniques for handling the many objects in a game without ending up with a god object. I've seen some material suggesting an Observer pattern being applied for things like the input layer above, but before I go too far, I'd like some feedback from the community since I've got so many different answers among all of my Googling today.

# Answer
You are right that directly coupling input handlers with actors introduces messy situations: for example, what happens if the actor dies - do you add alive checks in your input handler, or do you go through all your input handlers and invalidate their actor references? What if you are in a different context, like a modal menu?

I'm reminded of the **MVC** pattern which deals with a similar problem: by introducing an intermediary **controller** between the **models** (your actors) and **views** (your input handlers), you can interchange different views and models without affecting the other, and you get a lot of flexibility. Therefore I think you should have some intermediary between your input handlers and actors.

A common solution is to, yes, use the Observer pattern. One of your actors and input handlers agree to observe/notify on a common subject: movements for player number 1, so any time the input handler notifies about player 1 movement, the observing actor will move in reaction. The neat thing about this little bit of indirection is the flexibility you get:

* Anything can control the actor as long as they talk about "movements for player number 1" - think AI or scripted scenes. But you know this already, since you've implemented the Command pattern.
* The input handler can control anything as long as they observe "movements for player number 1". You can control multiple actors, or no actors (when the actor dies), or sneaky beaky like enemies.
* A typical use case for that last point is driving menu systems.
> 4 votes

---
Tags: software-engineering, input
---


# Question
Title: Unity setting rectTransform on an UI Image with a Vector3, do I need to convert coords?
I am trying to build a menu with a cursor. I created the menu and that in the unity UICamera on the canvas. It looks great. I want the cursor to move so what I did was move the cursor by hand and record the values at each location I want the cursor to possibly be (see attached). The problem is later when I try to set the value to these via this:

```
pauseCursor.rectTransform.position = new Vector3 (-45f, -80.6f, 0);

```

It fails and looking in the inspector again the x,y values are like 300, 800 or something. I am guessing I need a conversion I just am not sure where or how. Do I get the Ui camera reference and use the WorldToScreen?

# Answer
You want to use `localPosition` (the position of the GameObject in relation to its direct parent). Otherwise it will set the absolute/global position and it will re-calculate the `localPosition` (that's the one that actually shows up in the inspector) and will look wrong.

```
pauseCursor.rectTransform.localPosition = new Vector3 (-45f, -80.6f, 0);

```
> 1 votes

# Answer
Use this instead :

```
pauseCursor.rectTransform.anchoredPosition = new Vector3 (-45f, -80.6f, 0);

```
> 0 votes

---
Tags: unity, ui-design
---


# Question
Title: Orbits: Combine the Pros of RK4, Symplectic Euler, and Verlet Velocity Integrator
Recently, I've implemented and compared a number of basic integrators for my physics engine. The 3 that gave me the best results are RK4, Symplectic Euler, and Verlet Velocity, but I think I need something a little more advanced. I've done many Google and StackExchange searches but haven't found what I'm looking for.

I'm looking for something that combines the strengths of those integrators without their weaknesses. I'm only concerned about orbital mechanics. Drag and other similar forces will not be put through the integrator because it's not important that I get perfect answers for those other forces, but (near) perfect answers are very important for my orbital mechanics. Computationally expensive algorithms (within reason) are not as much of a concern as accuracy is.

My thoughts and primary concerns are as follows:

* RK4 Pros: Very accurate.
* RK4 Cons: Loses energy over the long term. This sim needs to be able to run for a VERY long time, so experiencing this kind of "orbital decay" is quite undesirable.
* Symplectic Euler and Verlet Velocity Pros: Symplectic/Don't lose energy.
* Symplectic Euler and Verlet Velocity Cons: Much less accurate. Highly eccentric orbits make this apparent very quickly...even with a simple massless-satellite-orbiting-a-massive-object scenario, the satellite's orbit "rotates" around the parent object over longer periods of time. This is extremely undesirable behavior.

For my purposes, I cannot resort to orbits "on rails".

***TLDR: I am looking for an algorithm that gives me the accuracy of RK4 without the slow decay. Computational expense is not a major concern.***

Thanks in advance for the help!

**Update 1:** I found a similar question here: https://stackoverflow.com/questions/3680136/help-with-symplectic-integrators

There might be good answers in the accepted answer, but after several hours of study, I have only determined that they are very difficult to understand. I will keep studying the accepted answer's linked paper and source code and post an answer if I get results. However, I suspect that while the algorithm is not much more complicated than RK4, the symbology and style of the linked explanations/source code are making it very difficult for anyone without a heavy math/physics background to understand. Unfortunately, as a comment noted, the OP accepted that answer, but never came back and gave a clearer explanation himself. I'll leave this question open and keep studying myself. Hopefully, together we can come up with a clearer answer for future searchers!

# Answer
> 1 votes
I suggest using Cartesain Orbit Elements , with rk4 in real time simulation. Switch to kepler Orbit Elements (orbit as a function of time) when you augment timestep. Try this answer of mine as reference

Another example schenario: when your orbital body is subject to only gravity force , use kepler Orbit Elements , whe you turn on body engine (to add/decrease prograde speed), swith to Cartesain Orbit Elements (with rk4) , at the end of acceleration proces (when turno of engines) swith back to kepler Orbit Elements (on rails).

The approach I described suffers if there are more than two objects , in this case you may integrate considering Sphere of influence.

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


# Question
Title: Unable to capture a frame of a specific game in PIX for Windows, although in other game it works
I'm trying to get the 3D models from a 2001 3D DirectX game with PIX for windows. It just doesn't work for some reason.I tried all options from PIX (A single frame capture of Direct3D,A replayable Direct3D call stream etc. I tested by trying on other more recent game and works.

What can I do to make it work? Thank you.

# Answer
Your game from 2001 most likely use Direct3D 8 since 9 was released 2002.

Pix is a very deprecated tool used only for debugging your own applications written in Direct3D 9+.
> 0 votes

---
Tags: pix
---


# Question
Title: How can I access to all component of a certain type in Unity?
I want access to (for example) all AudioSources in Unity and stop all sounds.

```
using UnityEngine;
using System.Collections;

public class StopAllSound: MonoBehaviour {

    void Start() {
        AudioSource[] allMyAudioSources = GetComponents<AudioSource>();
        allMyAudioSources.Stop();
    }
}

```

This does not work, because of the followin error:

```
Assets/SlowMotion.cs(8,35): error CS1061: Type `UnityEngine.AudioSource[]' does not contain a definition for `Stop' and no extension method `Stop' of type `UnityEngine.AudioSource[]' could be found (are you missing a using directive or an assembly reference?)

```

I try it by FindObjectsOfType:

```
using UnityEngine;
using System.Collections;

public class SlowMotion : MonoBehaviour {

    void Start() {
        AudioSource[] allAudioSources = UnityEngine.Object.FindObjectsOfType<AudioSource>();
        allAudioSources.Stop();
    }
}

```

but I get the same error.

# Answer
> 5 votes
Because Array doesn't contains `Stop`. But AudioSource does. So take all AudioSources in loop and Stop them as `AudioSource` not `AudioSource[]`. Array of anything having its own attributes and methods irrespective of what type of element that array contains.

You can do that by,

```
using UnityEngine;
using System.Collections;

public class StopAllSound: MonoBehaviour {

    void Start() {
        AudioSource[] allMyAudioSources = FindObjectsOfType<AudioSource>();
        foreach(AudioSource s in allMyAudioSources)
            s.Stop();
    }
}

```

# Answer
> 1 votes
If you want to mute *all* sounds in your game, then it might be far more elegant to not mute your audio sources but mute the `AudioListener` instead. You can do this with `AudioListener.pause = true` or `AudioListener.volume = 0.0f`.

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


# Question
Title: Algorithm for dynamically calculating a level based on experience points?
One of the struggles I've always had in game development is deciding how to implement experience points attributed to gaining a level. There doesn't seem to be a pattern to gaining a level in many of the games I've played, so I assume they have a static dictionary table which contains experience points vs. the level. e.g.

```
Experience   Level
0            1
100          2
175          3
280          4
800          5

```

...There isn't a rhyme or reason why 280 points is equal to level 4, it just is.

I'm not sure how those levels are decided, but it certainly wouldn't be dynamic. I've also thought about the possibility of exponential levels, as not to have to keep a separate lookup table, e.g.

```
Experience   Level
0            1
100          2
200          3
400          4
800          5
1600         6
3200         7
6400         8

```

...but that seems like it would grow out of control rather quickly, as towards the upper levels, the enemies in the game would have to provide a whopping amount of experience to level -- and that would be to difficult to control. Leveling would become an impossible task.

Does anyone have any pointers, or methods they use to decide how to *level* a character based on experience? I want to be fair in leveling and I want to stay ahead of the players as not to worry about constantly adding new experience/level lookups.

# Answer
It's quite common to use a square relation.

`level = constant * sqrt(XP)`

Or the approximate equivalent of a linearly rising level gap.

```
Level   XP      Difference
1       0       -
2       100     100
3       300     200
4       600     300
5       1000    400

```

These systems work pretty well when the XP gain is approximately linear. If a high level character can earn XP faster than a low level character then this is not the right system.
> 43 votes

# Answer
You'll probably find *logarithmic functions* helpful as they can be used to slow down the increase as more experience points are gained. Here are two web pages that explain how these work:

Graphs of Logarithmic Functions
http://www.analyzemath.com/Graphing/GraphLogarithmicFunction.html

Introduction to Graphing Logarithmic Functions
http://www.purplemath.com/modules/graphlog.htm

Here's what it looks like on a graph, which will hopefully meet your needs:
> 17 votes

# Answer
These are some ways I've used so far. They are sorted by grow rate (just multiplied every equation by a constant value):

1. exp = level (this one may seem odd but for some games that reward exp changes according to player level like borderlands this one may fit to)
2. exp = level * log10(level)

```
1   0
2   0.6
3   1.4
4   2.4
5   3.5
6   4.6

```
3. exp = level^const\_value : for my example I set const value to 3/2

```
1   1
2   2.8
3   5.1
4   8
5   11.2
6   14.7

```
> 10 votes

# Answer
I think it depends how how easy the player can get the experience. If the player can get 200 xp at lvl 1 in 20 minutes and then get 200 xp at lvl 2 in 2 minutes, then you need to scale your xp exponentially.

However if gaining a level only makes it marginally easier to gain xp, then you should do a more level xp function. (Maybe linear with some coefficient \> 1)
> 5 votes

# Answer
**Consider Time**

You first need to figure out how the **rate of experience gain** scales with level. Then you can tailor your leveling by **time required**. If every additional level allows you to gain experience twice as fast, and you need twice as much experience to level, every level will require the **same** amount of time.

My suggestion is to think about how much **time** the player should spend, then tailor the leveling to that.
> 5 votes

# Answer
Often the points needed to gain a level is based on a curve. In a lot of RPGs were there are also a lot of other characteristics and attributes of your character that increase with your level, they will also be on there own curves.

Take a look at RPGMaker to see how they do things. Specifically look at the parameter curves in the screenshots of the "Add Some Uniqueness to by Customizing Starting Equipment" section of the Creating a Main Character document.

Basically you might have a curve for how much XP is needed to levelup, then different curves for how much HP, MP, stamina, strength etc is gained each level.
> 4 votes

# Answer
Maybe I should just use a flat leveling system, where each level would require exactly the same amount of experience.
> -3 votes

---
Tags: game-design, progression
---


# Question
Title: How to justify friendly shopkeeper in the cave of doom among millions of mobs?
I am exploring the forbidden example cave of doom. I find, among squillions of baddies, a shopkeeper, who just happens to sell stuff inside a deadly cave where nobody goes. Weird. I accidentally cause him to be angry, and he turns out to be more powerful than *literally every monster in the game.* Messed up.

So here's two questions for you: **How can you justify a shopkeeper in the example cave of doom just happening to be there waiting for random adventurers to buy stuff,**

and,

**Is there a better way to discourage stealing stuff or killing the shop-keep' than just making them pummel you with ridiculous power?**

Side note: Bonus points for linking these, explain both why and how he would be down there, in the example cave of doom, surviving without a monster sword or magic to pwn things with, and why it would be a bad idea without him possessing those things, to fight him.

# Answer
1. The cave is where the player is in the game. If we want the player to have access to a shopkeeper, we either have to put the shopkeeper right there, or else we have to build somewhere else for the shopkeeper to be, and building that somewhere else will probably be expensive (in terms of new art required, etc). Additionally, making the player go somewhere else just to find a shopkeeper probably doesn't make the game better; it just adds a bunch of backtracking, or requires that we create Scrolls of Town Portal or something. (If you were asking for an in-game-world reason to justify why a shopkeeper is in the cave, I'll point out that we're talking about "caves of doom", and so a realistic world with internally-consistent lore which will stand up to any trivial amount of scrutiny is pretty much off the table to begin with)
2. If the goal is to stop the player from killing the shopkeeper or stealing shop contents, then make the shopkeeper not be a valid combat target and not allow the player to pick up his shop's contents without paying for them. This seems a little obvious -- almost tautological, in fact. But you asked.

Bonus points: He's down here because (according to point #1) he has to be here in order for the player to meet him, and it's presumably important for the game that the player meet him. And he's survived down here for the same reason: because he has to have survived in order for the player to meet him, and it's important for the player to meet him because if it wasn't important, we wouldn't have gone to the bother and expense of creating artwork for him.

Within the game fiction, he's survived because our world's mechanics are so thin that characters don't age, don't exercise, don't play Scrabble, don't sleep, and mostly don't eat (except occasionally in order to instantly repair themselves after being hit by a sword too often, often while the combat is still in progress). Characters don't require companionship to avoid becoming lonely, they don't require an occasional vacation, and they're happy standing stock-still on a single tile for eternity. Additionally, characters other than monsters and the player (and sometimes the player's companions) never even die, except in expensively-produced cutscenes with orchestral music.

And there's no space for an orchestra down here in the caves of doom.

Which, when you come to think of it, is actually a pretty good reason for the shopkeeper to want to live down here.
> 3 votes

# Answer
**Make the shopkeep a monster too**

Being a freebooter, he holds no particular allegiance to one side (the cave dwelling monsters) or the other (you, the player). But for a bit of coin, he'll sell you whatever he's got. He's been hawking his wares to the other monsters in the cave for years, but you're nothing more than a walking coin pouch to him. He knows that no matter how many of his 'compatriots' you kill, more will show up eventually and his business will continue.

Or maybe monsters don't respawn in your game, in which case, after the player leaves (the cave devoid of monsters), he despawns too: he closed up shop and went off to find somewhere else to pawn his goods. Maybe you'll run across him again later somewhere else...
> 6 votes

---
Tags: npc
---


# Question
Title: How to optimize movement script using CharacterController component?
I've made a very basic character controller using a CharacterController component. I'm still a beginner so I keep learning new things. My problem is how to optimize my controller script. Also, I would like to learn more about physics and things like this but I can't find any good tutorial or documentation, so if you know where I can find some interesting information (I'm not talking about Google here), I'd be glad if you share them with me.

My character falls way too slowly. Also, I can midair movement should be limited. My next problem is that my character levitates after hitting a platform or something with its head before reaching its max jump height. Another thing is that it can "levitate" next to platform just because it touches a collider, where normally it should just fall down.

So here's the code:

```
using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

public float moveSpeed = 9.5f;
public float jumpSpeed = 1.5f;
public float gravity = 7.0f;

CharacterController controller;
Vector3 currentMovement;

public Transform [] startPoint;

void Start ()
{
    controller = GetComponent<CharacterController>();
}

void Update ()
{
    currentMovement = new Vector3(Input.GetAxis("Horizontal") * moveSpeed, currentMovement.y, Input.GetAxis("Vertical") * moveSpeed);

    if(!controller.isGrounded) // Można również zapisać jako if(controller.isGrounded == false)
        currentMovement -= new Vector3(0, gravity * Time.deltaTime, 0); // Można zapisać jako currentMovement.y -= new Vector3(0, -gravity * Time.deltaTime, 0)
    else
        currentMovement.y = 0;

    if(controller.isGrounded && Input.GetKey(KeyCode.Space))
    {
        currentMovement.y = jumpSpeed;
    }

    controller.Move(currentMovement * Time.deltaTime);

    if(Input.GetKeyDown(KeyCode.X))
    {
        gameObject.transform.position = startPoint[0].position;
    }

    if(Input.GetKeyDown(KeyCode.Escape))
    {
        Application.LoadLevel(0);
    }
}
}

```

# Answer
> 0 votes
Your character falls too slowly because of these two lines:

```
currentMovement -= new Vector3(0, gravity * Time.deltaTime, 0); //multiply by deltaTime
controller.Move(currentMovement * Time.deltaTime); //multiply by delta time again

```

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


# Question
Title: Monogame project runs in VS but hangs when run via .exe
I've been working on a monogame project for a little over a week and had no problems. Today I went to test out the project outside of Visual Studio, by running directly from the .exe in the release folder. When I click on the .exe I get the cursor icon indicating something is loading, but nothing ever does. No window shows up, even though I see processes related to my game in the task manager. Also when I try to end mygame.exe in the taskmanager it doesn't work and the process still sits there.

I've tried both a Windows and Windows OpenGL monogame project and both hang once I click the exe. Does anyone have any idea why this may be or any steps I might take to track down the issue?

I'm using Windows 7, Visual Studio Community 2015 and the latest Monogame Build. My project references Farseer Physics, Lidgren, Json .Net, and my own Utility class library.

**Edit:** I tried creating a brand new Monogame project and run it without debugging in VS and it hangs the same way running from the .exe does. Also the project runs when placed on my laptop which also has monogame installed so it's nothing wrong with the project.

# Answer
So I was sitting here staring at my computer wondering why it absolutely refused to run my program, and then it hit me. I went to my anti-virus, turned it off, and voila, it works.

I don't know why Avast didn't come up with some sort of message about the program being unsafe or anything, but at least now I know what the problem was. I'm a little worried about what these means for anyone else running the same AV but at least I can start developing again.
> 1 votes

---
Tags: monogame, visual-studio
---


# Question
Title: What considerations should I be aware of when placing an Unreal project under source control?
I want to give it a try to creating a git repository from my UE4 project and uploading it to Github.com but I wonder what special considerations should I have to avoid posting sensitive information like my developer key/certificate, or avoid adding large binaries files, or temporary/intermediate files.

# Answer
Things like your registration information for UE4 and whatnot aren't stored with the projects, they're stored elsewhere (with the application data for the UE launcher or toolchain, probably).

By far the easiest way to prep for posting your project on GitHub is to use the UE editor's ability to initialize source control access in the project. You do that by clicking the "Source Control" button in the toolbar:

In the resulting window, set the provider to Git (you'll want to make sure you have Git installed; if you do and have your Git configuration set up, it will populate everything for you). Make sure the checkbox to generate a `.gitignore` is checked, and hit accept. It will do all the hard work for you.

If you aren't using the editor, if you're working directly with the engine from source or something, or you just want to do everything yourself, you'll want to set up a `.gitignore` that basically excludes all the generated/intermediate file directories, like this (which is basically the one the editor would set up):

```
Binaries
DerivedDataCache
Intermediate
Saved
*.opensdf
*.sdf
*.sln
*.suo
*.xcodeproj
*.xcworkspace

```

Beyond that, there isn't anything really special you need to do. You may want to consider something like git-annex to deal with large assets that you'll want to check in.
> 3 votes

---
Tags: unreal, git
---


# Question
Title: How can I avoid instantiating multiple instances of a RigidBody?
I could use a little help.

I've a state machine for an NPC that does a melee attack. The problem I'm running into is that the current code instantiates multiple instances when I only need one per cycle.

I could use some ideas.

This is the chunk of code I'm working with:

```
public void ChaseToAttack()
{
    _navMeshAgent.speed = 3.5f;//slow down the navAgent

    float playerDistance = Vector3.Distance(chaseTarget.position, transform.position);
    //stop navMeshAgent to begin attack sequence
    if (playerDistance <= stopAtDistance)
    {
        /// ensure enemy is always looking at player
        enemyToTarget = ((chaseTarget.position + offset) - eyes.transform.position);
        if(Physics.Raycast(eyes.position, enemyToTarget, out _hit, sightRange) && _hit.collider.CompareTag("Player"))
        {
            _navMeshAgent.Stop();
            currentState = _attackState;
            //StartCoroutine(FistTimer());
            PunchCycle();
        }
        /// ensure the enemy isn't hitting air & will always look for the player
        else
        {
            transform.Rotate(chaseTarget.position, searchTurnSpeed * Time.deltaTime, 0);
        }
        /// end look & atttack player block
    }
}

void PunchCycle()
{
    StartCoroutine(AttackCycle());
}

void PunchClone()
{
    clone = Instantiate(pfbPunch, transform.position, transform.rotation) as Rigidbody;
    clone.transform.Translate(0,1f,0);
    clone.velocity = transform.TransformDirection(0.0f,0.0f,0.125f * punchDistance);
}

IEnumerator AttackCycle()
{
    //move animation here
    AnimPunch();
    PunchClone();
    yield return new WaitForSeconds(4f);//fistTimer
    BeAlert();

}

```

Thanks in advance...

**EDIT:**

Changed the code so it would only instantiate once- but now, it will only instantiate only once even though it's still in the attack sequence.

```
    public void ChaseToAttack()
{
    _navMeshAgent.speed = 3.5f;//slow down the navAgent

    float playerDistance = Vector3.Distance(chaseTarget.position, transform.position);
    //stop navMeshAgent to begin attack sequence
    if (playerDistance <= stopAtDistance)
    {
        /// ensure enemy is always looking at player
        enemyToTarget = ((chaseTarget.position + offset) - eyes.transform.position);
        if(Physics.Raycast(eyes.position, enemyToTarget, out _hit, sightRange) && _hit.collider.CompareTag("Player"))
        {
            _navMeshAgent.Stop();
            currentState = _attackState;
            StartCoroutine(AttackCycle());
        }
        /// ensure the enemy isn't hitting air & will always look for the player
        else
        {
            transform.Rotate(chaseTarget.position, searchTurnSpeed * Time.deltaTime, 0);
        }
        /// end look & atttack player block
    }
}
void PunchClone()
{
    if(!didClone)
    {
        clone = Instantiate(pfbPunch, transform.position, transform.rotation) as Rigidbody;
        clone.transform.Translate(0,1f,0);
        clone.velocity = transform.TransformDirection(0.0f,0.0f,0.125f * punchDistance);
    }
    didClone = true;
}
IEnumerator AttackCycle()
{
    //move animation here
    AnimPunch();
    yield return new WaitForSeconds(0.75f);//fistTimer
    PunchClone();
}

```

# Answer
> 1 votes
So I've found a simple solution to synchronize the punch sequence without having to deal with coroutines or instantiating/destroying rigidbodies.

```
public void AttackCycle()
{
    _navMeshAgent.Stop();
    AnimPunch();
    nmeFistL.SetActive(true);
    if (_animation["nmePunch"].time >= 1.5f)
    {
        nmeFistL.SetActive(false);
    }
}

```

# Answer
> 0 votes
I am not sure why you have to instantiate the Rigidbody, but you can just destroy them when you are done punching.

```
Rigidbody PunchClone()
{
    clone = Instantiate(pfbPunch, transform.position, transform.rotation) as Rigidbody;
    clone.transform.Translate(0,1f,0);
    clone.velocity = transform.TransformDirection(0.0f,0.0f,0.125f * punchDistance);
    return clone;
}

IEnumerator AttackCycle()
{
    //move animation here
    AnimPunch();
    Rigidbody r = PunchClone();
    yield return new WaitForSeconds(4f);//fistTimer
    Destroy(r.gameObject);
    BeAlert();

}

```

Edit : If you need only one instance active at any time, then going with your boolean method is fine, but you have to set the boolean to false again. You can do that where I do the Destroy(r.gameObject).

# Answer
> 0 votes
`void PunchClone()
{
 if(!didClone)
 {
 clone = Instantiate(pfbPunch, transform.position, transform.rotation) as Rigidbody;
 clone.transform.Translate(0,1f,0);
 clone.velocity = transform.TransformDirection(0.0f,0.0f,0.125f * punchDistance);
 }
 didClone = true;
}`

There, `didClone=true` should be inside the `if(!didClone){}` block. After the `if` block, add

`else
 didClone=false;`

This will ensure that next time the method is called, the value of didClone will be toggled.

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


# Question
Title: Invoking a common method after a button press
I want to implement a common method that handles several numeric values and performs and action based on those values. So I have buttons with specific methods to change this values without affecting the rest. However I want to link them all to a final method that runs right after the press of a button, so this way the game will change only when the player chooses to change it and changes according to the players decisions. How can I implement this in my script? Most of my methods are like this:

```
public void "ButtonIDGoesHere" (int "SpecificVariable"){
//Add, Sub, Multiply, etc.

}

```

What can I add so that it goes to a common method right after it executes its instructions?

# Answer
> 0 votes
Can't you simply call a common method?

```
public void "ButtonIDGoesHere" (int "SpecificVariable" )
{
    .. whatever you need to do

    // now call the common function
    OnButtonPressed();
}

```

What are we missing?

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


# Question
Title: sf::RectangleShape's position is not same as I set it to
When I try to print my `box.getSfShape()`'s position it does not print out the position I set it to have.

**(** The `box.getSfShape()`'s position is by default set to 0 **)**

Wrong output : **(** printing the position of the `box.getSfShape()` **)**

**(** prints out : `X : 0` `Y : 0` ((These are the default assigned positions)) **)**

```
box.getSfShape().setPosition(box.getBody()->GetPosition().x / b2Meter, box.getBody()->GetPosition().y / b2Meter);

```

But when I print out the calculation only :

```
std::cout << "X : " << box.getSfShape().getPosition().x << " Y : " << box.getSfShape().getPosition().y << std::endl;

```

It prints out a increasing Y value and a X value on 0 like it should do.

---

So, I'm guessing the call to set the `box.getSfShape()` position somehow fails.

---

If you need something more, please tell me what to add :)

# Answer
> 2 votes
So as I mentioned in the comments, the problem is that getSfShape is returning by copy. Although I answered a very similar problem here, it was more a bit of a language specific case. Structs are not related to this in the context of C++, so I'll slightly rephrase what I posted for the other question.

Due to your getSfShape() returning by value, it returns a copy of the shape. This copy is just another RectangleShape, same values, but it is only **a copy** of the RectangleShape. Then on the copy that is returned, you call the setPosition. It won't fail and C++ will happily let you do this, but all you did was edit the copy, which you discard straight away!

The solution to this problem, as you seem to have figured out already, is to have getSfShape() return by reference. This gives you back a reference to the shape you actually wanted to edit and then sets the position. So just for clarity, rather than this (assuming the correct types are used):

```
sf::RectangleShape getSfShape()
{
    return shape;
}

```

You would do something like this:

```
sf::RectangleShape& getSfShape()
{
    return shape;
}

```

Even a little easier than in C#!

# Answer
> 0 votes
I guess you're not updating the SFML shape position after each call to the box2d world.Step().

What type is your `box`? Is that part of a third-party library or your own code?

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


title: How to adjust my games speed to fps

text:
# Question
Title: How to adjust my games speed to fps
Hi so i am making a small sort of physics engine, but if your fps is really slow the physics will update slower and objects will move slower. How do i make the speed of objects greater if the fps is lower so that on a computer with 5 fps the object will land at the same time as on a 60 fps computer? (just with that slow framerate)

# Answer
> 1 votes
Don't use frame rate as your mechanism of time. Rather, use time itself. If you want thing to run at '60' frames per second, you need to calculate everything in terms of time.

Lets say we choose milliseconds as our unit of time.

Now we can do the following:

```
int fps = 60;
double msPerFrame = 1000/fps;

```

When calculating your movements, rather than using the 'currentFrame', use the current running time of the sequence. Start the sequence, and on each frame tick, measure the time since start, and interpolate your values that way.

```
// assume calling 'now()' returns the time, GMT in ms.
long start = now();

void Update()
{
    // get current time each Update
    long now = now();

    // total duration since starting the 'event'
    long durationMs = now - start;

    // use actual frames passed to do your 'physics' updates
    // so erratic calls to update won't appear to make your movement
    // incorrect.
    long actualFramesPassed = durationMs / msPerFrame;

    // ...
}

```

# Answer
> 1 votes
When handling games with a fixed time step, which is what you would need to simulate a physics system, it is best not to go with the system Timer as it is not as precise as other methods (even though the difference is small). Here is an example of how you might go about running a game loop that iterates 60 times a second.

I chose Java as you did not specify your target language.

```
public void run() {
    double ns = 1000000000.0 / 60.0;
    double delta = 0;

long lastTime = System.nanoTime();
long timer = System.currentTimeMillis();

while (running) {
    long now = System.nanoTime();
    delta += (now - lastTime) / ns;
    lastTime = now;

    while (delta >= 1) {
        tick();
        delta--;
    }
        render();
    }
}

```

The running boolean would be set to true at the start of a program and is better practice than simply putting true, especially if there are multiple threads.

What makes this method better than using a Timer is if there is a hiccup or delay in one of the game ticks it is able to compensate. (ie. if the game for whatever reason only iterates 59 times in a second, the next second it will run 61 times) This is important considering performance issues will occur occasionally for whatever reason.

This also gives priority to updates since it will complete every update in query before it will render. Also if you have a different thread controlling the camera or something, it will continue rendering as long as there are available recourse. This is something you want especially in a first person game. (You don't want to limit how fast someone can look around based off of how fast the physics engine runs)

The tick() method would consist of all of the code to run the game. (The parts that include movement and such) The render() method would consist of all of the code to render a frame.

---
Tags: physics, frame-rate
---


# Question
Title: Terminology for the way Transformation Matrix Data is treated
I recently asked a question at math stack exchange and realize a similar questions is more suited for this forum, but the original is here:

https://math.stackexchange.com/questions/1526601/terminology-for-transformation-matrices-update-or-rigid-body-transform

I'm attempting to describe transformation matrix operations within Sketchup's Ruby scripts, and I need some terminology.

Sketchup allows the selection of a group of "loose" drawing objects (i.e. edges and faces), and provides options to create a grouped object from them. The drawing elements inside the group have position data relative to the group's local coordinate system. The grouped objects respond to a getter "transformation" method that returns a transformation object that contains data representing the orientation, scale, and position of the group.

Sketchup's "world space" supports multiple grouped objects, and typically there are numerous grouped entities in the outer level entities, as well as loose drawing objects. Each grouped object has a separate transformation that determines their position, orientation, and scaling in world space.

The transformation can be altered or replaced with methods that include:

a) The "transform" method: Applies a transformation (i.e. like a rotation) to rotate the group; and

b) The "transformation=" setter method: Replaces the existing transformation with the supplied argument.

Lets say I have a grouped object called "entity1" and rotation transformation object called "rotation". To provide the same rotation effect I could perform either of the following in Sketchup's Ruby programming:

```
entity1.transform!( rotation )
    OR
entity1.transformation= rotation * entity1.transformation

```

Only groups and components support the "transformation=" setter method, while fundamental Point3d & Vector3d object provide "transform!" kind of methods. It is obvious, at least from within Sketchup (which uses OpenGL internally), that transformation matrix internal data can be treated as either:

Relative: A transformation performs an incremental operation (Example "entity1.transform! identity" does not have an affect on the grouped model); or

Absolute: The data inside a transformation is treated as absolute position, orientation, and scaling of the grouped object. (Example "entity1.transformation= IDENTITY" sets the model to Sketchup's origin position, the model is de-rotated to the orientation it was when first grouped, and it is descaled)

Questions:

1) What is the terminology for the type of transformation that is supplied to the "transform!" method? I was calling it an "affine", now want to call it an "update transformation".

2) What is the terminology for the type of transformation that is the argument to the setter "transformation="? I have been calling it a "rigid body transformation", and sometimes "absolute transform". It appears that OpenGL is calling this the "model matrix".

3) If I call it "model matrix", is more than one model matrix transform allowed in world space?

A previous english stack exchange article for a word to mean "position and orientation" is at: https://english.stackexchange.com/questions/119883/word-for-position-and-orientation The article responses recommend to use "pose matrix".

# Answer
> 2 votes
I think you're overthinking it.

In Ruby, the `!` is conventionally attached to methods to indicate that the method modifies the object in some way (see this SO thread).

From the documentation of SketchUp's `Group` class, `transform!` *applies* a given transformation to the group whereas setting `transformation` just *replaces* the existing transformation with the new one.

Looking at it another way, `transform!` multiples the current transformation with the provided transformation (it's a `*=` operation) and `transformation=` sets the current transform to the provided transformation (it's `=` operation).

Fundamentally these transformations are just matrices (which are encoding a translation, rotation and scale). **They are the same transformation with the same meaning**, the different methods are simply giving you different ways of interacting.

---

As to your specific questions:

> 1) What is the terminology for the type of transformation that is supplied to the "transform!" method? I was calling it an "affine", now want to call it an "update transformation".

It's just a transformation. It's *probably* an affine transformation because that's usually what we use in 3D graphics. An "update transformation" is not really a generally-accepted piece of terminology, but it is true that `transform!` is updating the existing transformation of the group (of course, so is `transformation=`).

> 2) What is the terminology for the type of transformation that is the argument to the setter "transformation="? I have been calling it a "rigid body transformation", and sometimes "absolute transform". It appears that OpenGL is calling this the "model matrix".

Nope, it's just a transformation. It's not any different. A rigid body is a physical body that does not deform. A "rigid body transformation" would be what you might call a transformation that is conceptually associated with a rigid body (such as the one used to place it in a world), but they are otherwise orthogonal concepts.

What OpenGL calls the "model matrix" is specifically a transformation matrix it intends to be used to move from a specific coordinate system (the coordinate frame in which model geometry is provided) to the next system in the graphics pipeline (the world coordinate system).

"Absolute transformation" is not a generally accepted term either, but in context one would probably expect it to be a matrix that transformed a thing from a well-defined origin instead of relative to some other transformation.

> 3) If I call it "model matrix", is more than one model matrix transform allowed in world space?

Not in OpenGL, but you could just concatenate multiple transformations via multiplication.

---
Tags: opengl, matrix, models, transformation
---