title: LibGDX Overlay Game with Stage

text:
# Question
Title: LibGDX Overlay Game with Stage
I have been working on a 2d game that is similar to billiards/pool. I've got the basic game down and now I'm working on some visual effects. One of the things I would like to do is have have numbers pop up on the screen where a scoring event occurs and then have that number "swoosh up" to the main score at the top of the screen. To accomplish this I have been trying to overlay a Stage onto my main game area so that I can add score text and then let the LibGDX Scene2d take over. I am adding the text as an actor to the stage and then assigning some actions to it to achieve the desired effect. The problem I'm having is that when I add the object I need to convert from world to stage coordinates. This is because I want to place the score popup where two balls touch, which is in world coordinates. I have tried to use the "project" method of the stage's viewport (it is a FitViewport) but the coordinates never translate correctly.

Now that I've explained what I'm trying to do, I was hoping that someone would know how I could pull this off. I'm sure it isn't difficult and that I'm missing some small detail.

Here is the relevant code: This is the class that will be used to overlay a stage onto the main game screen.

```
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.viewport.Viewport;

public class UIOverlay {

    private Skin skin = new Skin(   Gdx.files.internal("skins/gamePlaySkin.json"));
    private Stage stage = new Stage();

    public void init (Viewport viewport) {

        stage.setViewport(viewport);
        stage.getViewport().update(GameWorld.WIDTH, GameWorld.HEIGHT, true);
    }

    public void render () {

        stage.act();
        stage.draw();
    }

    public Stage getStage () {

        return this.stage;
    }

    public void addScorePopup (int score, Vector2 worldPos) {

        Viewport vp = stage.getViewport();
        Vector2 screenPos = new Vector2(worldPos.x, worldPos.y);
        vp.project(screenPos);

        // Some sample vectors after projection:
        // worldPos.x = 0.88585174, worldPos.y = 1.6051532
        // screenPos.x = 0.885849, screenPos.y = 1022.39484
        // Another Set:
        // worldPos.x = 0.63776636, worldPos.y = 0.8991218
        // screenPos.x = 0.63777924, screenPos.y = 1023.1009

        Label popLabel = new Label(String.valueOf(score), skin, "popupScore");
        stage.addActor(popLabel);
        popLabel.setPosition(screenPos.x, screenPos.y);

        float time = 0.5f;
        popLabel.addAction(Actions.delay(1000, Actions.sequence(Actions.moveTo(0.0f, 0.0f, time, Interpolation.sineIn), Actions.alpha(0, 0.1f))));
    }
}

```

This is where I set up the main game viewport:

```
public static void init(){
    // GameWorld.WIDTH and HEIGHT are 1280 and 1024
    m_camera = new OrthographicCamera();
    m_camera.setToOrtho(true, GameWorld.WIDTH, GameWorld.HEIGHT);
    m_viewport = new FitViewport(GameWorld.WIDTH, GameWorld.HEIGHT, m_camera);
}

```

When creating the UIOverlay I pass the game's m\_viewport into UIOverlay.init(). I have also tried creating a new FitViewport in UIOverlay with the same dimensions as the game's viewport, but have the same behavior.

# Answer
> 4 votes
You need to project from the worldspace to screen space using the correct camera, not the `project` method on the `Vector2`. Then unproject back into the camera of the `Stage` (but in your case that is set to the screen so it should just work).

I think you want something like this;

```
public void addScorePopup (int score, Vector2 worldPos, Camera gameCamera) {
    Vector3 screenCoords = gameGamera.project(new Vector3(worldPos.x, worldPos.y, 0));
    // screenCoordsA is now the position on screen of the collision
    // Now you need to take that into the viewport of the Stage
    Vector3 stageCoord = stage.getCamera().unproject(screenCoords);

    popLabel.setPosition(stageCoord.x, stageCoord.y);

    // etc, etc...
}

```

It might seem weird to unproject but it means you can use any viewport for the Stage, it won't be bound to the dimensions of the screen which is convenient if your doing cross-platform things.

Here is a full, working example of a **Scene2D** `Actor` following a green ball (whose coordinates are updated in *world space*), and another `Actor` animating from the balls starting position to **(0, 0)**;

```
    package com.bornander.androidstudiosandbox;

    import com.badlogic.gdx.ApplicationAdapter;
    import com.badlogic.gdx.Gdx;
    import com.badlogic.gdx.graphics.Color;
    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.graphics.glutils.ShapeRenderer;
    import com.badlogic.gdx.math.Vector2;
    import com.badlogic.gdx.math.Vector3;
    import com.badlogic.gdx.scenes.scene2d.Stage;
    import com.badlogic.gdx.scenes.scene2d.actions.Actions;
    import com.badlogic.gdx.scenes.scene2d.ui.Label;
    import com.badlogic.gdx.scenes.scene2d.ui.Skin;
    import com.badlogic.gdx.utils.viewport.FitViewport;

    public class MyAndroidStudioSandboxGame extends ApplicationAdapter {

        private OrthographicCamera m_camera;
        private FitViewport m_viewport;
        private Stage m_stage;
        private Label m_follow;
        private Label m_goToZero;
        private ShapeRenderer m_shapeRenderer;
        private Vector2 m_worldPosition = new Vector2();

        @Override
        public void create () {
            m_camera = new OrthographicCamera();
            m_camera.setToOrtho(true, 1280, 1024);
            m_camera.position.setZero();
            m_viewport = new FitViewport(1280, 1024, m_camera);

            m_stage = new Stage();
            m_stage.getViewport().update(1280, 1024, true);

            m_camera.update();
            m_shapeRenderer = new ShapeRenderer();

            Skin skin = new Skin(Gdx.files.internal("uiskin.json"));

            m_follow = new Label("Follow", skin.get(Label.LabelStyle.class));
            m_goToZero = new Label("Go to Zero", skin.get(Label.LabelStyle.class));
            m_stage.addActor(m_follow);
            m_stage.addActor(m_goToZero);

            Vector2 p = getStagePositionOfWorldPosition();
            m_goToZero.setPosition(p.x, p.y);
            m_goToZero.addAction(Actions.moveTo(0, 0, 5.0f));
        }

        private Vector2 getStagePositionOfWorldPosition() {
            Vector3 screenPosition = m_camera.project(new Vector3(m_worldPosition.x, m_worldPosition.y, 0));
            Vector3 stagePosition = m_stage.getCamera().unproject(screenPosition);
            return new Vector2(stagePosition.x, stagePosition.y);
        }

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

            m_worldPosition.x += 64.0f * Gdx.graphics.getDeltaTime();

            m_camera.update();

            Vector2 followPosition = getStagePositionOfWorldPosition();
            m_follow.setPosition(followPosition.x, followPosition.y);
            m_stage.act(Gdx.graphics.getDeltaTime());

            m_shapeRenderer.setProjectionMatrix(m_camera.combined);
            m_shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
            m_shapeRenderer.setColor(Color.GREEN);
            m_shapeRenderer.circle(m_worldPosition.x, m_worldPosition.y, 32);
            m_shapeRenderer.end();

            m_stage.draw();
        }
    }

```

---
Tags: libgdx, coordinates, viewport
---


# Question
Title: In UE4, how do I turn my character's body together with the camera?
I made a simple punch animation in Blender and exported it into Unreal Engine 4. In-game, the character appeared from a 3rd-person perspective, but I made it look like first-person by adjusting the camera.

Now, whenever I turn the camera in-game, I can look around at different parts of the character's body. (For example, if I turn right I can see shoulder of my character, and if I am facing the front I can see just the wrists.) Whenever I turn the camera and run the punch animation, it looks weird because the character model isn't aligned with the camera.

How can I make the body turn together with the camera, so my animation looks right?

# Answer
> 1 votes
This has been done before in a video tutorial for a "Horror Game". They label it 'True FPS'. Right now it sounds like the mouse movement is moving the camera and not the body. What you want to do is attach the Camera to a Socket on the Skeleton (if you want the camera to move with the animations as well). If not you can just position the camera where you need it, then attach it to a "None" socket when you attach it to the root component or the Skeletal Mesh. The tutorial mentioned is found here. It should give you what you want based on your question.

*To be clear, your question is to turn the body with the camera. This answers your question because your turning input will move both the body and the camera. On a technical note though, it is not the body that will turn with the camera, it is the camera that is turning with the body due to the attachment hierarchy. I mentioned this in case you want to have a separate input to cause a Local Transform on just the camera - kind of like in Legend of Zelda: Ocarina of Time where you can use a "Look At / Look Around" function*

---
Tags: camera, rotation, unreal, first-person-shooter, unreal-4
---


# Question
Title: Unreal engine 4 - Actor not updating (when instancing on c++)?
My custom actor (containing a few custom UMeshComponent) does not update when I change its location or the visibility of its components.

I instantiate it this way in `StartPlay()` of my GameMode class:

```
  MyCustomActor = GetWorld()->SpawnActor<AMyCustomActor>(AMyCustomActor::StaticClass());

```

Then I set its new location like this:

```
  MyCustomActor->SetActorLocation(FVector(100,0,0));

```

Is it because I did not set the Owner? Or what is wrong?

**Note**

I don't understand why, but my code works now... It might be linked to those warnings:

`LogActor:Warning: GameSession /Game/PersistentLevel.GameSession_19 has natively added scene component(s), but none of them were set as the actor's RootComponent - picking one arbitrarily`

and

`LogActor:Warning: Natively added component (MyCustomActor_143.RootComponent) was left unattached from the actor's root.`

# Answer
> 2 votes
The problem is that in the constructor of your "MyCustomActor" you need to assign a RootComponent that is a SceneComponent. Typically you will see something like a ShapeComponent (SphereComponent, CylinderComponent, etc.).

Then in the constructor, once you have a RootComponent defined in the actor, you need to attach the RootComponent to all other SceneComponents that you add to that Actor.

Constructor Example:

```
AMyActor::AMyActor()
{
    BoxComponent = CreateDefaultSubobject<UBoxComponent>(TEXT("BoxCollider"));
    // ... setup your box component here ...
    RootComponent = BoxComponent;

    StaticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
    // ... setup your static mesh component here ...
    StaticMeshComponent->AttachTo( RootComponent ); // Or you could write StaticMeshComponent->AttachTo( BoxComponent );
}

```

By setting this as the RootComponent, and assuming your Actor is set to Movable, is active, and allowed to update, your call to `SetActorLocation(FVector(100, 0, 0));` will move your actor to that location.

---
Tags: c++, unreal-4
---


# Question
Title: Calculating initial velocities given trajectory parabola
I'm working on a volleyball game but my maths/physics knowledge isn't quite up to par. I need some help with the following problem:

The player can hit the ball from anywhere on the left of the court into one of three points on the right:

```
    P    | x  x  x

```

The ball travels in a parabola defined by the three points, all of which are known:

* The players X coord and height (Xp, Yp)
* The point just above the top of the net (0, Yn) (assume the left of the court is negative along the x axis)
* The point where the ball impacts the ground on the other side of the net (Xi, 0)

I need to calculate the initial X/Y velocities when the player hits the ball so that the ball, affected only by gravity, follows that parabola. EDIT Alternatively, the velocity magnitude and angle from which the X/Y component velocities can be calculated.

I'm able to find the function of the parabola using pen and paper but since this involves "saving" equations with unknown variables I have no idea how to translate that to code (how could you have variable a = 2b for example if b is undefined?). I'm not even sure if finding the function is necessary for this problem.

Any help?

EDIT: I just came to the realisation that if I can calculate the flight time then I can divide the distance traveled each frame along the x axis and just plug that into the parabolic function to get the ball's y coordinate. I guess that's my next avenue of research.

# Answer
> 4 votes
To simplify the math, let's translate everything so the projectile starts at the origin (subtract player position from the other points). Translating the whole problem doesn't modify the velocity, so we don't need to do any compensation at the end.

```
P1 = point above the net - player position (reached when t=t1)
P2 = target point - player position (reached when t=t2)
 v = initial velocity vector
 g = gravitational acceleration vector

```

Then the general form of our parabola is...

```
P(t) = t * v + t*t * g/2

```

We can substitute `t1` & `P1`, `t2` & `P2` to get...

```
P2/t2 - t2 * g/2 = v = P1/t1 - t1 * g/2

```

Since gravity only acts on the vertical axis (in this case), the x component is a bit simpler:

```
P2.x/t2 = P1.x/t1
t1 * P2.x = t2 * P1.x
t1 = t2 * P1.x/P2.x

```

(If by chance anyone wants to apply this formula to a case with *arbitrary* gravity direction, you can first form a local coordinate system with one axis parallel to the gravity direction and one axis perpendicular, solve there, then transform the result back to the original coordinate system)

Now we can substitute this into the above formula for the y axis and solve until we get...

```
t2 = sqrt(2 * (P2.y - P1.y*P2.x/P1.x)/(g.y*(1 - P1.x/P2.x)))

```

(If the inside of the `sqrt` is negative, then there is no ballistic arc joining the three given points with this gravity value. There might still be a solution if the point above the net is moved vertically)

Note that, because both P1.x and P2.x appear in denominators, this will behave badly if the player (and their target) can get right up to the net. You can either force the player & target to keep some minimum distance to the net, or fall back on a different approach for close-to-net shots.

Once you have `t2` in hand, you can solve for `v`:

```
v = P2/t2 - t2 * g/2;

```

Note that this gives a *lower bound* for the time to hit the target. Increasing the time will result in higher arcs with more clearance above the net. (ie. they pass *above* `P1` instead of passing through it)

Here's an animation of this method in action, moving the three points freely:

# Answer
> 0 votes
If I understand your question, your objective is to move your ball like projectile. If so then you can use parametric equation of Projectile, that is,

```
x = (v * t * Cos(theta)) + originX
y = (v * t * Sin(theta) - 0.5 * g * t * t) + originY

```

where v is initial velocity, g is gravity, originX and originY is your ball initial coordinates, theta is initial angle and t is the time.

You can use this equation in your `GameLoop` with everything known.

For example, initially you can set **v**, **theta**, **g**, **originX**, **originY**.

I can demonstrate via pseudo code.

Let say, your ball is at (3,5) then,

```
v = 5
g = -9.81
theta = 35
originX = 3
originY = 5
t = 0

GameLoop{
    ball.x = (v * t * Cos(theta)) + originX
    ball.y = (v * t * Sin(theta) - 0.5 * g * t * t) + originY

    // Nothing to change except "t"
    t++
}

```

By using this equation your ball will move in projectile trajectory. You can further play with it by changing theta, velocity (v).

I hope this helps.

---
Tags: physics, projectile-physics, trajectory
---


# Question
Title: My polygons only register a collision if they are the same shape and directly over top of each other
I'm trying to learn about 2d polygon collision detection/handling and have ran into a snag.

After running through lots of tutorials and sample code I've attempted to implement my own polygon class and separating axis functionality.

I have two polygons of the exact same shape and size that I can move around the screen, but they only register a collision if they are directly (to the pixel) over top of each other.

I suspect the problem to be in my `isSeparatingAxis()` or `flattenPoints()` function, as I'm struggling with some of the math involved in those.

Here's the relevant stripped down code / working example https://jsfiddle.net/gyngbo0d/

# Answer
> 3 votes
On line 161 you return too early from FlattenPoints. Move the return statement outside of the for loop and everything appears to work correctly.

---
Tags: 2d, collision-detection, javascript, separating-axis-theorem
---


# Question
Title: How to give each player in card game the same shuffled deck?
I'm writing a card game in Swift. The idea is to make it work on the Apple Game Center framework. I've noticed an issue which I am not sure how to address.

* I need the current game data to be the same for all players.
* There are 6 players in the game.
* There is a deck of 30 cards, they are shuffled.
* Each player must have the same deck of cards (post-shuffle).
* 6 cards are presented to the "table" one at a time (animation).

There are also other activities that a player does that are outside the bounds of this question.

My question is this;

**How do I give each player the same shuffled deck of cards?**

There are a couple of options I can think of, but perhaps none of these are the best way; hence my question

1. The start player is the `host`. The `host` creates the shuffled deck, and this deck is sent to other players (ie: JSON); in short all activities are facilitated through him.

The problem with this is that the start player could lose internet, abandon the game or all sorts?

So I don't think this is a viable solution

2. There is a middleman, the server.

There is a "lobby" (waiting area) There is multiple games. The game has players. An AI-bot could be used to fill in abandoned players

But wait, does this then mean the server shuffles the cards and sends the same data to all players and makes the players "thin clients"?

Can Apple's Game Center handle this for me?

I'm not sure about the best solution for this?

# Answer
Why shuffle the deck in the first place? All clients know which cards were already played and which cards are still in the deck. What they don't know is the order in which they come. So instead of fixing the order at the beginning of the game, why not determine it during the game?

Keep the deck as a sorted array and whenever a new card is needed, pick a random number and remove that card from the deck.

Generating the random number on the server would be the best way to prevent cheating. There are ways for multiple clients to agree on a random number together without any one client being able to predict or force the result, but they are quite complicated. So if you have the option of doing it server-sided, do it.
> 4 votes

---
Tags: networking, card-game, game-center, peer-to-peer
---


# Question
Title: How do I create an in-app update for a mobile game?
I'm researching how to make an in app update on mobile game.

When there is a hotfix, or an update, I don't want users to have to go to Play store, or App Store to update, but rather for them to update inside the game (like in Clash of Clans). I want to do this because Apple takes too much time for reviewing.

I found https://ionic.io, they use Cordova to embebed HTML inside. We can do live update, rollback to old version with a click. This is pretty suitable for normal app, but for game, the performance is not great.

How can I create an in-app update like this?

# Answer
As Ophir Prusak points out, Apple does not allow downloading code to your app.

So one possibility is that you could make your game logic and behavior entirely data-driven. Then all you do is download new data to the app, and your game changes.

This is not a simple solution, however.
> 3 votes

# Answer
For iOS, you're not allowed to remotely inject native obj-c code, but you can either inject JavaScript, or use any existing code already in the app.

Your best bet is to use method swizzling in order to actually change the behavior of the app:
http://nshipster.com/method-swizzling/

You should also check out Google Tag Manager for mobile which is an awesome tool to directly push new configuration data to apps:
https://www.youtube.com/watch?v=Xe8W5w68BRg

I only know of one solution that provides code level updates for Obj-C apps remotely - https://rollout.io

Check out the video that shows how it works:
http://support.rollout.io/docs/video-fix-a-bug-with-rolloutio

and here is some more info on reddit: https://www.reddit.com/r/iOSProgramming/comments/3rjdfo/experiences\_with\_rolloutio/

(fyi, I work at Rollout)
> -1 votes

---
Tags: android, ios, patching
---


title: Subdivision of a triangle in HLSL

text:
# Question
Title: Subdivision of a triangle in HLSL
How can I subdivide a triangle more than once. I can not use recursion as directx 11 hlsl will not allow it. Are there any links to a HLSL code. This has to be done in the geometry shader as my book says.

my code that will subdivide once is:

```
  void Subdivide(VertexOut inVerts[3], out VertexOut outVerts[6])
{
    //          1
    //          *
    //         / \
    //        /   \
    //     m0*-----*m1
    //      / \   / \
    //     /   \ /   \
    //    *-----*-----*
    //   0     m2     2

    VertexOut m[3];

inVerts[0].PosL = normalize(inVerts[0].PosL);
inVerts[1].PosL = normalize(inVerts[1].PosL);
inVerts[2].PosL = normalize(inVerts[2].PosL);
// compute edge midpoints
m[0].PosL = 0.5f * (inVerts[0].PosL + inVerts[1].PosL);
m[1].PosL = 0.5f * (inVerts[1].PosL + inVerts[2].PosL);
m[2].PosL = 0.5f * (inVerts[2].PosL + inVerts[0].PosL);
m[0].PosL = normalize(m[0].PosL);
m[1].PosL = normalize(m[1].PosL);
m[2].PosL = normalize(m[2].PosL);

    // derive normals
    m[0].NormalL = m[0].PosL;
    m[1].NormalL = m[1].PosL;
    m[2].NormalL = m[2].PosL;

    // interpolate texture coordinates
    m[0].Tex = 0.5f * (inVerts[0].Tex + inVerts[1].Tex);
    m[1].Tex = 0.5f * (inVerts[1].Tex + inVerts[2].Tex);
    m[2].Tex = 0.5f * (inVerts[2].Tex + inVerts[0].Tex);

    outVerts[0] = inVerts[0];
    outVerts[1] = m[0];
    outVerts[2] = m[2];
    outVerts[3] = m[1];
    outVerts[4] = inVerts[2];
    outVerts[5] = inVerts[1];
}

void OutputSubdivision(VertexOut v[6], inout TriangleStream<GeoOut> stream)
{
    GeoOut gout[6];

    [unroll]
    for(int i = 0; i < 6; ++i)
    {
        // Transform to World Space
        gout[i].PosW = mul(float4(v[i].PosL, 1.0f), gWorld).xyz;
        gout[i].NormalW = mul(v[i].NormalL, (float3x3)gWorldInvTranspose);

        // Transform to homogeneous clip space
        gout[i].PosH = mul(float4(v[i].PosL, 1.0f), gWorldViewProj);

        gout[i].Tex = v[i].Tex;
    }

    //          1
    //          *
    //         / \
    //        /   \
    //     m0*-----*m1
    //      / \   / \
    //     /   \ /   \
    //    *-----*-----*
    //   0     m2     2

    // We can draw the subdivision in two strips:
    // strip 1: bottom three triangles
    // strip 2: top triangle

    [unroll]
    for(int j = 0; j < 5; ++j)
    {
        stream.Append(gout[j]);
    }
    stream.RestartStrip();

    stream.Append(gout[1]);
    stream.Append(gout[5]);
    stream.Append(gout[3]);

    }

[maxvertexcount(8)]
void GS(triangle VertexOut gin[3], inout TriangleStream<GeoOut> stream)
{
    VertexOut v[6];

    Subdivide(gin, v);

    OutputSubdivision(v, stream);
}

```

How can I subdivide twice or even three or four times. thx

# Answer
Although you can use the geometry shader to sub-divide primitives, I would suggest looking into tessellation. It is a new feature that has been added in DirectX 11, which allows you to sub-divide low level primitives into high-detailed primitives. This feature is highly optimized to do the exact thing you are describing. See the image below for an example.

Without going into too much detail, the tessellation pipeline consists of three new stages: hull shader, fixed-function tessellator and domain shader. Simply put, the hull shader defines the positions of new points inside original primitive, which are passed to the fixed-function tessellator stage. The domain shader runs on the output of the tessellator. You can think of the domain shader as a replacement of the vertex shader of sorts, as stuff that you would normally put in the vertex shader are now placed in the domain shader.

To get any more information I would suggest to look for documentation and tutorials (like this one, for example)
> 2 votes

# Answer
I found this post on gamedev.net.

Try to use their code, and correct the Vertex Positions.

Try creating a method that implements a barycentric function, and use the generated coords to create 3 triangle. For example, you should generate this:

Use the coordinates of the line segments that form 3 equal triangles

I have a bit of code to generate a barrycentric function, but it is written in Java, so you may have to translate/port it:

```
public static float barryCentric(Vector3f p1,Vector3f p2, Vector3f p3, Vector2f pos){
    float det = (p2.z - p3.z) * (p1.x - p3.x) + (p3.x - p2.x) * (p1.z - p3.z);
    float eleven = ((p2.z - p3.z) * (pos.x - p3.x) + (p3.x - p2.x) * (pos.y - p3.z)) /det;
    float tweleve = ((p3.z - p1.z) * (pos.x - p3.x) + (p1.x - p3.x) * (pos.y - p3.z)) /det;
    float thirteen = 1.0f - eleven - tweleve;
    return eleven * p1.y + tweleve * p2.y + thirteen * p3.y;
}

```
> 0 votes

---
Tags: directx, hlsl
---


# Question
Title: How can I combine sprites and attach them to a GameObject?
I have the following sprites:

Background

Foreground

Combined they should look like this:

The first problem is Unity can only show one sprite with its Sprite Renderer, so I can't combine them with it.

The second problem is the bomb sprite should not be rotating along with the background, like so:

How can I do this?

# Answer
You can simply have them as different objects and make one of them as main object with the others as children of it. So you can code a behavior for each of them.
> 1 votes

---
Tags: unity, sprites
---


title: How to set Text in C# code?

text:
# Question
Title: How to set Text in C# code?
I'm trying to make a series of text appear programmatically. It's not quite showing up, and I'm struggling to understand exactly why. Any ideas?

```
GameObject row = new GameObject("Row");
row.transform.parent = panel.transform;
HorizontalLayoutGroup rowLayoutGroup = row.AddComponent<HorizontalLayoutGroup>();
rowLayoutGroup.childForceExpandHeight = false;

GameObject name = new GameObject("Name");
name.transform.parent = row.transform;
GameObject value = new GameObject("Value");
value.transform.parent = row.transform;

Text nameText = name.AddComponent<Text>();
nameText.text = tup.First;
nameText.alignment = TextAnchor.MiddleRight;

```

Note that this script is run from a Panel, contained within a Canvas.

# Answer
It seems the problem is that I don't have a font specified, as determined by playing with the inspector text that came out. To do that, I simply needed to add the following text to my listed code.

```
nameText.font= Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;

```
> 2 votes

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


title: Is async image loading possible?

text:
# Question
Title: Is async image loading possible?
Can anyone tell me if there is a async version of LoadImage() method? I found about Resources.LoadAsync, however the method doesnt work.

Thank you

# Answer
You're on the right track in the comments above when you ask whether the WWW class could help. This is how I've solved the problem in the past for asynchronously loading local image files as Texture2D data:

```
Texture2D _content;
Material _material;

// Call this with StartCoroutine(LoadTexture(path));
IEnumerator LoadTexture(string path)
{
    // Start the asynchronous load.
    var www = new WWW("file://" + path);

    // Let the game continue running until the texture has been loaded.
    yield return www;

    // Replace current content with loaded texture.
    if (_content != null)
        Destroy(_content);
    _content = www.texture;

    // Instantiate a copy of the material,
    // and hang onto it so we can clean up when finished with it
    if (_material == null)
        _material = GetComponent<Renderer>().material;

    _material.mainTexture = www.texture;
}

void OnDestroy()
{
    // Clean up created instances
    // (these aren't immediately garbage-collected otherwise)
    if(_material != null)
         Destroy(_material);
    if(_content != null)
         Destroy(_content);
}

```

I don't know how much load-balancing Unity does on its own, but it might be good to avoid kicking off all 6GB of load requests at once. ;) Try pacing them out, so you only have a few requests running at a time, to avoid any major hitches.
> 0 votes

# Answer
You can fire off a C# thread to load the image from a file, and get as far as turning it into a color array, with which you can quickly set a texture. So assuming you have some class `AsyncImage` with a function `loadMyImage()` which sets a `Color[] pixels` member variable, you could do something like:

```
 Thread t = new Thread(new ThreadStart(asyncImage.LoadMyImage));
 t.Start();

```

Now in the update method of your script, or some coroutine that runs every few milliseconds:

```
if (asyncImage.pixels != null) {
  myTexture2d.SetPixels(asyncImage.pixels);
}

```

You have probably heard that Unity can't do threading, but it is only the case that most Unity objects will not function outside of the main thread. You can still fire off as many threads as you want and do whatever things you want in them, as long as you don't use those forbidden unity methods/objects. This may mean you have to roll your own image loading code, or find some open source code. It is possible the standard mono libraries will have what you need. You can see a similar example in my source where I am generating an image procedurally in the background here: https://github.com/jackmott/solescape/blob/master/Assets/src/MainMenu/MainMenuManager.cs
> 0 votes

---
Tags: unity, image, loading
---


title: m_Entries is undefined

text:
# Question
Title: m_Entries is undefined
I am following this tutorial and this guy puts in his code m\_Entries and doesn't explain it at all at least I think. So any one who has done skeletal animation show me what he is talking about by m\_Entries.

# Answer
> 4 votes
Note that this is the 38th tutorial in a series. If you go back to part 22, you can see m\_Entries is defined as follows:

> The m\_Entries member of the Mesh class is a vector of the MeshEntry struct where each structure corresponds to one mesh structure in the aiScene object. That structure contains the vertex buffer, index buffer and the index of the material.

This is the type of answer you could easily have found by yourself by at least skimming earlier parts of the tutorial, or, worst case, downloading the full source from the link above and looking in `mesh.cpp` and `mesh.h` to see how it's used.

---
Tags: opengl, animation, skeletal-animation, assimp
---


title: For loop won't run in Unity

text:
# Question
Title: For loop won't run in Unity
I have a basic knowledge of coding in C++ but have been following a tutorial and am having trouble following it. I have tried using Debug.Log to find out my problem and it seems my for loop is not running but the function is being called successfully. Can someone help?

```
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class AddButtons : MonoBehaviour {

public Transform puzzleField;
public GameObject btn;

void Awake()
{
    Debug.Log("Awake Function Started");
    for(int i=0; i>8; i++)
    {
        Debug.Log("loop started");
        GameObject button = Instantiate(btn);
        button.name = "" + i;
        button.transform.SetParent(puzzleField, false);
    }
}
}

```

The debug log shows "Awake Function Started" correctly as expected but "loop started" doesnt show in the log. Can anyone tell me what I am doing wrong? Thanks

# Answer
In your for loop, your condition is `i>8`, which won't be true for the first iteration, so the loop is skipped. You probably meant `i<8`.
> 11 votes

# Answer
Actually for-loop contains of **for(initialization;condition;increment/decrement)**

* Initialization: Any variable should be initialized here on which whole for loop will depends. It runs only once.
* Condition: It is the condition on which for loop executes if gets true, per loop. It runs every time after every loop and executes the loop until it gets false.
* Increment/Decrement: In loop variable. Although you can do anything in it.

In your case you put i=0 and condition i\>8 which is not true, that's why your loop is not executing.
> 4 votes

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


# Question
Title: Different ways to mark the status of an enemy
I have a 3D game with a "eagle view", I have enemies and I have magics that will affect the status of the enemies.

I want to show the status of the enemies( frozen, on fire(dot damage), slowed...etc)

I think about two possibilities

* Put a 2D image in the enemy that show status
* Change the color of the enemy with vertex shaders

Is there other,or correct way? In case of use vertex shader, how I change the color of enemy without losing all details(Something like a filter)? shaders

# Answer
> 1 votes
**Is there other, or correct way?**

Sure, there's tons of ways to "show the status of the enemy" and maybe not even with color. This is a very subjective question but it comes down to what you think looks best and what works with the rest of your game.

**In case of use vertex shader, how I change the color of enemy without losing all details (Something like a filter)?**

This is a much more concrete question. If you want to apply colors without losing any of the details, you're probably going to look at some sort of tinting of the character.

What you can do is have a custom uniform value in your *fragment shader* (not the vertex shader!) that will render all the pixels of that object with a tinting. The easiest way to do this is just with multiplicative blending. Multiplicative blending is simple in that a 1.0 in a given channel will let original color pass through while a 0.0 will produce no color in that channel. A value in the middle gives a partial pass through (darker color).

```
uniform vec4 tintColor;

void frag(out vec4 fragColor)
{
    vec4 originalColor; //Comes from original object color
    return originalColor * tintColor;
}

```

Multiplicative blending is not the only one and you should consider other types of blending (or even more complex forms of tinting) by doing research until you find something that fits with your design.

---
Tags: shaders
---


title: How to resize animation in libgdx?

text:
# Question
Title: How to resize animation in libgdx?
I want to draw an animation, the size of each frame is 500x500px but when I try to resize, the animation seems to rotate...

Here the code to load frames and create animation:

```
    Texture fireSheet = new Texture(Gdx.files.internal("fire_sheet.png"));

    TextureRegion[] fireFrames = new TextureRegion[4];

    fireFrames[0] = new TextureRegion(fireSheet,0,0,500,500);
    fireFrames[1] = new TextureRegion(fireSheet,700,0,1200,500);
    fireFrames[2] = new TextureRegion(fireSheet,1450,0,1950,500);
    fireFrames[3] = new TextureRegion(fireSheet,2250,0,2750,500);

    fireAnimation = new Animation(0.5f, fireFrames);

```

In draw method I resize the animation in this way:

```
    public void draw(Batch batch, float parentAlpha) {

        batch.enableBlending();
        stateTime += Gdx.graphics.getDeltaTime();

        currentFrame = Assets.fireAnimation.getKeyFrame(stateTime, true);

        batch.draw(currentFrame, getX(), getY(), 200, 200 );

    }

```

So if I use:

```
batch.draw(currentFrame, getX(), getY() ); // WORKS!!! But too Big for me 500x500px

```

Instead if I use:

```
batch.draw(currentFrame, getX(), getY(), 200, 200 ); // Animation doesn't work properly

```

What Can I do?

Thank you in advance

# Answer
I made a custom Class for you:

```
public class MyAnimation extends Animation {

    float scaleX;
    float scaleY;

    public MyAnimation(){
        scaleX=1;
        scaleY=1;
    }

    public void setScaling(float scale){
        scaleX = scale;
        scaleY = scale;
    }

    public void draw (float stateTime, Batch batch, float x, float y) {
        TextureRegion region = getKeyFrame(stateTime);
        batch.draw(region, x, y, region.width*scaleX, region.height*scaleY);
    }
}

```

You can use it as it is or customize it as you wish.
> -1 votes

---
Tags: libgdx, animation, frame-rate
---


# Question
Title: Effect of vertex winding on normals and shading
I have implemented a Phong and Gourand shader for a triangle mesh that is being imported from an STL file. It appears to be working fairly allright but some triangles seem to be what I can only describe as upside down due to lack of better wording. This effect is visible in both shading models albeit a bit smoother in Phong. Here is an example:

On something basic like a cube the rendering is perfect. I am no expert but from what I have read, I am lead to suspect that perhaps the winding of the vertices in the mesh might be causing normals that are somewhat incorrect. Could this be possible and if so, how does one correct for that?

The effect of interpolating the normals by either division or by area weight does not really make too much of a difference. I can also confirm that the normals that I am calculating are basically the same as those that come with the STL as calculated by FreeCAD. The manually calculated normals are slightly better though because they are area weighed. They are calculated as follows:

```
glm::vec3 e1 = vecs[1] - vecs[0];
glm::vec3 e2 = vecs[2] - vecs[0];
faceNorms[i] = glm::cross(e1, e2);

```

with "vecs" being the 3 points of my vertices. I then sum up all these area-weighed normals for each face that uses a normal and finally normalize that.

PS. FreeCAD renders the mesh in a "flat" fashion and I guess thereby avoids this issue but unfortunately rendering "flat" with GLES 2.0 is a bit of a performance waste from what I have read.

# Answer
Ok so the problem was not winding. It seems that MickLH is right in that one cannot simply combine all the shared points in a mesh into one vertex. Only vertices used in triangles with similar normals can be combined otherwise one gets this strange effect.
> 0 votes

---
Tags: opengl, shaders, opengl-es2, 3d-meshes, normals
---


# Question
Title: Background with small, randomly moved elements in LibGDX
I'm looking to implement a 'dynamic' background (meaning, with objects moving randomly) in my libgdx game, something **similar to what you can see in this video** (from the Google Play game 'Finger Dodge'):

https://www.youtube.com/watch?v=Zf8mpqf0jGc

In the above example, the background has a **bunch of moving squares and triangles (and some blinks) that move randomly, independently from each other**. So, what exactly should be the best approach to get something like that? I'm guessing that those background elements aren't just a bunch of single, independent textures that all get rendered at the same time with a random direction, because that would seem a bit TOO much stuff to render... Or am i wrong and that's what it might be?

**So, is there any way to consistently and efficiently achieve this effect in libgdx (or if not, any other way)?**

Thanks in advance!

# Answer
What you are seeing in the video is just an animated background image , You can try to create your owen using sprite sheet animation techniques ( see here ) take a look here also :
> 1 votes

---
Tags: java, libgdx
---


title: Cossacks game pathfinding

text:
# Question
Title: Cossacks game pathfinding
Cossacks (released in 2002) is an RTS game where you can build huge (few thousands men per player) armies on a really big maps. Imagine Age of Empires 2 for few players on Ludikris map with no lag, with 8000 units on the map (or even bigger map with even more units!). What is interesting is the fact, that if you send this huge army to the other corner of the map ... the game does not stall. Units just start moving towards their target position. There are obstacles on the way, like hills, buildings, walls etc, which are avoided by units.

There is, however, a problem with pathfinding - sometimes units just go back and forth around hills, so that might indicate, that whole path length is divided into smaller parts and units' gets confused. But still, that's massive amount of computation to be done for a few-thousand-men army, really impressive.

Do you have any idea how such smooth (in terms of performance) pathfinding was/could be achieved?

# Answer
> 8 votes
I don't know which technique was specifically used in Cossacks, but I guess you are also interested in the problem at hand in general terms. In fact, nowadays, there are ways trough which such result can be achieved - although of course advanced techniques are needed in demanding scenarios.

Overall, two are the main bottlenecks when implementing path-finding in that type of map you describe: number of agents and size of the space to be searched (path-finding = search for a viable or the shortest path).

1. The number one approach in such situation is trying to decrease the size of the problem, i.e. search less and search in lower areas.

1a) On the one hand, to search in lower areas means reducing the possible paths that have to be evaluated in a path-finding step. For that, spatial partitioning is often used. The scene is divided in areas so that the path-finding can be performed in smaller search-spaces at a time. Also, there are search algorithms such as the HPA\* and the HAA\* that implement inherently a hierarchical path-finding, by partitioning the scene.

1b) On the other hand, searching less means assuring that only some agents search paths at a time. An useful trick here is to create the impression of a higher number of agents path-finding than the real one. For instance, in some games there are squads of a given number of soldiers, where the path-finding is actually done per squad, not per soldier. If you think of a squad composed by 10 soldiers, that alone reduces the path-finding by an order of magnitude. Then, once the path of the squad is found, what is needed is that each soldier is able to avoid obstacles in the ways - which means collision avoidance per soldier.
2. I mentioned collision avoidance above. Notice that quite likely, most of the frequent CPU work of the many units in the situation you describe would not be due path-finding in itself, but rather due to avoiding obstacles during the path-following stage. But hills, buildings and so on are never very numerous. The real problem arises when agents have to avoid each other.

Indeed, that can hurt performance when thousands of agents are avoiding the collision against each other at the same time. However, tricks can be also used here. First, agents only have to avoid the agents and buildings that are close to then. Second, in some games (particularly isometric games), there can be quite a tolerance with how much agents can in fact collide (or even overlap) with each other, since the camera angle disguises it. In some older games, units simply could "walk over each other" - meaning that one agent does not fully block the path of the others.

Also, modern applications can handle fairly impressive number of actors avoiding collision at the same time. E.g.: https://www.youtube.com/watch?v=Hc6kng5A8lQ or download and see an ORCA algorithm example with 25000 agents in a really huge crowd: http://gamma.cs.unc.edu/ORCA/videos/ORCA-3.wmv
3. In games with huge number of units fighting, a lot of units die. And die fast. Often before the mass of units even have to avoid too much obstacles.
4. Modernly, a technique called Flow Field Path-finding has been introduced in Supreme Commander 2 (2010), that actually allowed for the first time the RTS control of massive number of individually behaved agents: How does Flow Field pathfinding work?

---
Tags: performance, path-finding
---


# Question
Title: How to place a sprite in the center of the world in Phaser
I am very new to Phaser. Here is what I did:

```
  <!DOCTYPE html>
  <html>
    <body>
    <script src="phaser.js"></script>
    <script>
        var game = new Phaser.Game(500, 500, Phaser.AUTO, '', {
            preload : preload,
            create : create,
            update : update
        });

        function preload() {
            game.load.image('dog', 'assets/dog.png');
        }

        function create() {
            game.stage.backgroundColor = "#1BDCFF";
            game.physics.startSystem(Phaser.Physics.ARCADE);
            game.physics.startSystem(Phaser.Physics.ARCADE);
            dog = game.add.sprite(game.world.centerX, game.world.centerY, 'dog');
            game.physics.arcade.enable(dog);
        }

        function update() {

        }

    </script>
</body>

```

Shouldn't the dog appear in the center of the "world"? Here is how it looks like :

I then tried something like this :

```
var dogImage = game.cache.getImage('dog');
dog = game.add.sprite(game.world.centerX-dogImage.width/2, game.world.centerY-  dogImage.height/2, 'dog');

```

And now that I edited in this way the create function it does place the dog in the center. Is this the way of doing it or there's a more elegant way ?

# Answer
Valkea has the right idea, but I recommend you modify the `anchor` of your Sprite to what you intend - in this case, the center of the sprite. If you were using P2 or Ninja physics, this is done automatically for you, but with Arcade physics, this defaults to the top-left corner. Simply call `<your sprite>.anchor.setTo(0.5);` to set both the x and y anchors to the middle.

Doing this will save you from having to account for the top left corner everywhere. The anchor point is used when transforming (flips, rotations, scales), measuring distances, when specifying a different collision box size than your sprite, and many more.

Have a look at the Phaser anchor example for a visual representation of the anchor and how it affects sprite positioning.

**Update:** the `anchor` property now belongs to `Sprite`.
> 10 votes

# Answer
The **top left corner** of your dog asset is most probably placed at the center of your game area.

In order to solve your problem, you should move the dog asset by half its height and width so it is centered on the given coordinates.

Maybe something like this :

```
var TmpImg = game.cache.getImage('dog');
game.add.sprite(game.world.centerX - TmpImg.width/2.0,game.world.centerY - TmpImg.height/2.0,'dog');

```

(I don't know Phaser, so I might be wrong)
> 4 votes

# Answer
You could try to set the anchor of the dog to 0.5, like this:

```
dog.anchor.setTo(0.5);

```
> 1 votes

---
Tags: phaser
---


# Question
Title: How to design a leaderboard where lower is better?
In a classic high score leaderboard, the player with the highest score is leading, followed by people with slightly lower scores. In short, higher is better.

But in a game I am working on, the player has to reach the objective by completing various puzzles. The fewer puzzles he needs to solve before reaching his objective, the better. This is somewhat similar to fewest moves possible.

So basically, the leaderboard would be reversed, the player with the lowest ~~score~~ puzzles needed would lead the board, followed by players who needed slightly more puzzles to reach the goal.

**How would I design/build the leaderboard so players understand the principle of lower is better?**

Edit: One more important detail: The leaderboard will not be global, but local for one user, so he can track his own progress/improvement. So the design should be clear even if there are no entries yet.

# Answer
1. Order the entries top down, this is how all arcade games did it, so it's a de facto standard.
2. Use multiple columns, first rank (1st, 2nd, 3rd, etc), then name, then any score related columns.
3. If you want to, you can decouple number of puzzles from the actual score by calculating a score based on number of puzzles and time required to solve them, then list both the number of puzzles and the scores on the leaderboard.

> "So the design should be clear even if there are no entries yet."

Local single player leaderboards/highscores often include dummy leaderboard entries. This also gives the player an incentive to play long enough to get first place, or even to play often enough so all the dummies get removed from the leaderboard.
> 15 votes

# Answer
**Players expect higher scores to be better.** You might be able to teach them otherwise, but it's easier to go with the flow.

Hence I suggest inverting your scoring system instead: think of your "lower-is-better" score as a fraction (e.g. 3 = 3/1) and invert it (e.g. 3/1 → 1/3). If you want integer scores, multiply or round the result as you like.

For example, assuming you went with `inverted_score = floor(1/(score + 1) * 100)`:

3 becomes `floor(1/(3+1) * 100)` = 25
2 becomes `floor(1/(2+1) * 100)` = 33
0 becomes `floor(1/(0+1) * 100)` = 100

Then just have a traditional "higher-is-better" highscore table.

---

Inverting fractions has the advantage that your worst possible score can be arbitrarily large, but has the problem that the scoring is no longer linear:

If you *do know* what the worst possible score is, it's simpler to just subtract scores from that, which preserves the linearity.
> 3 votes

# Answer
I think that you shoud name the Leaderboard something like "Number of puzzles needed", and if you want to show/track his own progress you can include average "puzzles needed"

Something like

```
**Number of puzzles needed**

Name                  Puzzles

-----------------------------

1- Player 1            6
2- Player 2            8

-----------------------------
Average                7

```
> 2 votes

# Answer
Designing

Wherever you have the leaderboard simply have it say **lowest scores** at the top or even just say best scores with the lowest at the top. People can figure out that lowest is the best from there.

Please specify what language you are using so I can give you exact code/ syntax. But in most languages just set a variable that is a score and run it against the highscore which is a different variable.

Say something on the lines of

```
if(score <= highscore) {
     //make new score top
     document.getElementByID("Position 1").textContent = score;
     //make the old highscore equal to a new variable for second on the leaderboard
     score2 = highscore
     //make the new highscore variable equal to the new score
     highscore = score
     //put highscore in the second position
     document.getElementByID("Position 2").textContent = score 2;
}

```

and keep doing the process of moving down. Also remeber to make the same for the second, third positions and so on.

I am sure there is an easier way to do it but that was an easy way to make a small leaderboard in a javascript and html game.

Please specify a langauge if you want something better.
> 1 votes

---
Tags: leaderboards, ranking
---


# Question
Title: LibBDX create a tail when the object is moved
I am looking for a way to implement in my game a kind of shadow/tail which will be displayed after the object is moved. Should I use animation? If yes how? Here an example:

# Answer
I used ParticleEditor to create this:

This is the code:

```
package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.ParticleEffect;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class Particles extends ApplicationAdapter {
   SpriteBatch batch;
   ParticleEffect pe;

   @Override
   public void create () {
      batch = new SpriteBatch();

      pe = new ParticleEffect();
      pe.load(Gdx.files.internal("Particles.party"),Gdx.files.internal(""));
      pe.getEmitters().first().setPosition(Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);
      pe.start();
   }

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

      pe.update(Gdx.graphics.getDeltaTime());
      batch.begin();
      pe.draw(batch);
      batch.end();
      if (pe.isComplete())
         pe.reset();
   }
}

```

This is a basic fire that can be used (for example) in any car, simulating turbo. You can edit create something more specific with the ParticleEditor.
> 1 votes

---
Tags: libgdx, animation, shadows, motion
---


# Question
Title: Interpolation over a network - receiving and drawing an opponent in 1v1 game
I'm a newbie Java coder and I'm creating a 1v1 game with an authoritative server and two clients.

My whole network is based on UDP packets:

* sending positions from clients
* sending confirmations them from the server (and deleting old ones on client)
* sending 'non cheated' positions to the opponent from the server

Everything was okay, until the last issue appeared.

When I send positions from the server to the opponent, they are being received in different timings. An example:

* Position 1 comes in 43 ms
* Position 2 comes in 15 ms (from the previous one)
* Position 3 comes in 34 ms
* Position 4 comes in 10 ms
* Position 5 comes in 35 ms

As we all know - THIS IS NETWORKING, it is impossible to make it 'stable' that every packet comes within a constant: 30 ms time (omg that would be perfect).

And here comes my problem, I don't know how to adjust the interpolation that the 'opponent' is drawn as smooth as a normal player (me on my phone).

When the process is static (I click arrows and move my player 'step by step') it is really, really smooth. My gameloop has some timings and it works really well. But when I receive my opponent's position and set his 'desiredPosition(x,y)' his movement is not smooth, his 'positions' are not 'updating' in a constant time but with random delays (cause we get these positions in different timings).

And example of my issue:

**The gameloop:**

```
@Override
    public void run(){

        long beginTime;     // the time when the cycle begun
        long timeDiff;      // the time it took for the cycle to execute
        int sleepTime;      // ms to sleep (<0 if we're behind)
        int framesSkipped;  // number of frames being skipped

        while(match_running){
            beginTime = System.currentTimeMillis();
            framesSkipped = 0;  // resetting the frames skipped
            // update game state

            // MOST IMPORTANT METHODS - look below
            player_me.updatePosition(); // move me (smoothly) to desired position
            player_op.updatePosition(); // move the opponent (smoothly)

            // render state to the screen
            // draws the canvas on the panel
            repaint();

            // calculate how long did the cycle take
            timeDiff = System.currentTimeMillis() - beginTime;
            // calculate sleep time
            sleepTime = (int)(FRAME_PERIOD - timeDiff);

            if (sleepTime > 0) {
                // if sleepTime > 0 we're OK
                try {
                    // send the thread to sleep for a short period
                    // very useful for battery saving
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {}
            }

            while (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS) {
                // we need to catch up
                // update without rendering
                player_me.updatePosition(); // move me to desired position
                player_op.updatePosition(); // move the opponent

                // add frame period to check if in next frame
                sleepTime += FRAME_PERIOD;
                framesSkipped++;
            }

            // sending positions every 30 seconds
            time_now = System.currentTimeMillis();
            if(time_now >= (packet_past_time + 30)) {
                sendPositions();
                packet_past_time = System.currentTimeMillis();
            }
        }
    }

```

**Listening for 'opponent's positions':**

```
public void received(Object o){
    if(object instanceof OpponentPositionList)
        player_op.setDesiredPosition(object.x, object.y);
}

```

So we set his new 'desired position'. **The Gameloop is always calling his 'updatePosition()'** which should move him to the 'desired position'. And it works totally smoothly with 'Player Me' cause it updates positions constantly, but it freezes when receiving positions 'not constantly' from the opponent:

```
public void updatePosition(){
     double xDistance = desiredX - this.x;
     double yDistance = desiredY - this.y;

     double distance = Math.sqrt(xDistance * xDistance + yDistance * yDistance);

       if (distance > 1) {
           this.x += xDistance * 0.5;
           this.y += yDistance * 0.5;
       }else{
          this.x = Math.round(this.desiredX);
          this.y = Math.round(this.desiredY);
       }
}

```

The main question is:

If positions come not 'constantly', with random 10-50 ms delays how to draw the opponent as smooth as a normal player on this device? With some sort of 'timed interpolation' or something? Any suggestions would be awesome. Thanks!

# Answer
Your question boils down to an answer that results in client prediction for replicated movement of remote entities in your game. There are several theories and implementations that you can go with for this. Linear interpolation is a popular one for having the client predict where the server is going to tell it where various objects are. Here is a nice list with some sources about this topic.

**Movement Queues**

Here is a good example/discussion that talks about different approaches and their success / failures. It is valid because it is not specific to any language and can be applied to any game engine. It has an approach where you save (client side) the client side movements. Then, as a packet, you send them to the server. The server sends this client movement packet to all interested parties (other clients). This is neat because if you have a huge delay, rather than teleporting the character, you simply replay those saved packets that the client received of the remote entity.

**Curves**

Then there is the approach that was seen in Planetary Annihilation with the use of Curves. (P.S. The link has a lot of links in the article discussion this very topic). What that is essentially the client tells the server where it was at a given time. From there, the server tells all clients where that entity is at a given time using a list of times and positions. From there the client can smooth the movement using the time and position pairs. What is really great, and they mention this too, is that you get free game replay data for free.

**Tick Rate Entity Interpolation**

A third method is one found in the Source engine Multiplayer Networking guide. This example is pretty straight forward. It involves some interpolation math and using tick rates. May be the simplest to implement.
> 1 votes

# Answer
**Linear Interpolation**

Want to ensure that at time T, player B will appear at location L for player A?

Make player A speed up the movement of player B so that they get there in time.

E.g. The movement should last 5 seconds in total. The packet takes 1 second, so player A renders player B as moving at 1.25x of his usual speed.

**No Interpolation**

Packets typically take well under 250ms to reach their destinations, so you could just preserve player B's rendered speed and have player A see the action completed 250ms later.

They will not notice this unless your game is extremely quickly paced and the network is especially laggy at that time.
> 0 votes

---
Tags: java, networking, multiplayer, interpolation, multiple-render-targets
---


title: Cannot turn script back on

text:
# Question
Title: Cannot turn script back on
I've got an issue. When `(Input.GetMouseButtonUp (0)`, `Speedy` script is disabled, thus we cannot enable it again from inside the script like shown below. How can we go around this?

```
public class  Speedy : MonoBehaviour {

GameObject car;

 if (speed == good)
    {
        GameObject car = GameObject.FindWithTag ("Car");

        if (Input.GetMouseButtonUp (0))
        {
            car.GetComponent<Speedy>().enabled = false;
        }

        else car.GetComponent<Speedy>().enabled = true;
    }
}

```

# Answer
> 1 votes
For this, you can use `FindObjectOfType` either.

`FindObjectOfType` gives you reference on relevant script once then you can play with it.

If I edit your code, then it should be something like this

```
public class  Controller : MonoBehaviour {

    Speedy car;

    Start()
    {
        car = FindObjectOfType<Speedy>();
    }

     if (speed == good)
        {

            if (Input.GetMouseButtonUp (0))
            {
                car.enabled = false;
            }

            else car.enabled = true;
        }

}

```

Drop this script to another `GameObject` in hierarchy.

**NOTE:** In your question you are disabling script from `car` but enabling if from `cube`. I don't know that you did it intentionally.

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


# Question
Title: Ball Speed is not increasing as per code
I am working on small project , but now I have a problem . The problem is The Player speed (Ball speed) is not increasing as per the code .

In the beginning ball speed increases , but as the time goes the speed becomes constant .

I made Gravity as -50 in Y - Axis .

So here is the C# Script attached to the ball :-

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Ball_Script : MonoBehaviour
{

// Ball Physics Variables
private Rigidbody Ball_Rigid;
public float Ball_Speed = 10f;
private float Speed_Change_Time = 1.0f ;

// UI Text
public Text My_Ball_Speed_Text ;
public Text My_Key ;

// Use this for initialization
void Start ()
{
    Ball_Rigid = GetComponent<Rigidbody>();
    My_Ball_Speed_Text.text = Ball_Speed.ToString () + " km/h";
    My_Key.text = "No Key Pressed";
}

// Update is called once per frame
void Update ()
{
    // Restart game
    if(transform.position.y < -7.0f)
    {
        Application.LoadLevel(0);
    }

    // Ball Automatic Movement script Starts here
    Speed_Change_Time_Interval ();
    Ball_Rigid.AddForce (new Vector3 (Ball_Speed * -1 * Time.deltaTime, 0, 0));
    // Ball Automatic Movement script Ends here

    if(Input.GetKeyDown(KeyCode.LeftArrow))
    {
        Ball_Rigid.MovePosition(new Vector3(transform.position.x , transform.position.y , transform.position.z - 1.0f));
        My_Key.text = "Left Arrow Pressed";
    }

    if(Input.GetKeyDown(KeyCode.RightArrow))
    {
        Ball_Rigid.MovePosition(new Vector3(transform.position.x , transform.position.y , transform.position.z + 1.0f));
        My_Key.text = "Right Arrow Pressed";
    }
}

// This Fixed update stops the ball from bouncing
void FixedUpdate()
{

    Vector3 currentVelocity = Ball_Rigid.velocity;

    if (currentVelocity.y <= 0f)
        return;

    currentVelocity.y = 0f;

    Ball_Rigid.velocity = currentVelocity;
}

// This function increases the ball speed in every 1 second
void Speed_Change_Time_Interval ()
{
    Speed_Change_Time = Speed_Change_Time - Time.deltaTime;

    if(Speed_Change_Time <= 0)
    {
        Ball_Speed = Ball_Speed + 10;
        Speed_Change_Time = 1.0f;
        print(Ball_Speed);
        My_Ball_Speed_Text.text = Ball_Speed.ToString ()+ " km/h";
    }
}
}

```

Here `FixedUpdate ()` stops the ball from bouncing and `Speed_Change_Time_Interval ()` function increases the ball speed in every second . But it works some extent . Then there is no change in speed of the ball . Here is the video of the game ( Recorded with Jing , so file is in .swf format . Sorry for that :( ) Link :- http://www.mediafire.com/download/ibk4ffjm3y6i96y/Ball\_Vid.swf

File size = 9.28 MB

So what is the problem of this script . If my method is wrong / not good please suggest me a good one :).

Hope you will help me to figure it out .

Thanks , Regards

NB :)

# Answer
Your ball behaves similar to how a real ball would. You are applying an increasing *force* (which looks unusual to me) you call "speed". The drag of the Rigidbody dampens the effect of the force in a way that grows with speed, which means that there is a max speed called "terminal velocity": http://forum.unity3d.com/threads/terminal-velocity.34667/

Set your drag to zero and the speed will not be clamped to a maximum but this is unrealistic. In any case I don't get why your force (stop calling it "speed") cannot just be a constant.

What you are doing is made difficult by the fact that you are trying to be physics-based along the Y axis, kinematic along the X axis and... teleported along the Z axis. :-)
> 1 votes

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


# Question
Title: Color Based Collision Javascript (Cocos2d-js)
I'm looking to make an isometric game so my partner designed the isometric map (jpg image) along with the map objects (png) on Adobe Illustrator. The thing is I would like to set the player path based on color, for example if the terrain is white the player can go through, if it's black then the player is not allowed to pass. Is this a viable method to do this or are there better methods? Also I'm using Cocos2D-js so my coding is JavaScript

I would appreciate any suggestions.

# Answer
> 1 votes
I am not experienced in Cocos2D or JavaScript, but using color-patterns is very common on Java game development, and I am sure JavaScript will be almost the same.

Here you have an example that does this:

-Every static int on capital letters is a color. (Each element in the game is assigned a color)

-loadBinary() reads levels.png and creates a new element depending on the pixel color it reads.

```
public class Map {
    static int EMPTY = 0;
    static int TILE = 0xffffff;
    static int START = 0xff0000;
    static int END = 0xff00ff;
    static int DISPENSER = 0xff0100;
    static int SPIKES = 0x00ff00;
    static int ROCKET = 0x0000ff;
    static int MOVING_SPIKES = 0xffff00;
    static int LASER = 0x00ffff;

    int[][] tiles;
    public Bob bob;
    Cube cube;
    Array<Dispenser> dispensers = new Array<Dispenser>();
    Dispenser activeDispenser = null;
    Array<Rocket> rockets = new Array<Rocket>();
    Array<MovingSpikes> movingSpikes = new Array<MovingSpikes>();
    Array<Laser> lasers = new Array<Laser>();
    public EndDoor endDoor;

    public Map () {
        loadBinary();
    }

    private void loadBinary () {
        Pixmap pixmap = new Pixmap(Gdx.files.internal("data/levels.png"));
        tiles = new int[pixmap.getWidth()][pixmap.getHeight()];
        for (int y = 0; y < 35; y++) {
            for (int x = 0; x < 150; x++) {
                int pix = (pixmap.getPixel(x, y) >>> 8) & 0xffffff;
                if (match(pix, START)) {
                    Dispenser dispenser = new Dispenser(x, pixmap.getHeight() - 1 - y);
                    dispensers.add(dispenser);
                    activeDispenser = dispenser;
                    bob = new Bob(this, activeDispenser.bounds.x, activeDispenser.bounds.y);
                    bob.state = Bob.SPAWN;
                    cube = new Cube(this, activeDispenser.bounds.x, activeDispenser.bounds.y);
                    cube.state = Cube.DEAD;
                } else if (match(pix, DISPENSER)) {
                    Dispenser dispenser = new Dispenser(x, pixmap.getHeight() - 1 - y);
                    dispensers.add(dispenser);
                } else if (match(pix, ROCKET)) {
                    Rocket rocket = new Rocket(this, x, pixmap.getHeight() - 1 - y);
                    rockets.add(rocket);
                } else if (match(pix, MOVING_SPIKES)) {
                    movingSpikes.add(new MovingSpikes(this, x, pixmap.getHeight() - 1 - y));
                } else if (match(pix, LASER)) {
                    lasers.add(new Laser(this, x, pixmap.getHeight() - 1 - y));
                } else if (match(pix, END)) {
                    endDoor = new EndDoor(x, pixmap.getHeight() - 1 - y);
                } else {
                    tiles[x][y] = pix;
                }
            }
        }

        for (int i = 0; i < movingSpikes.size; i++) {
            movingSpikes.get(i).init();
        }
        for (int i = 0; i < lasers.size; i++) {
            lasers.get(i).init();
        }
    }

    boolean match (int src, int dst) {
        return src == dst;
    }

    public void update (float deltaTime) {
        bob.update(deltaTime);
        if (bob.state == Bob.DEAD) bob = new Bob(this, activeDispenser.bounds.x, activeDispenser.bounds.y);
        cube.update(deltaTime);
        if (cube.state == Cube.DEAD) cube = new Cube(this, bob.bounds.x, bob.bounds.y);
        for (int i = 0; i < dispensers.size; i++) {
            if (bob.bounds.overlaps(dispensers.get(i).bounds)) {
                activeDispenser = dispensers.get(i);
            }
        }
        for (int i = 0; i < rockets.size; i++) {
            Rocket rocket = rockets.get(i);
            rocket.update(deltaTime);
        }
        for (int i = 0; i < movingSpikes.size; i++) {
            MovingSpikes spikes = movingSpikes.get(i);
            spikes.update(deltaTime);
        }
        for (int i = 0; i < lasers.size; i++) {
            lasers.get(i).update();
        }
    }

    public boolean isDeadly (int tileId) {
        return tileId == SPIKES;
    }
}

```

I took this code from cuboc. The game is used as example for LibGDX, it is Open Source and available Here.

I´m sorry I can´t provide JavaScript code, but I think this is pretty similar, and fits your needs really well. Ask if you have any questions, please.

I hope this helps.

(Sorry for any english mistakes, I am spanish, trying to improve my english every day, as well as my development skills).

**EDIT: Forgot to mention this method is valid, but VERY slow. You should use this to pre-load little levels, reading thousands of pixels on runtime would slow your game a lot.**

---
Tags: collision-detection, javascript, isometric, cocos2d-x-js
---


title: Distance per mesh in HLSL directx

text:
# Question
Title: Distance per mesh in HLSL directx
I'm subdividing a sphere so when distance gets greater, the sphere is subdivided less to save memory.

The sphere changes to another sphere when the distance is 10. My problem is that only one triangle gets rendered at a time in the geometry shader. This makes the rest of the sphere the different and causes holes and cracks. like the image below

How can I render all the triangles at one time?

my geometry function code is

```
 [maxvertexcount(50)]
void GS(triangle VertexOut gin[3], inout TriangleStream<GeoOut> stream)
{

if(distance(gin[0]) < 10.0f)
{
VertexOut v[15];
Subdivide2(gin, v);
OutputSubdivision2(v,stream);

}
else if(distance(gin[0]) >= 10)
{
VertexOut v[6];
Subdivide(gin, v);
OutputSubdivision(v,stream);

}
}

```

# Answer
> 2 votes
There are different ways to do this.

**1. Tessellation**

Do this with tessellation. That is exactly what tessellation was created for. You have to read a bit about it, but when you got it, thinks are going much easier.

**2. Structured Buffer**

Instead of using the normal pipeline, you can bind the triangle mesh (vertices) as a structured buffer. Then you can draw one vertex with Setting the Vertex buffer of IA Stage to NULL. Just render 1 vertex, using SV\_VERTEXID. In the Geometry Shader you can access the structured buffer like an texture. Just sample everything you need

**3. Point Primitive**

Why not just render the center of sphere as a single point. Create the whole mesh with a bit of math completly in the Geometry Shader. Performance is not optimal for so many created vertices in the GS, but it does the job. You can read the distance to the camera once, and then create vertices around that center with the radius you want. be carefull with connecting the triangles. Maybe some drawing will help.

Hope the answer gives you some inspiration^^

---
Tags: directx, directx11, hlsl
---


title: Full screen quad in the HLSL Directx 11

text:
# Question
Title: Full screen quad in the HLSL Directx 11
I want to create a full screen Triangle/Quad so I can blur the box that is the quad I made. I want to do this in the vertex buffer. I tried this code:

```
    struct VSQuadOut {
    float4 position : SV_POSITION;
    float2 uv: TEXCOORD;
};

// outputs a full screen triangle with screen-space coordinates
// input: three empty vertices
VSQuadOut VSQuad( uint vertexID : SV_VertexID ){
    VSQuadOut result;
    result.uv = float2((vertexID << 1) & 2, vertexID & 2);
    result.position = float4(result.uv * float2(2.0f, -2.0f) + float2(-1.0f, 1.0f), 0.0f, 1.0f);
    return result;
}

```

I want something like this

Any ideas?

# Answer
> 2 votes
That is my blur shader, it does a simple gaussian blur first in x direction. Then changing rendertarget to be the texture, and render in y direction to the final rendertarget.

```
//////////////////////////
//       OUTPUT

struct VertexOut
{
    float4 PosH     : SV_POSITION;
    float2 Tex      : TEXCOORD;
};

//////////////////////////
//     Screen Quad

VertexOut VS(uint id : SV_VertexId)
{
    VertexOut vout;
    vout.Tex = float2(id % 2, (id % 4) >> 1);
    vout.PosH = float4((vout.Tex.x - 0.5f) * 2, -(vout.Tex.y - 0.5f) * 2, 0, 1);
    return vout;
}

//////////////////////////
//        Blur
float pixelOffset[7] =
{
    -3, -2, -1, 0, 1, 2, 3
};

float blurFactor[7] =
{
    1, 3, 5, 9, 5, 3, 1
};

float4 PS_BlurX(VertexOut pin) : SV_TARGET
{
    float4 sum = float4(0.0f, 0.0f, 0.0f, 0.0f);

    [unroll]
    for (int i = 0; i < 7; i++)
    {
        float4 col = txBlur.Sample(sampleLinear, pin.Tex + float2(pixelOffset[i], 0));
        sum += col * blurFactor[i];
    }
    return sum / 27;
}

float4 PS_BlurY(VertexOut pin) : SV_TARGET
{
    float4 sum = float4(0.0f, 0.0f, 0.0f, 0.0f);

    [unroll]
    for (int i = 0; i < 7; i++)
    {
        float4 col = txBlur.Sample(sampleLinear, pin.Tex + float2(0, pixelOffset[i]));
        sum += col * blurFactor[i];
    }
    return sum / 27;
}

//////////////////////////
//      TECHNIQUES

technique11 BlurTech
{
    pass P0
    {
        SetVertexShader(CompileShader(vs_5_0, VS()));
        SetPixelShader(CompileShader(ps_5_0, PS_BlurX()));
        SetDepthStencilState(noDepth, 0);
        SetRasterizerState(0);
    }

    pass P1
    {
        SetVertexShader(CompileShader(vs_5_0, VS()));
        SetPixelShader(CompileShader(ps_5_0, PS_BlurY()));
        SetDepthStencilState(noDepth, 0);
        SetRasterizerState(0);
    }
};

```

And here is the source code:

```
//render screen quads
    pd3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
    pd3dImmediateContext->IASetVertexBuffers(0, 0, NULL, NULL, NULL);
    pd3dImmediateContext->IASetInputLayout(NULL);

    //set viewport
    pd3dImmediateContext->RSSetViewports(1, &g_Viewport.Blur);

    //blur x
    pd3dImmediateContext->OMSetRenderTargets(1, &g_RTV.BlurTemp, NULL);
    BlurShader::txBlur->SetResource(g_SRV.Blur);
    BlurShader::blurTech->GetPassByIndex(0)->Apply(0, pd3dImmediateContext);
    pd3dImmediateContext->Draw(4, 0);

    //free shader resource
    BlurShader::txBlur->SetResource(0);
    BlurShader::blurTech->GetPassByIndex(0)->Apply(0, pd3dImmediateContext);

    //blur y
    pd3dImmediateContext->OMSetRenderTargets(1, &g_RTV.Blur, NULL);
    BlurShader::txBlur->SetResource(g_SRV.BlurTemp);
    BlurShader::blurTech->GetPassByIndex(1)->Apply(0, pd3dImmediateContext);
    pd3dImmediateContext->Draw(4, 0);

    //free shader resource
    BlurShader::txBlur->SetResource(0);
    BlurShader::blurTech->GetPassByIndex(0)->Apply(0, pd3dImmediateContext);

```

---
Tags: directx11
---


# Question
Title: Unity3D Resize texture without corruption
I am currently working on a solution to make my game look very pixelated, like Doom or Quake. But there is a big problem.

I'm using Unity Personal.

I render my camera to a 1920x1080 texture, then I try to use Texture2D.Resize on it, then render it back to the screen using ScaleMode.StretchToFill.

But the problem is that the texture seems to corrupt when I use Texture2D.Resize on it.

And here is my current code: using UnityEngine; using System.Collections;

```
public class PixelRenderer : MonoBehaviour {

    Texture2D texture;

    // Use this for initialization
    void Start () {
        texture = new Texture2D(256, 256, TextureFormat.ARGB32, false);
    }

    // Update is called once per frame
    void OnPostRender() {
        texture = new Texture2D(Screen.width, Screen.height, TextureFormat.ARGB32, false);
        texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        texture.Apply();
        texture.Resize(256, 256);
    }

    void OnGUI() {
        GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), texture, ScaleMode.StretchToFill);
    }
}

```

Is there something that I'm missing here? Or am I doing something wrong?

# Answer
There is much simpler solution for re-sizing.

```
public static Texture2D Resize(Texture2D source, int newWidth, int newHeight)
{
    source.filterMode = FilterMode.Point;
    RenderTexture rt = RenderTexture.GetTemporary(newWidth, newHeight);
    rt.filterMode = FilterMode.Point;
    RenderTexture.active = rt;
    Graphics.Blit(source, rt);
    Texture2D nTex = new Texture2D(newWidth, newHeight);
    nTex.ReadPixels(new Rect(0, 0, newWidth, newHeight), 0,0);
    nTex.Apply();
    RenderTexture.active = null;
    RenderTexture.ReleaseTemporary(rt);
    return nTex;
}

```

Obviously if you want filtering you also can switch from point filtering to bilinear/trilinear.

Or, alternatively you can do point filtering, which gonna resize your texture with nearest neighbor, and from there you can apply shader like fastblur for much smoother control over resampled quality.
> 6 votes

# Answer
It might be your system or limitations in WebGL. Unless the screen you are resizing to is a Power-of-two texture. (POT/NPOT) Then your selections for read and write pixels would be off.

From the docs for the Texture-Importer:

> It is possible to use other (non power of two - “NPOT”) texture sizes with Unity. Non power of two texture sizes generally take slightly more memory and might be slower to read by the GPU, so for performance it’s best to use power of two sizes whenever you can. If the platform or GPU does not support NPOT texture sizes, then Unity will scale and pad the texture up to next power of two size, which will use even more memory and make loading slower (in practice, this can happen on some older mobile devices). In general you’d want to use non power of two sizes only for GUI purposes.

I would assume this applies to all textures. Not just imported ones. And while the GUI supports NPOT textures, (uGUI and Canvas, maybe?) your texture isn't being scaled in the GUI, it's being scaled as a 2D texture after creating, before being displayed.

You might also want to look at the AssetPostprocessor. It would allow you to set your texture 'import' settings after creation. You may be able to limit texture size, or render a specific mipmap level and get the visual you desire.

Last resort, look for a 'pixlate' shader, and instead of resizing, just use a custom material.
> 0 votes

---
Tags: unity, textures
---


# Question
Title: libgdx: SpriteBatch and ShapeRenderer projection wrong
I'm using LibGDX and the SpriteBatch and ShapeRenderer are having a perspective problem or something... When I draw something with both (code below), the planet texture is smaller than it should be. I can even manually set the size values and it's still wrong.

I'm setting:

```
    Matrix4 matrix = cam.combined;
    batch.setProjectionMatrix(matrix);
    sr.setProjectionMatrix(matrix);

```

and the draw code is...

```
            // outline
            sr.begin(ShapeRenderer.ShapeType.Filled);
            sr.setColor(Color.BLACK);
            sr.circle(c.getPos().x,c.getPos().y,c.getSize());
            sr.end();

            // planet tex
            batch.begin();
            batch.draw(c.getTexture(), c.getDrawPosition().x, c.getDrawPosition().y, c.getSize(), c.getSize());
            batch.draw(c.getShadow(), c.getDrawPosition().x, c.getDrawPosition().y, c.getSize(), c.getSize());
            batch.end();

```

Both the texture and the shape are centered properly and c.getSize() should always be returning the same value, so I'm trying to figure out why this isn't working. I've tried manually setting the value for size and it still does it, so either the texture is being rendered at the wrong size or somehow the ShapeRenderer and SpriteBatch are using a different camera/projection.

# Answer
It looks like you want to draw the circle with half the `c.size ()` as the `circle` method's third parameter is radius, not diameter.

```
sr.circle(c.getPos().x,c.getPos().y,c.getSize() / 2.0f);

```

Either that or multiply the width and height passed in the draw calls for the textures by two.

The draw calls on the `SpriteBatch` takes width and height and the width of a circle is two times the radius.
> 1 votes

---
Tags: android, libgdx, spritebatch
---


# Question
Title: Minimum number of moves algorithm in Java
I'm looking to implement the minimum number of moves algorithm for the java game I'm developing but I can't quite figure it out.

Here's an example picture:

There are also some specifications about this:

> The solution in the example above **is not unique**; other solutions would also be valid as long as the "final character layout (or the positioning of the characters in the nodes)" matches a certain condition (I don't think that's very relevant now so won't go into detail). Also, the nodes aren't actually moved, only it's content.
>
> Adjacent elements cannot be swapped (i.e. in the example above, on the starting side's first swap, 'E' couldn't be swapped with neither 'A' or 'B'; B could be swapped with any character but 'E' and so on.)
>
> The same character can be swapped as many times as one wishes. So, for example, 'B', in the starting side of the picture, could be swapped with 'D' in the first move (B and D trade places) and then 'B' could be swapped with, let's say, 'E' (so B and E trade places).

So how exactly should I approach this, in order to get the **minimum moves**? I don't need a full solution, but some pseudo-code or a couple of hints would be greatly appreciated!

# Answer
As people have said in comments section, A\* or (AStar) is a viable algorithm for this, and a good waypoint.

Here you have a generic AStar implementation in Java so you can start with something. Please, ask if you have any question.

```
import java.util.*;

public class AStar {

  public static class PriorityList extends LinkedList {

    public void add(Comparable object) {
      for (int i=0; i<size(); i++) {
        if (object.compareTo(get(i)) <= 0) {
          add(i, object);
          return;
        }
      }
      addLast(object);
    }
  }

  protected List constructPath(AStarNode node) {
    LinkedList path = new LinkedList();
    while (node.pathParent != null) {
      path.addFirst(node);
      node = node.pathParent;
    }
    return path;
  }

  public List findPath(AStarNode startNode, AStarNode goalNode) {

    PriorityList openList = new PriorityList();
    LinkedList closedList = new LinkedList();

    startNode.costFromStart = 0;
    startNode.estimatedCostToGoal =
      startNode.getEstimatedCost(goalNode);
    startNode.pathParent = null;
    openList.add(startNode);

    while (!openList.isEmpty()) {
      AStarNode node = (AStarNode)openList.removeFirst();
      if (node == goalNode) {
        // construct the path from start to goal
        return constructPath(goalNode);
      }

      List neighbors = node.getNeighbors();
      for (int i=0; i<neighbors.size(); i++) {
        AStarNode neighborNode =
          (AStarNode)neighbors.get(i);
        boolean isOpen = openList.contains(neighborNode);
        boolean isClosed =
          closedList.contains(neighborNode);
        float costFromStart = node.costFromStart +
          node.getCost(neighborNode);

        // check if the neighbor node has not been
        // traversed or if a shorter path to this
        // neighbor node is found.
        if ((!isOpen && !isClosed) ||
          costFromStart < neighborNode.costFromStart)
        {
          neighborNode.pathParent = node;
          neighborNode.costFromStart = costFromStart;
          neighborNode.estimatedCostToGoal =
            neighborNode.getEstimatedCost(goalNode);
          if (isClosed) {
            closedList.remove(neighborNode);
          }
          if (!isOpen) {
            openList.add(neighborNode);
          }
        }
      }
      closedList.add(node);
    }

    return null;
  }

}

```
> 1 votes

---
Tags: java, libgdx, algorithm
---


title: 2D TileMap smooth lighting

text:
# Question
Title: 2D TileMap smooth lighting
I want to implement (a smooth) lighting into my 2D Maps. I want to have the basic idea. What I thought of is 2 components.

The Scene's Ambient light:
The Tiles and Sprites are tinted into this colour first. For example if it's nighttime, the ambient color is very dark so you can barely see anything.

The Scene's Light sources: The Light Sources have a Radius, intensity and a falloff. The more a tile or sprite is near a light source, the more it gets illuminated by it.

What I thought about the soft lights is that a tile/ sprite has a bounding. Since Tiles are always quadratic, I assume I can interpolate between all four edges of the bounding.The Edges of two neighbouring tiles have the same illumination,similar to vertex lighting in 3D. Does someone have an approach how to start this?

# Answer
> 1 votes
One method you could use is lightmaps. It depends on how big your tile maps get I guess but a good thing about lightmaps is that they dont have to be the same resolution as your tilemaps.

So say you have a 2d tilemap, each tile is 16\*16 and you have 10X10 tiles ( to make the maths easy ). This is 160\*160 pixels.

You create a 160X160 bitmap ( rgb if you want coloured lights ) and plot your lighting onto it only.

You then take the corner positions of each of your tiles and use that as coordinates into the lightmap.

So tile at coord 8X3 is gets the rgb at coord (8\*16), (3\*16) from the lightmap. You then apply this to the tile corner.

Sprites would use the same method.

A good thing about lightmaps is that you can also bake shadows into them.

# Answer
> 1 votes
You can set spotlights and simulate light by a raycast algorithm and interpolate to have the light intensity, here's an approximation in javascript that i wrote to test something similar some time ago, read it carefully, it's not clean as it could be but it can help you to find out your own solution.

```
var canvas = document.getElementsByTagName("canvas")[0];
canvas.height = 300;
canvas.width = 300;
var ctx = canvas.getContext("2d");

var vec2 = function(_x,_y){
    this.x = _x || 0;
    this.y = _y || 0;

    this.add = function(v){
        var t = new vec2;
        t.x = this.x + v.x;
        t.y = this.y + v.y;
        return t;
    }
}

var Player = function(){
    var fov = 15;
    var direction;
    var speed = 2;
    var acceleration = new vec2(0,0);
    var pos = new vec2(0,50*world.ts);

    this.pos = function(){
        return pos;
    }
    this.Draw = function(){
        ctx.save();
        ctx.fillStyle = "red";
        ctx.fillRect(pos.x, pos.y, world.ts , world.ts);
        ctx.restore();
    }

    this.Move = function(kc){
        pos.x++;
        if(pos.x > canvas.width)pos.x = 0;
    }

    this.Update = function(){
        // var nextstep = pos.add(
        // if()
    }

    this.RayCast = function(){
        world.tileVisible("clear");
        var rays = 3600;
        var visible = [];
        var angle = 360/rays;

        for(var r = 0; r < rays; r++){
            var p = new vec2(pos.x + world.ts/2, pos.y - 1 + world.ts/2);
            var ang = (angle * r) * (Math.PI / 180);

            for(var f = 0; f < fov; f++){
                var pointing = new vec2(p.x + (world.ts*f) * Math.cos(ang), p.y + (world.ts*f) * Math.sin(ang));
                if(world.getTileByCoord(pointing)){
                    world.tileVisible(pointing);
                }else{
                    world.tileVisible(pointing);
                    break;
                }
            }
        }

    }
}

var WorldMap = function(){
    var size = 100;
    var ts = 3;
    var visible = {};

    var tiles = (function(){
        var temp = [];
        for(var y = 0; y < size; y++){
            var row = [];
            for(var x = 0; x < size; x++){
                (y != 50 && Math.floor(Math.random()*100) > 90)? row.push(0) : row.push(1);
            }
            temp.push(row);
        }
        return temp;
    })();

    this.Draw = function(){
        for(var y = 0; y < tiles.length; y++){
            for(var x = 0; x < tiles[0].length; x++){

                if(this.isVisible(x,y)){
                    if(tiles[y][x]){
                        // ctx.strokeRect(0 + (ts * x), 0 + (ts * y), ts, ts);
                    }else{
                        ctx.fillRect(0 + (ts * x), 0 + (ts * y), ts, ts);
                    }
                }else{
                    ctx.save();
                    ctx.fillStyle = "grey";
                    ctx.fillRect(0 + (ts * x), 0 + (ts * y), ts, ts);
                    ctx.restore();
                }
            }
        }

    }

    this.getPortion = function(cpos, fov, cb){
        var temp = [];
        var ini = new vec2(Math.round(cpos.x - fov.x/2), Math.round(cpos.y - fov.y/2));

        for(var y = ini.y; y < ini.y + fov.y; y++){
            for(var x = ini.x; x < ini.x + fov.x; x++){
                if(tiles[y] && typeof tiles[y][x] == "number"){
                    if(cb) cb(new vec2(x,y));
                    else temp.push(new vec2(x,y));
                }
            }
        }

        if(!cb) return temp;
    }

    this.getTileByCoord = function(tile){
        return tiles[Math.round(tile.y/ts)][Math.round(tile.x/ts)];
    }

    this.tileVisible = function(tile){
        if(tile == "clear"){ delete visible; visible = {};}
        if(!visible[Math.round(tile.x/ts)])
            visible[Math.round(tile.x/ts)] = {};

        visible[Math.round(tile.x/ts)][Math.round(tile.y/ts)] = true;
    }

    this.isVisible = function(tile, y){
        if(!y){
            if(visible[Math.round(tile.x/ts)] && visible[Math.round(tile.x/ts)][Math.round(tile.y/ts)])
                return true;
            return false;
        }else{
            if(visible[tile] && visible[tile][y])
                return true
            return false;
        }
    }

    this.setVisibles = function(vis){
        visible = vis;
    }

    this.map = tiles;
    this.ts = ts;
}

function Raycast(args){
    var map = args.map;
    var center = args.center || {x: map.length/2,y: map[0].length/2};
    var los = args.lengthOfSight || map.length/2;
    var ts = args.tileSize || 5;
    var prec = args.precision || 100;
    var block = args.vBlock || [0];

    var visibles = {};

    var rays = 3600 * ((prec || 100)/100);
    var los = los || map.length;
    var visible = [];
    var angle = 360/rays;

    var getTileByCoord = function(tile){
        return map[Math.round(tile.y/ts)][Math.round(tile.x/ts)];
    }

    var tileVisible_1 = function(tile){
        if(!visibles[Math.round(tile.x / ts)])
            visibles[Math.round(tile.x / ts)] = {};

        visibles[Math.round(tile.x / ts)][Math.round(tile.y / ts)] = true;
    }

    var tileVisible = function(tile){
        if(!visibles[Math.round(tile.x)])
            visibles[Math.round(tile.x)] = {};

        visibles[Math.round(tile.x)][Math.round(tile.y)] = true;
    }

    var getTilesCrossed = function(ini, end){
        if(!window.first){
            console.log(ini,end);
            window.first = 1;
        }
        var steep = Math.abs(ini.y - end.x) > Math.abs(ini.y - end.x);
        if (steep) {
            ini = new vec2(ini.y, ini.x);
            end = new vec2(end.y, end.x);
        }
        if (ini.x > end.x) {
            ini = new vec2(ini.y, ini.x);
            end = new vec2(end.y, end.x);
        }

        var deltax = end.x - ini.x;
        var deltay = Math.abs(end.y - ini.y);
        var error = 0;
        var ystep;
        var y = ini.y;

        if(ini.y < end.y){
            ystep = 1;
        }else{
            ystep = -1;
        }

        for (var x = ini.x; x <= end.x; x++) {
            if(typeof map[y][x] == "number"){
                var t = map[y][x];
                if(steep)
                    tileVisible(new vec2(y,x));
                else
                    tileVisible(new vec2(x,y));

                if(block.indexOf(t) >= 0) break;

                if(!steep){
                    error += deltay;
                }

                if (2 * error >= deltax) {
                    y += ystep;
                    error -= deltax;
                }
            }
        }
    }

    var ini = new Date().getTime();

    for(var r = 0; r < rays; r++){
        var p = new vec2(center.x, center.y);
        var ang = (angle * r) * (Math.PI / 180);

        for(var f = 0; f < los; f++){
            var pointing = new vec2(p.x + (ts*f) * Math.cos(ang), p.y -1  + (ts*f) * Math.sin(ang));
            var t = parseInt(getTileByCoord(pointing));
            if(typeof t == "number" && block.indexOf(t) < 0){
                tileVisible_1(pointing);
            }else{
                tileVisible_1(pointing);
                break;
            }
        }
    }

    // console.log("raycast in: ",new Date().getTime() - ini);
    return visibles;
 }

world = new WorldMap();
pj = new Player();

window.timer = setInterval(function(){
  ctx.clearRect(0,0,canvas.width,canvas.height);
  world.setVisibles(
    Raycast({
      map: world.map,
      center: {x: pj.pos().x,y: pj.pos().y},
      tileSize: world.ts,
      lengthOfSight: 10,
      precision: 100,
      vBlock: [0]
    })
  );
  world.Draw();
  pj.Draw();
  pj.Move();
},1000/60);
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<canvas></canvas>
```

---
Tags: java, 2d, lighting
---


title: OpenGL ES 2.0 facet lighting

text:
# Question
Title: OpenGL ES 2.0 facet lighting
I am trying to figure out if there is a way to achieve facet lighting in OpenGL ES 2.0 without extensions. I know it is possible if I don't used indexed vertices but I don't really want to do that because it is a bit wasteful. I have seen people use dFdx and dFdy to achieve this in the shader but unfortunately they are only avaible with extensions here. Are the other options or is there perhaps a way to implement these functions manually?

# Answer
> 1 votes
Unfortunately, when it comes to lighting, some way or another, you'll need some normals.

As you mentioned, for flat shading, you need per triangle normals, which implies vertices duplication, compared to smooth shading.

The most often used techniques to compute normals in an OpenGL shader (using dfx/dfy or geometry shader) are not available in gles 2.0.

Still, there could be another more exotic technique that you could use. This technique consist in storing per triangle normals in CPU memory and construct an array of these to send to the GPU before drawing the mesh.

Let's say you have a 4 triangle tetrahedron (4 vertices). You could the construct an array of 12 normals based on the normals for the 4 triangles repeated 3 times for each vertex involved in the triangle. You can then bind this array to a specific attribute of your shader before each rendering, separately from your non redundant indexed array. In the shader, you'll then get the same normal for the three vertices of a triangle so you'll be able to do flat shading.

Anyway, this technique will eat up some CPU cycles and also some memory bandwidth as you'll have to transfer data between CPU and GPU memory before each mesh rendering.

Indeed, other techniques like dfx/dfy will consume some GPU cycles.

Then, in the end, my advice would be to profile your rendering time in order to find the best solution for you app.

For example, if you are short in GPU cycles, it's better to have pre-computed normals in a vbo even if this leads to vertices duplication. If you are short in the CPU, again, pre-computed normals are a better choice. If you're short in GPU memory, then on the fly GPU normals computation could be a good solution...

Hope this helps.

---
Tags: opengl, shaders, lighting, opengl-es2
---


title: What is the Z plane?

text:
# Question
Title: What is the Z plane?
I am learning the basics of geometry shaders and I came across references to the "Z plane." It's pretty easy to visualize the X and Y planes, but where does the Z plane reside in Cartesian space? Wikipedia says

> it can be thought of as a modified Cartesian plane

So how exactly am I going to visualize it? Looking at google images doesn't help either. I am not a math savvy person so can someone help me understand the Z plane better?

# Answer
You can think that z-plane is like a book glued to your monitor screen . You look at it, and each z-coord represents a page ( which then, have their x,y-coords ).

Also, maybe those three images will help you a little:
> 5 votes

---
Tags: geometry, terminology
---