texts: Where and how to store players collection in a computer card game?

texts:
I am developing a trading card game ( something like Hearthstone but not as complex) and I am faced with the following problem: I don't know what is the optimal way to store players collections and decks (the cards that they have available).

I thought of storing their collections on a local file on their device, but that seems bad, as they could probably modify that file and get themselves cards that they shouldn't have.

The second idea is that i could save all their decks and collection in a database. But having one table for each player isn't possible. Having one table with all that data something like PlayerCards(id, cardId, playerName, deckName) seems like it might work, but the table would be huge, and containg quite a bit of redundant data (cards that are in the same collection but are in multiple decks).

What would be the proper way to do it?


texts:
I have a ball that moves along a platform. The ball is characterized as a sphere that has a radius and a position. The platform basically is a rectangle consisting of two vertex triangles. Its class also stores the normal of the platform.

While moving the ball and applying the physics of gravity doesn't pose a problem, I just can't get the sphere to rotate correctly. To represent the rotation(s) I'm using Qt's QQuaternion class.

Here's my current rotation code:

QVector3D right = QVector3D::crossProduct(tile->getSurfaceNormal(), step).normalized();
QVector3D forward = QVector3D::crossProduct(right, tile->getSurfaceNormal()).normalized();

float radian = QVector3D::dotProduct((ball - position), forward) / radius;
angularRate = ((radian / interval) * 180.0f / M_PI) * right;

QQuaternion rotation(angularRate.length() * interval, angularRate);
orientation = rotation * orientation;

The orientation quaternion is initialized like this:

orientation = QQuaternion(0.0f, QVector3D(0.0f, 0.0f, 1.0f));

When drawing the ball I update the model matrix (QMatrix4x4) like this:

    modelMatrix.setToIdentity();
    modelMatrix.translate(position.x(), position.y(), position.z());
    modelMatrix.rotate(orientation);
    modelMatrix.scale(radius);

What I noticed when debugging is that the final model matrix gets NAN values in the first three columns. Is there any physical flaw in my calculation or could it have to do with the model matrix itself?

If that's important, here's the full code for updating the ball's properties:

void Ball::update(float interval) {
    collision = false;

    // Calculate new velocity
    velocity += (MOVE_FORCE / mass * interval) * pushDirection;
    velocity.setY(velocity.y() - (GRAVITY * interval));

    /* Collision detection */
    QVector3D normal(0.0f, 0.0f, 0.0f);
    QVector3D step = interval * velocity;
    QVector3D ball = position + step;

    // Check all tiles for collision with ball
    for (unsigned int i = 0; i < tiles->length(); i++) {
        Tile *tile = tiles->at(i);
        QVector<QVector3D> mainVertices = tile->getVertices();

        QVector3D a1 = VectorMath::closestPointOnTriangle(ball, mainVertices[0], mainVertices[1], mainVertices[2]);
        QVector3D a2 = VectorMath::closestPointOnTriangle(ball, mainVertices[2], mainVertices[3], mainVertices[0]);

        float d1 = (ball - a1).length();
        float d2 = (ball - a2).length();

        QVector3D a = (d1 <= d2) ? a1 : a2;
        QVector3D aN = a - tile->getAdjustedSurfaceNormal();

        float aBallLength = (a - ball).length();
        float aNormalBallLength = (aN - ball).length();

        if (aBallLength <= radius || aNormalBallLength <= radius) {
            QVector3D distance = (aBallLength <= aNormalBallLength) ? a - ball : aN - ball;
            float l = distance.length();

            QVector3D move = -((radius - l) / l) * distance;

            // Rotation
            QVector3D right = QVector3D::crossProduct(tile->getSurfaceNormal(), step).normalized();
            QVector3D forward = QVector3D::crossProduct(right, tile->getSurfaceNormal()).normalized();

            float radian = QVector3D::dotProduct((ball - position), forward) / radius;
            angularRate = ((radian / interval) * 180.0f / M_PI) * right;

            ball += move;
            normal += move;

            collision = true;
        }
    }

    // Set new ball position
    position = ball;

    normal.normalize();

    // Applying rebound
    if (collision) {
        float velocityNormal = QVector3D::dotProduct(velocity, normal);
        QVector3D rebound = (-(1 + ELASTICITY) * velocityNormal) * normal;

        velocity += rebound;
    }

    // Damping
    velocity *= DAMPING;

    QQuaternion rotation(angularRate.length() * interval, angularRate);
    orientation = orientation * rotation;

    if (position.y() < -10.0f) {
        reset();
    }
}


texts: How to check whether an angle lies within a specific negative to positive range?

texts:
I'm trying to develop a script that detects if an object's angles are tilting too much.

I am new to Unity, and I am sure this is not the best way to test an object's angles, but I am trying to learn C# so I'd rather figure that out myself.

All I want to know is how to check whether a value is between -101 and 101.

I have tried this so many different ways, and even though it is working fine for positive integers, the if statement is not applying the moment that my z angle becomes negative.

Here is what I have tried so far:

(maxangle = 101, minangle = -101)

if(Player.transform.rotation.eulerAngles.z > Mathf.Sign(-101) &&
Player.transform.rotation.eulerAngles.z < maxangle),

if(Player.transform.rotation.eulerAngles.z > minangle &&
Player.transform.rotation.eulerAngles.z < maxangle)


texts: Where do i start with game development when i'm terrible at art and 3d modelling?

texts: I've wanted to try and make my own game for a while now but i'm i'm terrible at art, textures and 3D modelling but i want to learn it so has anyone got any pointers to get started with the whole shebang?


texts: Game Mechanics for character development in an RPG

texts:
I recently asked a question here on a different stack about how to write strong characters given the limitations of the RPG genre. After all, even in an RPG, which is somewhat story friendly, many gamers just want to get on with the game. I understand the impulse and have no desire to punish the players of my game for just wanting to play my game.
The Goal:
I want to create a character driven ensemble cast jRPG/cRPG with strong characters that the player begins to know and love.
The Problem:
I don't want to shove story or backstory or dialogue down peoples throats when they just want to fight battles and level up and complete quests. Especially when this can get very repetitive when a player is 'stuck'.
Current Solutions:

Skippable Dialogue and cutscenes: This feature will often be used by players and can cause problems of its own. Many people will skip the important parts. Then you need to make the important bits unskippable or keep a quest log to hold their hand.
Characters make predetermined choices: This is the thing I can use the most. But I need to also allow the player to make some decisions too. Need might be a strong word; I want. I also don't want to define my characters by a string of choices they made throughout an adventure story.
Blank Canvas: This is where the character is just a representation of what the player makes of them. Their dialogue, their actions, their appearance and personality are all given to them by the player, not the game designer. This doesn't work for me. I have multiple characters. Plus I don't feel strongly that I can develop a game that facilitates the player projecting themselves onto the character, and that is a different skill and style.

The Question:
What are some game mechanics that can facilitate character development. My Writing question was how do I write within the above constraints. My question here is: What other game mechanics are available to seamlessly integrate character development into my game?

My question is not a dupe of How can I make my players interested in the game lore of my MMORPG?. While we have similar problems, I am working on a single player jRPG which allows for different approaches to story and character than an MMO. I am also not looking for just back-story to develop character. For instance, one of the answerers to my linked writing question mentioned a characters battle-cry as an opportunity to develop their personality, which is decidedly not story.


texts:
I created a map only with an image layer in tiled map editor.

When I want to load the map the layer isn't shown. Only the background color.

Followed the tutorial from
http://www.gamefromscratch.com/post/2014/04/16/LibGDX-Tutorial-11-Tiled-Maps-Part-1-Simple-Orthogonal-Maps.aspx

Here the code (left out empty overrides):

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;

public class Main extends ApplicationAdapter implements InputProcessor  {
TiledMap tiledMap;
OrthographicCamera camera;
TiledMapRenderer tiledMapRenderer;

@Override
public void create () {
    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();

    camera = new OrthographicCamera();
    camera.setToOrtho(false,w,h);
    camera.update();
    tiledMap = new TmxMapLoader().load("C:/Users/Robin/Desktop/map.tmx");
    tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap);

    Gdx.input.setInputProcessor(this);
}

@Override
public void render () {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    camera.update();
    tiledMapRenderer.setView(camera);
    tiledMapRenderer.render();
}
}

I added a tileset and tried again (just a little test). Only the tiles are visible:

Any ideas how to set the layer visible?

Greetings
Kaito


texts: How can I ensure my Direct3D 11 shader scripts are not visible to the user?

texts:
Right now for my engine, I rely on pixel and vertex shader script text files that I load and compile when I need them.

What I am wondering is, how can I store the shader scripts so that they are not visible to the user?

Maybe I could hard code them inside the executable, then dump them to .ps and .vs files, compile them, and then delete those files?

Or I could place them in binary files along, say, level or model data, and then generated/compiled in that same way?

Or would I pack them as text files inside a proprietary compressed file format with all the other resources, that is uncompressed and loaded as needed?

I'd like to avoid storing them in a way that's hackable or easy to reverse engineer.


texts: How to properly implement alpha blending in a complex 3D scene?

texts:
I know this question might sound a bit easy to answer but It's driving me crazy. There are too many possible situations that a good alpha blending mechanism should handle, and for each Algorithm I can think of there is something missing.

These are the methods I've though about so far:

First of I though about object sorting by depth, this one simply fails because Objects are not simple shapes, they might have curves and might loop inside each other. So I can't always tell which one is closer to camera.
Then I thought about sorting triangles but this one also might fail, thought I'm not sure how to implement it there is a rare case that might again cause a problem, in which two triangle pass through each other. Again no one can tell which one is nearer.
The next thing was using depth buffer, at least the main reason we have depth buffer is because of the problems with sorting that I mentioned but now we get another problem. Since objects might be transparent, in a single pixel there might be more than one object visible. So for which object should I store pixel depth?
I then thought maybe I can only store the most front object depth, and using that determine how should I blend next draw calls at that pixel. But again there was a problem, think about two semi transparent planes with a solid plane in middle of them. I was going to render the solid plane at the end, one can see the most distant plane. Note that I was going to merge every two planes until there is only one color left for that pixel. Obviously I can use sorting methods too because of the same reasons I've explained above.
Finally the only thing I imagine being able to work is to render all objects into different render targets and then sort those layers and display the final output. But this time I don't know how can I implement this algorithm.


texts: How to create a 32 bit red texture byte buffer

texts:
I want to make a red texture image buffer. Would anyone help me to make it in right way. I have tried following:

std::vector<BYTE> redTexture(w*h*4);
const auto stride = w * 4;
BYTE* buf = redTexture.data();

for (int i = 0; i < h; ++i)
{
  const auto redValue = Gdiplus::Color::Red;
  memcpy(buf, &redValue, stride);
  buf += stride;
}


texts: How to rotate several game objects without rotating individual objects

texts:
I have a some game objects that are a unit away from the center. They are all contained in a parent object, see the image below.

When I rotate the parent object by 60°, the game objects individually rotate, as  below.

Below is the script attached to the parent object that I use to rotate the parent object.

    IEnumerator RotateSquaresParent(Vector3 byAngles, float duration)
{
    Quaternion fromAngle = gameObject.transform.rotation ;
    Quaternion toAngle = Quaternion.Euler (transform.eulerAngles);
    toAngle = Quaternion.Euler (gameObject.transform.eulerAngles - byAngles);

    for(float t = 0f ; t <= 1f ; t += Time.deltaTime/duration)
    {
        gameObject.transform.rotation = Quaternion.Lerp(fromAngle, toAngle, t) ;
        yield return null ;

    }
    gameObject.transform.rotation = Quaternion.Lerp(fromAngle, toAngle, 1);

}

How can I rotate the parent object containing these square game objects without rotating them individually?

UPDATE

The squares represent enemy objects that would be shooting projectiles (yet to work on that) in my game. Thats why they'd have to be straight. As a player approaches a given child square (enemy), I would want to rotate individual child squares based on proximity and other conditions to possibly face the player object.


texts: Painter algorithm on transparant objects

texts:
Why do you have to use the painter's algorithm when drawing transparant objects ? Can't you just use a z-buffer, draw all non transparant/opaque objects, then draw all transparant/opaque objects last?

Sorry if it is a stupid question, but i guess it's something all beginners run in to.


texts: What are the common rendering optimization techniques for the geometry pass in a deferred shading renderer?

texts:
I have been developing a game engine using OpenGL 3 and C++ (and glfw for window management). I have advanced so far, got most of the things done except sound entities and optimizations. The engine uses deferred shading so since deferred shading is itself a tiring process for an average GPU, I want to optimize the rendering process as much as possible.

The current system consists of a Scene, containing a Renderer and the current World and the World holds entities and lighting entities as separate std::vectors.

So basically every time the Scene gets called by ->render(), and it calls the Renderer, passinng the world as a parameter and gets the entity iterators from the world, draws them to the FBO and then goes through the lighting entities for the second pass. And I think this is not enough.

My current algorithm iterates through everything even if the entity is not in the screen space. I am thinking of a way to optimize the current rendering algorithm so it only calls the API functions only for the visible objects, so what are the common techniques for optimizing such renderer ?


texts: How to achieve good looking surface net normals?

texts:
EDIT After Victor T.'s suggestion (ignore seams):

I'm using elastic surface nets to convert a 3D voxels into a nice smooth mesh. The mesh part, is great, however, I can't seem to find a decent looking method of getting proper vertex normals for each voxel.
I've been reading a couple of forums, like this one from reddit and this one from Stack Overflow. Using the method described in the stack overflow one, I got normals that looked like this:

(Shaded)

(Scaled Normals)

While this might seem okay, it doesn't work very well with flat surfaces, and if I try to add methods for dealing with flat surfaces, it messes everything else up. And yet it still doesn't look ideal.

Using cross products of the vertices to get the normal, I was only able to get a hard shaded mesh, that did look decent, however, it can't distinguish up and down, so it doesn't look right in overhangs. It also is hardshaded, and I want smooth shading.

Question :
What are ways I can achieve a better looking normal? What techniques are common for this? Is there any way modified methods I can use that are better than the ones I am doing? I am okay if the best looking method is expensive.

I can post source code if needed.

Thanks

UPDATE

After Victor T.'s suggestion, I managed to get great looking surface normals! One problem, the corners don't look right, I was unable to find any correlation between why is the normals on the corners need to be flipped (0 - normal).

Here is a picture :

EDIT 2:
Managed to particially solve the problem, however, when the vertice is on a 45 degree angle on all axises, it seems to mess up and needs to be flipped:


texts:
I have a class BlinkingBehaviour which inherits from MonoBehaviour. Game objects attached to scripts containing classes that inherit from BlinkingBehaviour should, as the name suggests, blink.

BlinkingBehaviour is a small class so I will share the entirety of its code here:

public class BlinkingBehaviour : MonoBehaviour
{
    private Renderer renderer;

    public bool BlinkingEnabled;
    public Color BlinkingColour = new Color(1.0f, 127f / 255f, 39f / 255f);

    protected float CurrentColourScale;
    protected float ColourScaleIncrementPerUpdate = 0.005f;

    protected const float MaxColourScale = 2f;

    protected void Start()
    {
        this.renderer = this.gameObject.GetComponent<Renderer>();
    }

    protected void Update()
    {
        if (this.BlinkingEnabled)
        {
            SetBlinkingColour();
        }
        else
        {
            SetColour();
        }
    }

    protected void SetColour()
    {
        if (this.CurrentColourScale <= 1f)
        {
            this.renderer.material.SetColor("_EmissionColor", this.BlinkingColour * this.CurrentColourScale);
        }
        else
        {
            this.renderer.material.SetColor("_EmissionColor", this.BlinkingColour * (MaxColourScale - this.CurrentColourScale));
        }
    }

    protected virtual void SetBlinkingColour()
    {
        SetColour();
        this.CurrentColourScale += ColourScaleIncrementPerUpdate;

        if (this.CurrentColourScale <= MaxColourScale)
        {
            return;
        }

        ResetBlinkingColourScale();
    }

    protected void ResetBlinkingColourScale()
    {
        this.CurrentColourScale = 0f;
    }
}

I have a class Lamp which inherits from BlinkingBehaviour. I attached Lamp.cs to an object in my scene. In my inspector, I checked the BlinkingEnabled option, expecting to see the Lamp game object blinking after I pressed "Play".

However, the object did not blink.

Here is my Lamp class:

public class Lamp : BlinkingBehaviour
{
    private void Start()
    {
        base.Start();
    }

    private void Update()
    {
        base.Update();
    }
}

After setting various breakpoints, I could see that the Start() method was hit in both Lamp and BlinkingBehaviour. I could also see that this.gameObject.GetComponent<Renderer>(); returned a valid component.

On the other hand, my breakpoint in the Update method in Lamp was never hit.

What can I do to fix this issue?

UPDATE:

I deleted the Start() and Update() methods from my derived class. I discovered something new: The Update() method in BlinkingBehaviour is never called, even though Start() is.


texts: WinAPI window taking 50% of CPU when idle

texts:
I'm currently working on a game that creates a window using WindowsAPI.  However, at the moment the process is taking up 50% of my CPU.  All I am doing is creating the window and looping using the code found below:

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    MSG message = {0};
    WNDCLASSEX wcl = {0};

    wcl.cbSize = sizeof(wcl);
    wcl.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
    wcl.lpfnWndProc = WindowProc;
    wcl.cbClsExtra = 0;
    wcl.cbWndExtra = 0;
    wcl.hInstance = hInstance = hInstance;
    wcl.hIcon = LoadIcon(0, IDI_APPLICATION);
    wcl.hCursor = LoadCursor(0, IDC_ARROW);
    wcl.hbrBackground = 0;
    wcl.lpszMenuName = 0;
    wcl.lpszClassName = "GL2WindowClass";
    wcl.hIconSm = 0;

    if (!RegisterClassEx(&wcl))
        return 0;

    hWnd = CreateAppWindow(wcl, "Application");

    if (hWnd)
    {
        if (Init())
        {
            ShowWindow(hWnd, nShowCmd);
            UpdateWindow(hWnd);

            while (true)
            {
                while (PeekMessage(&message, 0, 0, 0, PM_REMOVE))
                {
                    if (message.message == WM_QUIT)
                        break;

                    TranslateMessage(&message);
                    DispatchMessage(&message);
                }

                if (message.message == WM_QUIT)
                    break;

               if (hasFocus)
            {
                elapsedTime = GetElapsedTimeInSeconds();
                lastEarth += elapsedTime;
                lastUpdate += elapsedTime;
                lastFrame += elapsedTime;
                lastParticle += elapsedTime;

                if(lastUpdate >= (1.0f / 100.0f))
                {
                    Update(lastUpdate);
                    lastUpdate = 0;
                }
                if(lastFrame >= (1.0f / 60.0f))
                {
                    UpdateFrameRate(lastFrame);
                    lastFrame = 0;
                    Render();
                    SwapBuffers(hDC);
                }
                if(lastEarth >= (1.0f / 10.0f))
                {
                    UpdateEarthAnimation();
                    lastEarth = 0;
                }
                if(lastParticle >= (1.0f / 30.0f))
                {
                    particleManager->rightBooster->Update();
                    particleManager->rightBoosterSmoke->Update();
                    particleManager->leftBooster->Update();
                    particleManager->leftBoosterSmoke->Update();

                    particleManager->breakUp->Update();
                    lastParticle = 0;
                }
            }
            else
            {
                WaitMessage();
            }
            }
        }

        Cleanup();
        UnregisterClass(wcl.lpszClassName, hInstance);
    }

    return static_cast<int>(message.wParam);
}

So even when I am not drawing anything when the window has focus it still takes up 50%.  I don't understand how this is taking up so much system resources.

Am I doing something wrong?

Any help would be much appreciated, thank you!


texts: How do I move the camera sideways in Libgdx?

texts:
I want to move the camera sideways (strafe). I had the following in mind, but it doesn't look like there are standard methods to achieve this in Libgdx.

If I want to move the camera sideways by x, I think I need to do the following:

Create a Matrix4 mat
Determine the orthogonal vector v between camera.direction and camera.up
Translate mat by v*x
Multiply camera.position by mat

Will this approach do what I think it does, and is it a good way to do it?
And how can I do this in libgdx? I get "stuck" at step 2, as I have not found any standard method in Libgdx to calculate an orthogonal vector.

EDIT: I think I can use camera.direction.crs(camera.up) to find v. I'll try this approach tonight and see if it works.

EDIT2: I got it working and didn't need the matrix after all:

Vector3 right = camera.direction.cpy().crs(camera.up).nor();
camera.position.add(right.mul(x));


texts: Animation of moving circle by square's outer surface

texts:
I want to make this animation in OpenGL, here I attached a simple gif how I want it to looks like:

Main problem is that I can not figure out how to move by corner - circle should smoothly move by corner, not to just jump to another side's begin position.
import Blender
from Blender import Draw,BGL
from Blender.BGL import *
from math import sin,cos
import time

squareLength, squareX, squareY, circleRadius = 200, 200, 200, 20
movingX, movingY = 0, 0

def event(evt, val):
    if evt == Draw.ESCKEY :
        Draw.Exit()

def gui():
    global movingX, movingY

    glClearColor(0.17, 0.24, 0.31, 1.0)
    glClear(BGL.GL_COLOR_BUFFER_BIT)
    glLineWidth(1)
    glColor3f(0.74, 0.76, 0.78)

    glBegin(GL_QUADS)
    glVertex2i(squareX, squareY)
    glVertex2i(squareX, squareY + squareLength)
    glVertex2i(squareX + squareLength, squareY + squareLength)
    glVertex2i(squareX + squareLength, squareY)
    glEnd()

    glColor3f(0.58, 0.65, 0.65)

    glPushMatrix()

    if movingX == -circleRadius:
      if movingY < squareLength:
        movingY += 1
      else:
        movingX = 0
        movingY = squareLength + circleRadius
    else:
      if movingY == squareLength + circleRadius:
        if movingX < squareLength:
          movingX += 1
        else:
          movingX = squareLength + circleRadius
          movingY = squareLength
      else:
        if movingY < 0:
          if movingX > 0:
            movingX -= 1
          else:
            movingX = -circleRadius
            movingY = 0
        else:
          if movingY > 0:
            movingY -= 1
          else:
            movingX = squareLength
            movingY = -circleRadius

    glTranslatef(movingX, movingY, 0)

    glBegin(GL_LINE_LOOP)
    for i in xrange(0, 360, 1):
        glVertex2f(squareX + sin(i) * circleRadius, squareY + cos(i) * circleRadius)
    glEnd()

    glPopMatrix()

    Draw.Redraw(1)

Draw.Register(gui, event, None)

Can you please say me, how can I optimize this code to make circle moving by corners?
Just start learning computer graphics and think up such exercises for training, so I will really appreciate for any help.


texts:
Let's make a list of the best books that every game developer should read.

Each answer should have a single book (by title and optionally author), a link to buy the book, and a short synopsis of what the book is about.


texts:
I'm just getting started with libGDX and have run into a snag registering an InputListener for a button. I've gone through many examples and this code appears correct to me but the associated callback never triggers ("touched" is not printed to console). I'm just posting the code with the abstract game screen and the implementing screen. The application starts successfully with a label of "Exit" in the bottom left hand corner, but clicking the button/label does nothing.

I'm guessing the fix is something simple. What am I overlooking?

public abstract class GameScreen<T> implements Screen
{
    protected final T game;
    protected final SpriteBatch batch;
    protected final Stage stage;

    public GameScreen(T game)
    {
        this.game = game;
        this.batch = new SpriteBatch();
        this.stage = new Stage(0, 0, true);
    }

    @Override
    public final void render(float delta)
    {
        update(delta);

        // Clear the screen with the given RGB color (black)
        Gdx.gl.glClearColor(0f, 0f, 0f, 1f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

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

    public abstract void update(float delta);

    @Override
    public void resize(int width, int height)
    {
        stage.setViewport(width, height, true);
    }

    @Override
    public void show()
    {
        Gdx.input.setInputProcessor(stage);
    }

    // hide, pause, resume, dipose
}

public class ExampleScreen extends GameScreen<MyGame>
{
    private TextButton exitButton;

    public ExampleScreen(MyGame game)
    {
        super(game);
    }

    @Override
    public void show()
    {
        super.show();

        TextButton.TextButtonStyle buttonStyle = new TextButton.TextButtonStyle();
        buttonStyle.font = Font.getFont("Origicide", 32);
        buttonStyle.fontColor = Color.WHITE;

        exitButton = new TextButton("Exit", buttonStyle);
        exitButton.addListener(new InputListener() {
            @Override
            public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
                System.out.println("touched");
            }
        });
        stage.addActor(exitButton);
    }

    @Override
    public void update(float delta)
    {
    }
}


texts: The math of normal mapping without a dot product

texts:
As far as I understand the technical details about a good normal mapping they go like this:

everything gravitates around the concept of vertex
the artist provides an RGB image and an UV map, the UV map maps the 3D vertexes of the object to the 2D surface of said image
the image represents the information about 3 vectors/axis/directions, U and V, and the color in a point P of the normal map is carrying the information about the magnitude of the normal, the tangent and the bitangent
you are basically interpolating real vertex realV on the 3D geometry with vertex fakeV that you create by interpreting the normal map and the uv map
people that use a dot product assume that the vertex fakeV that you create/compute has a normal fakeV_N that is orthogonal to both the tangent fakeV_T and the bitangent fakeV_B, the tuple (fakeV_N,fakeV_T, fakeV_B) can be basically seen as a new set of cartesian axis in the local space of the vertex since they form a 90 ° angle with each other.
Since there is an infinite amount of vectors that are orthogonal to fakeV_N the orientation of fakeV_T and fakeV_B is determined by the coordinates of UV values on the map

Now the part that I don't get

If you are going to say that said tuple is not orthonormal, where do you get the information about which angles the algorithm is supposed to create between each pair of vectors ? The informations that I get from the artists are the RGB at a specific point, the UV location relative to the 3D vertex on the geometry and the 2D coordinate system on the image that is the normal map, basically the values of U and V .
Where do I get the accurate angles for tangent and the bitangent ?


texts: How can I resize the Unity Facebook SDK's login dialog to fit my vertical phone screen?

texts:
I have a Facebook-login button for my iOS game, but Facebook's login panel is entirely too big:

The panel is cut off on both sides. It allows for input, but I cannot see most of it. My aspect ratio is 2:3; for vertical phone screens.

I tried to use FB.Canvas.SetResolution and .SetAspectRatio both did nothing. I have not attempted to view this on an iPhone yet, only in my Unity debug view.

I have never worked with Facebook SDK before, and can't find this issue discussed elsewhere, so help would be appreciated!


texts: Multiplayer architecture in games like Diablo 2

texts:
So I've been wondering, what kind of architecture would games like world of warcraft, diablo 2 (which is most probably a different beast than WoW) use?

As far as I know, RTS games state-syncs every client and server, and the input from the clients get relayed to the server, and all states from all clients will get the same input, because everything is synced.

And because everything is synced, state changes can be done safely, thus allowing large numbers of entities in the game (e.g zerglings), because the clients only need to know the players' inputs.

This is all fine and well, but AFAIK diablo 2 allows players to join servers mid-game, which leads me to believe they use a different architecture. I'm stumped on how they do this though, and if elegant solutions exist for such a thing. Does anyone have a better idea?


texts: How can I generate a 3d model via a series of transforms?

texts:
Is it possible to generate 3D models using some sort of object transformation (like it's shown here), using PovRay or any other tool, and import them into Blender / Unity?

For example starting with a primitive sphere:

And applying a series of transforms/noise to generate something like:

Then baking them in, resulting in a 3D model of an asteroid that can be used in game.


texts: How to make unitypackage from allseen alliance's android sdk?

texts:
Im making an offline multiplayer for Android device by Unity and I found only one way to do this is the allseenalliance sdk. After download its from here I found that to use it I need to create an .unitypackage file but I cant understand the tutorial they give
> Open a CMD window.
>     Add the path to Unity.exe (the Unity IDE) to your PATH, if it is not there already.
>         For example, set PATH=%PATH%;C:\Program Files\Unity\Editor
>     CD to each "unity" folder in the SDK, and run the following command in each location:
>         Unity.exe -batchmode -nographics -quit -projectPath %CD% -exportPackage Assets AllJoyn.unitypackage
>     This command creates the AllJoyn.unitypackage file.

Please give me a noob tutorial for this or the package file, thanks.
p/s:Is there another way to connect mobile device without internet in unity3d?


texts: A building imported from Blender is missing parts

texts:
I want to make a scene that a player can log into using my django server and walk around.
So, I created a simple building inside Blender that resembles my school's building. (And yes, the building from the SIMS would look 1000 times better because all I have been using is cubes and loop cuts and extrudes)

I exported this building from Blender as an FBX format. And then when I drag and drop it into the Unity, some of the parts are gone.

How can I fix this?


texts: I'm working with 2D sprites - and I want to do 3D style depth testing with them. When writing a pixel shader for them, I get access to the semantic DEPTH0. Would writing to this value help? It seems it doesn't. Maybe it's done before the pixel shader step? Or is depth testing only done when drawing 3D things (I'm using SpriteBatch)? Any links/articles/topics to read/search for would be appreciated.


texts: Implementing a Custom Mouse Cursor in XNA

texts:
I have tried making a custom mouse cursor, hiding the real mouse, taking the real mouse delta and clamping it to a maximum speed. Here is the problem:

In windowed mode, the "real" mouse cursor moves off the window while the custom mouse cursor (since it's movement is being scaled) is still somewhere inside the game window. This becomes bizarre and is obviously not desired, as clicking at this point means clicking on things outside the game window. Is there any way to accomplish this in windowed mode?
In fullscreen mode, the "real" mouse cursor is bounded to the edges of the screen. So I get to a point where there is no more mouse delta, yet my custom cursor is still somewhere in the middle of the screen and hence can't move further in that direction. If I wanted to clamp it to the edge of the screen when the real cursor is at the edge, then I would get an abrupt jump to the edge of the screen, which isn't desired either

Any help would be appreciated. I'd like to be able to limit the speed of the mouse.


texts: What strategies are best for managing Game Center and offline saves in the same app?

texts:
I have an iOS app for which I want to use the Game Center API for saving games. At the same time, I want to have the option to save multiple games on the local file system, using the familiar save-slots mechanism. I anticipate that a user may not wish to use the Game Center, or may wish to support a guest user on their device.

I initiate authentication and loading asynchronously, as recommended by Apple, which in itself causes issues as the callbacks may arrive before or after the ViewControllers which are interested in them are loaded.

Typically, the app starts before the authentication is complete, which means the offline games are available first and the game center games become available at a later point. However, if the user is using the Game Center, it is likely that these later arriving games are the ones that would be interesting.

I am wondering how to handle these two sets of save-games. My first thought was to allow the user to explicitly switch between Game Center mode and local mode, but Apple explicitly says that you should not do this. I also want to avoid blocking waiting for the authentication to complete. I have to admit that, since I am still in development, I lack the ability to try out various strategies easily.

Are there any good patterns for managing both online and offline saves in an iOS app?


texts: Can I use a match-3 mechanic in my commercial game without being sued by some company holding the patent? I will add some extra features to the mechanic.


texts: What's the best way to time a character AI movement on android/java?

texts:
I'm creating an android game and I'm trying to figure out the best way to time a character position change, something like this:

public void move() {
    //this.posX += 5;
    this.posY += 5;

    if (posY < 350) {
    new Timer().schedule(new TimerTask() {
        public void run()  {
            this.move();
        }
        }, 300, 300);
    }
}

Is this the best way? I'm using Canvas. Thanks for your time.


texts: What formula does this projectile velocity code derive from?

texts:
//Calculate the velocity needed to throw the object to the target at specified angle.
float projectile_Velocity =
            target_Distance / (Mathf.Sin(2 * firingAngle * Mathf.Deg2Rad) / gravity);

Which formula is used to derive this projectile code?


texts: Whats the point of this LPDIRECT3DDEVICE9 reference?

texts:
I'm going through the DirectX 9 MSDN documentation

Which lead me to something rather peculiar, do you need a class reference in DirectX 9?

Can someone tell me what the point of the class reference:

LPDIRECT3DDEVICE9  d3ddev;

I don't see anything using it.

Also maybe point me in the direction to some decent documentation  for DirectX 9 that explains this stuff like this:

LPDIRECT3DDEVICE9 pDevice = NULL;

D3DPRESENT_PARAMETERS d3dpp;

ZeroMemory( &d3dpp, sizeof(d3dpp) );
d3dpp.Windowed   = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_COPY;

in little bit more detail then slapping some code in your face with no actual description of what it's for.


texts: Erasing part of lines in libgdx with ImmediateModeRenderer

texts:
Hi i'm using the ImmediateModeRenderer renderer = new ImmediateModeRenderer10(); to render a line with the next block

renderer.begin(matrix, GL10.GL_LINES);
    renderer.color(color.r, color.g, color.b, color.a);
    renderer.vertex(x0, y0, 0);
    renderer.color(color.r, color.g, color.b, color.a);
    renderer.vertex(x1, y1, 0);
renderer.end();

But know I want to erase some part of that line when I drag the mouse over it, are there any ideas ?


texts: Efficient way to calculate "vision cones" on 2D tile map?

texts:
I'm trying to calculate which tiles a particular unit can "see" if facing a certain direction on a tile map (within a certain range and angle of facing). The easiest way would be to draw a certain number of tiles outward and raycast to each tile. However, I'm hoping for something slightly more efficient. A picture says a thousand words:

The red dot is the unit (who's facing upwards). My goal is to calculate the yellow tiles. The green blocks are walls (walls are between tiles, and it's easy to check if you can pass between two tiles). The blue line represents something like the "raycasting" method I was talking about, but I'd rather not have to do this.

EDIT: Units can only be facing north/south/east/west (0, 90, 180, or 270 degrees) and FoV is always 90 degrees. Should simplify some calculations. I'm thinking there's some sort of recursive-ish/stack-based/queue-based algorithm, but I can't quite figure it out.

Thanks!


texts:
This is just a toy experiment.

I laid out a graph in 2d space, so that every node has x and y coordinates. I'm considering degree of a node as a height value at position x and y of a height map.

I wonder what's the best strategy to interpolate this sparse heightmap with missing values?

Ideally I'd love to have some sort of gravitational pull towards the bottom in the places where I don't have height values. Think of it like somebody dropped fabric on bunch of spikes...


texts: How to draw text with characters rendered in reverse order in a Godot game?

texts:
I need to have some text showing up in my Godot game in a way that each character overlaps the character directly to its right, like so:
     -- ---    -- --
   /  /     \ |  |  |
  /  /       \|  |  |
 /  /  /---\  \  |   ----
/  /  /  \  \  \ |       |
-- --     -- -- - -------

Using a BMFont (.fnt) in a Label node with the values of xadvance specified in the font smaller than the characters width I get this:
     -- ---    -- --
   /  /     \ |  |  |
  /  /       \|  |  |
 /  /  /---\  |  |   ----
/  /  /  \  \ |  |       |
-- --     -- -- - -------

What approach can I use to still be able to use my .fnt font and also store the text with the characters in their natural order, as it would be stored for using with a normal Label or Button control? Which would help for language localization purposes.


texts: Why doesn't glBindVertexArray work in this case?

texts:
From my understanding of what glBindVertexArray does and how it works, the following code should work fine:

First init:

    glGenVertexArraysOES(1, &_vertexArray);
    glBindVertexArrayOES(_vertexArray);

    glGenBuffers(1, &_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, _buffer);
    glBufferData(GL_ARRAY_BUFFER, kMaxDrawingVerticesCount*sizeof(GLKVector3), NULL, GL_DYNAMIC_DRAW);

    glGenBuffers(1, &_indexBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, kMaxDrawingVerticesCount*1.5*sizeof(GLuint), NULL, GL_DYNAMIC_DRAW);

    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(GLKVector3), BUFFER_OFFSET(0));

    glBindVertexArrayOES(0);

And later add new geometry:

glBindVertexArrayOES(_vertexArray);
glBufferSubData(GL_ARRAY_BUFFER, 0, (GLintptr)_data.vertices.length, _data.vertices.bytes);
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, (GLintptr)_data.indices.length, _data.indices.bytes);
glBindVertexArrayOES(0);

However, it doesn't work (there is screen output, but it looks like the buffers were changed between each other). Binding the vertex array is not enough for the vertex/indices buffer to get bound? Because, if I do this:

glBindVertexArrayOES(_vertexArray);
glBindBuffer(GL_ARRAY_BUFFER, _buffer); <-- note this line
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBuffer); <-- note this line

glBufferSubData(GL_ARRAY_BUFFER, 0, (GLintptr)_data.vertices.length, _data.vertices.bytes);
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, (GLintptr)_data.indices.length, _data.indices.bytes);
glBindVertexArrayOES(0);

Everything works/looks as expected. I find it strange, since the vertex array should have taken care of the buffer binding. Otherwise, what's the purpose to have a vertex array if you still have to bind all the buffers?


texts: AoE 2 DE - Modding a building to have two page interface

texts:
I am using Advanced Genie Editor and currently trying to create a copy of a Krepost and give it a second page of units (like the docks).
I have so far been unable to do it as the second page just doesn't show up. The unit's train button is, of course, numbered to appear on the second page (i.e. 21). I tried changing the interface to match that of the dock (i.e. 2) but to no avail. Anyone have any idea regarding how to do it?


texts: How do I keep different platforms code in separate plugins?

texts:
Considering that some game platforms are under NDA and that publishing code publicly using their SDK is not allowed, how do game engine usually manage keeping plugins for different platforms separated?

For example if I make a plugin for PS3 export, it needs to be distributed only to people that do have the PS3 license.

Platform code can happen in many places of the code, and keeping it entirely separated from the core engine seems really hard/impossible to manage to me.

Edit for example:

If I make an open source game engine for which users are allowed to see the code, it means that the core engine is entirely viewable. Using preprocessors or anything like that would allow people to view code subjected to NDA, which doesn't work.

So, the platform-specific code needs to be totally separate from the core engine, but the core engine needs to be able to use it. The most obvious solution is to duplicate implementations of system things for every platform, and when using a plugin you select which implementation you use, but it seems very hard to maintain.


texts: LibGDX render sprites in tiled-map format ( convert texture to sprite )

texts:
I am creating a game in which till now I have used textures to create A 2D tiled game.
I have created a matrix which converts the touch co-ordinates into a array index number and according to that index number, a specific tile gets selected. The problem is that I want to emulate the same behaviour for sprites instead of textures. But I get stuck on what could possibly be given as the co-ordinates for the sprite position? I want to just use Sprites instead of using textures as Sprites are easier to animate. No matter which values I give, the screen remains white and sometimes a different tile's texture gets rendered at a different position. What am I doing wrong?

//      Function returns the position of tile touched
int getPos(int screenX, int screenY) {
    x = screenX / (int)xSize;
    y = screenY / (int)ySize;
    y = Squares_Y - 1 - y;
    int result = y * Squares_X + x;
    return result;
}

// Previous Render function
public void render(float delta) {
    batch.begin();
    Tile current=initial_layout;
    if(current.topLink != null)
    {
        for (int Pos=0; Pos<Squares_X; Pos++) {
            for (int ypos=0; ypos<Squares_Y; ypos++) {
                batch.draw(bg_texture, Pos * xSize, ypos * ySize, xSize, ySize);
                if(current!= null)
                {
                    batch.draw(current.getTexture(), Pos * xSize, ypos * ySize, xSize, ySize);
                    current=current.topLink;
                }
            }
        }
    }
    if(Gdx.input.justTouched()){
        if(win == false)
        {
            int x =Gdx.input.getX();
            int y =Gdx.input.getY();
            touchDown(getPos(x, y));
        }
        else{
            System.out.print("\nLevel Completed !! : " + utils.level);
            game.dispose();
        }
    }
    batch.end();
}

// New Render Function
public void render() {
    batch.begin();
    Tile current=initial_layout;
    if(current.topLink != null)
    {
        for (int Pos=0; Pos<Squares_X; Pos++) {
            for (int ypos=0; ypos<Squares_Y; ypos++) {
                batch.draw(bg_texture, Pos * xSize, ypos * ySize, xSize, ySize);
                if(current!= null)
                {
                    spriteBatch.begin();
                    texture = current.getTexture();
                    sprite = new Sprite(texture,(int)xSize,(int)ySize);
                    sprite.setPosition(Pos * xSize, ypos * ySize);
//                  batch.draw(current.getTexture(), Pos * xSize, ypos * ySize, xSize, ySize);
                    sprite.draw(spriteBatch);
                    current=current.topLink;
                    spriteBatch.end();
                }
            }
        }
    }
    if(Gdx.input.justTouched()){
        if(win == false)
        {
            int x =Gdx.input.getX();
            int y =Gdx.input.getY();
            touchDown(getPos(x, y));
        }
        else{
            System.out.print("\nGame WON for Level : "+utils.level);
            game.dispose();
        }
    }
    batch.end();
}


texts: Render graphics using Doubles in Graphics2D

texts: Currently, I have a JFrame for my game to render in, and I'm using Graphics2D for drawing (The games graphics are fairly simple 2D sprites). However, my delta variable is a double, and all of the Graphics 2D methods (And Grpahics) use int. I tried to type cast the delta to an int, but it just rounds down to 0. So my question is, how can I render graphics using Graphics2D in Java with coordinates that are doubles. Can I convert it to work with Graphics2D if there is no built in way? Or, is there a graphics library that can support doubles for coordinates?


texts:
First, I know there's a question exactly like mine, and some ohter really close, but my implementation of the solutions didn't work at all. Ok, now to the question.

I created some forms of camera based on quaternions, however, for my orbit/chase camera every quaternion I create will roll the camera in an uncontrollable manner. What I want is a function like Unity's Quaternion.LookRotation where you can pass an up vector.
This is a simplification current attempt of implementation:

Vector3 target = -Position; //Because we're looking at the origin
target.Normalize();

float cosine = Vector3.Dot(Vector3.Forward, target);
Vector3 axis = Vector3.Cross(Vector3.Forward, target);
Rotation = Quaternion.CreateFromAxisAngle(axis, (float)Math.Acos(cosine));

//Trying to unroll up vector to Vector3.Up
//based on the other answer but results were unchanged
Vector3 rolledUp = Vector3.Transform(Vector3.Up, Rotation);
Vector3 right = Vector3.Cross(target, Vector3.Up);
Vector3 newUp = Vector3.Cross(right, target);

Vector3 axis2 = Vector3.Cross(rolledUp, newUp);
float angle2 = (float) Math.Acos(Vector3.Dot(rolledUp,newUp));

Rotation = Quaternion.CreateFromAxisAngle(axis2, angle2) * Rotation;

return Matrix.CreateLookAt(
    cameraPosition: Position,
    cameraTarget: Vector3.Transform(Vector3.Forward, Rotation),
    cameraUpVector: Vector3.Transform(Vector3.Up, Rotation));

If my sleepiness got in the way of my clarity, here's what I have:

and here's what I want:


texts: Unity2d: orthographic camera and z-axis?

texts:
I wonder if anyone can help with an explanation of the z-axis and using unity with 2D with an orthographic camera.

Up until now i have only been modifying the x and y values of game objects, thinking this is the correct way. i thought the Z axis didn't exist in 2D space (i.e. unity 2d with orthographic camera) but I do notice that the orthographic camera is placed at -10 on the z axis, if i change this value then the camera disappears. I sort of began to accept that.

Now I cam to a point where I wanted to rotate something, and I notice that rotating eithe on the z or x axis, doesn't seem to do anything, only on the z-axis, there is that z-axis again !

Can anyone tell me when i should be worrying about the z axis in unity using 2D games.

It seems now that it is more important than I once thought :-)

Thanks in advance.


texts: SDL2 sprite batching and texture atlases

texts:
I have been programming a 2D game in C++, using the SDL2 graphics API for rendering. My game concept currently features effects that could result in even tens of thousands of  sprites being drawn simultaneously to the screen. I'd like to know what can be done for increasing rendering efficiency if the need arises, preferably using the SDL2 API only. I have previously given a quick look at OpenGL-based 2D rendering, and noticed that SDL2 lacks a command like

int SDL_RenderCopyMulti(SDL_Renderer* renderer,   SDL_Texture* texture,
                        const SDL_Rect* srcrects, SDL_Rect* dstrects,   int count)

Which would permit SDL to benefit from two common techniques used for efficient 2D graphics:

Texture batching: Sorting sprites by the texture used, and then simultaneously rendering as many sprites that use the same texture as possible, changing only the source area on the texture and the destination area on the render target between sprites. This allows the encapsulation of the whole operation in a single GPU command, reducing the overhead drastically from multiple distinct calls.
Texture atlases: Instead of creating one texture for each frame of each animation of each sprite, combining multiple animations and even multiple sprites into a single large texture. This lessens the impact of changing the current texture when switching between sprites, as the correct texture is often ready to be used from the previous draw call. Furthemore the GPU is optimized for handling large textures, in contrast to the many tiny textures typically used for sprites.

My question: Would SDL2 still get somewhat faster from any rudimentary sprite sorting or from combining multiple images into one texture thanks to automatic video driver optimizations? If I will encounter performance issues related to 2D rendering in the future, will I be forced to switch to OpenGL for lower level control over the GPU?

Edit: Are there any plans to include such functionality in the near future?


texts: Turning layout items invisible in Android layout

texts:
I am trying to turn some items visibility off when submitting a high score.

I have the following code but it does not appear to work.  Any suggestions?

mSignText = (EditText) findViewById(R.id.sign);

submitBtn = (ImageView) this.findViewById(R.id.submitbtn);

mSignText.setVisibility(View.GONE);

submitBtn.setVisibility(View.GONE);


texts: Collisions between mesh (bounding-box) and Vertex/Index Buffer

texts:
I have a short Question:
I'm trying to add Collisions in my 3D DirectX9 game and my World is Stored in a LPDIRECT3DVERTEXBUFFER9 and LPDIRECT3DINDEXBUFFER9 and Rendered per DrawIndexedPrimitive. My Player is a LPD3DXMESH loaded from a .X file. Now I want to detect Collisions between the two! How can I do that? After some research I could only find Collisions between Bounding Boxes and/or Rays!

Apologise my bad English, I'm German! :-)
Hope for fast reply!


texts: What is a GUI element with a filling-up rectangle shape called?

texts:
After every game of StarCraft 1, the statistics screen shows up. The part I like on this screen is the points counter. It starts from zero and then it counts up to the points you have achieved, with a filling-up rectangle shape based on the number it represents.

What is this type of counter called?

For example, the Units bar for Alpha Squadron counts from 0 to 4975.


texts: How to use dynamic resources with SharpDX by detail?

texts:
I've looked through a lot of archives but still cannot figure out how it works.
Taking this overridden one for example.
public DataBox MapSubresource(Buffer resource, MapMode mode, MapFlags flags, out DataStream stream)

Is this method aiming to change the resource with stream. If it is, why would the stream be marked out as if it is an output value rather than input?
If the above one is true, where can I stream my data into the stream to update the buffer? Has it to be between the Map and Unmap methods? And typically how should I stream it (Take vertex buffer for example, what would the format of streaming be like?)
Is it advisable to call the MapSubresource method whenever GPU access is finished(after every frame), and call the UnmapSubresource next frame to allow GPU access so it may save more time when I am keep updating the data?

Thank you!


texts: First frame has a much longer delta time than other frames

texts:
I had a problem where my AI moved extreme at the first frame and then normal after that. I then figured out it was my delta. It's about 0.016 seconds (60 fps), but the first frame was about 19000 seconds, which is obviously impossible. Does anybody know what might be happening? Also the delta later on likes to oscillate from 0.01 to 0.03.

    long time = Sys.getTime() * 1000 / Sys.getTimerResolution();
    float delta = (time - lastFrame) / 1000f;
    lastFrame = time;
    return delta;

That's the delta code.

EDIT: Wow, you guys really like to take the fun out of composing a question with all your editing.


texts: libgdx collision on moving Rectangle with other Rectangle

texts:
I'm making a soccer game where you touch the screen and the player shoot the ball to the touched position with the objective of scoring goals when it hits the goal. The player is just a Sprite and the Ball and the Goal are Rectangles. What I'm trying to do here is when the Ball collides with the Goal the player changes its position to a random one on the screen and the ball resets to the player position, although I'm not actually getting the collision between the Rectangles. Any help would be appreciated.

TLDR : make so that when the ball collides with the goal, the players position changes and the ball resets to the player position.

Game class

private SpriteBatch batch;
private OrthographicCamera cam;

private Texture player1;
private Sprite player;

private Sprite bg;
private Texture back;

private Texture ball1;
private Rectangle ball = new Rectangle();
private Sprite bs;

private Texture goal1;
private Rectangle goal = new Rectangle();

private Texture line;

Ball b = new Ball();

public void create () {

    cam = new OrthographicCamera();
    cam.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    batch = new SpriteBatch();
    batch.setProjectionMatrix(cam.combined);

    player = new Sprite(player1);
    player.setX(MathUtils.random(Gdx.graphics.getWidth()));
    player.setY(MathUtils.random(Gdx.graphics.getHeight() / 2));

    b.position.set(player.getX(), player.getY());

    goal.setWidth(420);
    goal.setHeight(130);
    goal.setX(Gdx.graphics.getWidth()/4-20);
    goal.setY(Gdx.graphics.getHeight() - 180);

    ball.setX(b.position.x);
    ball.setY(b.position.y);
    ball.setWidth(40);
    ball.setHeight(40);

}

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

    b.update(Gdx.graphics.getDeltaTime());

    batch.begin();
    batch.draw(bg, 0, 0);
    if (!Gdx.input.isTouched()) {
        batch.draw(bs, b.position.x, b.position.y);
    }else if (Gdx.input.isTouched()) b.shootToward(Gdx.input.getX(), Gdx.graphics.getHeight() - Gdx.input.getY());
    batch.draw(goal1, Gdx.graphics.getWidth()/4-20, Gdx.graphics.getHeight() - 180, 420, 130);
    player.draw(batch);

    if (goal.contains(ball)) {
        player.setX(MathUtils.random(Gdx.graphics.getWidth()));
        player.setY(MathUtils.random(Gdx.graphics.getHeight() / 2));
    }
    batch.end();
}

Ball class

public void shootToward(float targetX, float targetY) {

    velocity.set(targetX - position.x, targetY - position.y);
}

public void update(float deltaTime) {

    position.add(velocity.x * deltaTime, velocity.y * deltaTime);
    velocity.scl(1 - (.98f * deltaTime));
}


texts: JOGL KeyListener not functioning properly

texts:
I have been having a problem with the JOGL KeyListener where if I hold down a key, it would register the key as pressed for around 1 second, then it would start quickly switching back and forth between pressed and unpressed. However, if I hold more than one key at once, sometimes the key listener "forgets" about one of the keys and keeps it held down (like it should) while releasing the other one (when it shouldn't).

Here is the relevant code in the class:

import com.jogamp.newt.event.KeyEvent;
import com.jogamp.newt.event.KeyListener;

import java.util.HashSet;
import java.util.Set;

public class KeyInput implements KeyListener {
    private static Set<Short> key=new HashSet<Short>();
    public void keyPressed(KeyEvent keyEvent) {
        key.add(keyEvent.getKeyCode());
        System.out.println("added " +keyEvent.getKeyChar());
    }

    public void keyReleased(KeyEvent keyEvent) {
        key.remove(keyEvent.getKeyCode());
        System.out.println("removed " +keyEvent.getKeyChar());
    }

    public static boolean getKey(short k){
        return key.contains(k);
    }
}

I tried using other methods of storing the keys to no avail. How should I fix it so that it properly registers and remembers held down keys? I tried a different program with Swing and it worked fine. It has the exact same code as shown here.


texts:
Ok maybe i'm missing something because its getting late and i've been programming now for about 72 hours straight (minus a nap or 2) ...

I'm trying to write a shader for unity that will apply triplanar texturing to a mesh, here's my shader code ...

Shader "My Shaders/TriPlanar" {
    Properties {
        Tex1 ("Texture 1", 2D) = "white" {}
        Tex2 ("Texture 2", 2D) = "white" {}
        Tex3 ("Texture 3", 2D) = "white" {}
    }

    SubShader {
        Pass {
             CGPROGRAM
                #pragma target 3.0
                #pragma glsl
                #pragma vertex Vert
                #pragma fragment Frag
                #include "UnityCG.cginc"

                sampler2D Tex1;
                sampler2D Tex2;
                sampler2D Tex3;

                struct data
                {
                    float4 position : POSITION;
                    float3 normal;
                    float4 uv : TEXCOORD0;
                };

                data Vert(appdata_base v)
                {
                    data res;
                    res.position = mul( UNITY_MATRIX_MVP, v.vertex);
                    res.normal = v.normal;
                    res.uv = v.texcoord;
                    return res;
                }

                float4 Frag( data input ) : COLOR
                {
                    float4 result;

                    float norX = abs(input.normal.x);
                    float norY = abs(input.normal.y);
                    float norZ = abs(input.normal.z);

                    float total = (norX + norY + norZ);
                    norX /= total;
                    norY /= total;
                    norZ /= total;

                    // get sample from tex1 and apply norX amount to pixel color
                    float4 texXZ = tex2D(Tex1, input.uv.xz);
                    float4 texXY = tex2D(Tex1, input.uv.xy);
                    float4 texYZ = tex2D(Tex1, input.uv.yz);
                    result = (texXZ * norX);

                    // get sample from tex2 and blend norY amount
                    texXZ = tex2D(Tex2, input.uv.xz);
                    texXY = tex2D(Tex2, input.uv.xy);
                    texYZ = tex2D(Tex2, input.uv.yz);
                    result += (texXY * norY);

                    // get sample from tex3 and blend norZ amount
                    texXZ = tex2D(Tex3, input.uv.xz);
                    texXY = tex2D(Tex3, input.uv.xy);
                    texYZ = tex2D(Tex3, input.uv.yz);
                    result += (texYZ * norZ);

                    return result;
                }
            ENDCG
        }
    }
}

The problem is that I only get 1 pixels worth of sample from the texture so I end up ultimately just "colouring" the verts instead of actually texturing them.

How do I tell my shader to build a colour that results in the texture being drawn not just 1 corner pixels worth of it?

EDIT:

The code in the shader is an implementation of a vertex and fragment but the fragment part came from a pixel shader ... i don't understand the difference there (my first problem)

I can't say i've ever written a fragment shader before (a second problem)

Also i'm not setting any uv's in my cpu code (a problem when I come to use my shader but i'll face that later) ... odd that I get anything at all to be honest, however I'm applying this to a cube game object generated by unity and I get strips of texture so i can't be that far off.


texts:
I have a custom class named Stars:

class Star
{
    public int primaryID;
    public string properName;
    public string HIPID;
    public string HDID;
    public string HRID;
    public string GLID;
    public string BFID;
    public decimal rightAscension;
    public decimal declination;
    public string magnitude;
    public string colourIndex;
    public int scale;
    public int red;
    public int green;
    public int blue;
    public bool isSimulated;
    public double x;
    public double y;
    public double z;

    public void setDetails(int primaryID, string properName, string HIPID, string HDID, string HRID, string GLID, string BFID, decimal rightAscension, decimal declination, string magnitude, string colourIndex)
    {
        this.primaryID = primaryID;
        this.properName = properName;
        this.HIPID = HIPID;
        this.HDID = HDID;
        this.HRID = HRID;
        this.GLID = GLID;
        this.BFID = BFID;
        this.rightAscension = rightAscension;
        this.declination = declination;
        this.magnitude = magnitude;
        this.colourIndex = colourIndex;
        decimal deg2rad = 0.01745329251994329576923690768489m;

        this.isSimulated = true;

        // Decimal datatype is used to make sure that values are very accurate and precise
        decimal degrees_ra;
        decimal degrees_dec;
        decimal radians_ra;
        decimal radians_dec;

        degrees_ra = Decimal.Multiply(rightAscension, 15);
        degrees_dec = declination;

        radians_ra = Decimal.Multiply(degrees_ra, deg2rad);
        radians_dec = Decimal.Multiply(degrees_dec, deg2rad);

        // Converted from decimal to double because the Math library cannot work with decimals
        float distanceStars = 19113;

        this.x = (distanceStars * Math.Cos(decimal.ToDouble(radians_dec)) * Math.Cos(decimal.ToDouble(radians_ra)));
        this.y = (distanceStars * Math.Cos(decimal.ToDouble(radians_dec)) * Math.Sin(decimal.ToDouble(radians_ra)));
        this.z = (distanceStars * Math.Sin(decimal.ToDouble(radians_dec)));
    }

    public Vector3 getVector()
    {
        return new Vector3((float)z, (float)y, (float)x);
    }
}

There are many of these stars and I want to instantiate them at run-time:

void plotStars()
{
    int i = 0;
    while (i < (StarDataBank.Instance.NumOfStars))
    {
        string name = StarDataBank.Instance.StarName[i];
        string HIP = StarDataBank.Instance.StarIDHIP[i];
        string HD = StarDataBank.Instance.StarIDHD[i];
        string HR = StarDataBank.Instance.StarIDHR[i];
        string GL = StarDataBank.Instance.StarIDGL[i];
        string BF = StarDataBank.Instance.StarIDBF[i];
        decimal RA = Convert.ToDecimal(StarDataBank.Instance.StarRA[i]);
        decimal Dec = Convert.ToDecimal(StarDataBank.Instance.StarDec[i]);
        string Mag = StarDataBank.Instance.StarMag[i];
        string ColI = StarDataBank.Instance.StarCI[i];

        var star = new Star();
        star = Instantiate(ObjectStar, transform.position + star.getVector(), Quaternion.identity);

        star.transform.parent = StarObject.transform;
        star.transform.localScale = new Vector3(star.scale, star.scale, star.scale);
        i++;
    }
}

But I am experiencing a lot of errors.

Unity isn't instantiating the Stars because it can't convert UnityEngine.Transform to Star
Star doesn't contain definition of Transform

Is there a way to assign a class as a gameobject?


texts: changing color of sprite not every frame

texts:
So I have been trying making this game, which changes color of sprites in it.
It should only happen when OnMouseDown().
but it is executing every frame and cannot go out of the couroutine.
I want the color change to be slower. Please mark the colors should still change.

Please Help,

public class control : MonoBehaviour
{
    public bool startstop = false;
    SpriteRenderer m_SpriteRenderer;
    private void Update()
    {
        StartCoroutine("Changecolor", 3f);
    }
    IEnumerator Changecolor()
    {
        yield return new WaitForSeconds(3);
        if(startstop == true)
        {
            int random = Random.Range(1, 4);
            if (random == 1)
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.blue;
            }
            else if(random == 2)
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.red;
            }
            else if(random == 3)
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.green;
            }
            else
            {
                m_SpriteRenderer = GetComponent<SpriteRenderer>();
                m_SpriteRenderer.color = Color.yellow;
            }
        }
    }
    private void OnMouseDown()
    {
        startstop = !startstop;
    }
}


texts: How do you handle animations that are for transitioning between states?

texts:
How does one usually handle animations that are for going between a game object's states? For example, imagine a very simple game in which a character can only crouch or stand normally. Currently, I use a custom Animation class like this:

class Animation{
 int numFrames;
 int curFrame;
 Bitmap spriteSheet;
 //... various functions for pausing, returning frame, etc.
}

and an example Character class

class Character{
 int state;
 Animation standAni;
 Animation crouchAni;
 //... etc, etc.
}

Thus, I use the state of the character to draw the necessary animation.

if(state == STATE_STAND)
    draw(standAni.updateFrame());
else if(state == STATE_CROUCH)
    draw(crouchAni.updateFrame());

Now I've come to the point where I want to draw "in-between" animations, because right now the character will just jump immediately into a crouch instead of bending down. What is a good way to handle this? And if the way that I handle storing Animations in the Character class is not a good way, what is?

I thought of creating states like STATE_STANDING_TO_CROUCHING but I feel like that may get messy fast.


texts: GameLogic Model as Property or Constants with lookup in other Models?

texts:
Basically imagine a game where the Player has a Weapon which has a BulletType/type of Bullet.

Now Player, Weapon and Bullet are Models having properties and they would represent Instances in the game.

I want to Instantiate a Bullet when the Player fires and I have to check what BulletType the Weapon currently has, but I don't understand what kind of Property Weapon should have to represent the current type of Bullet.

Should in the Weapon class the BulletType be an Instance of Bullet or should I use some kind of Constant as BulletType that would map to the Bullet Model?

class Weapon{
    IBullet currentBulletType //<-- a Bullet Model with Position and everything
}

or

class Weapon{
    BulletTypeConstant currentBulletType // a Constant that is mapped to a specific Model
}

The first approach is using a whole Model to represent the BulletType currently equipped.
The Second uses some kind of Constant that must then be mapped to a specific Model of Bullet on firing.

I always find myself troubled as to which approach would be better.
Or perhaps you have an even better Idea.
Thanks


texts: Best physics engine for OpenGL ES (different implementations)?

texts:
Can you recommend a good physics engine which is easily portable between WebGL and other OpenGL ES implementations like in Android and iPhone?

I don't want a game engine. Only the physics part.


texts:
I'm using the  OpenGL Programming Guide, 8th Edition with MSVC 2013 but I can't get the triangles.cpp file to run.

These are the errors popping up:
http://puu.sh/jAokn/c07420cf46.png


texts: Why is the depth test not done on geometry before rasterization?

texts:
It seems the only time depth is used to discard data is during rasterization, i.e. at the fragment level.

In the geometry stage, I've only see culling and clipping of vertices. Is it not possible to determine whether if a triangle is behind another triangle using just vertex data (depth?) and discard if so? Wouldn't this save all the work later in scan conversion?


texts: Finding the "Important" nodes of a grid path

texts:
On a Navmesh Grid, all nodes are essentially vertices or turn-points so the returned path is efficient in that it only involves points where an entity must change its direction.

A grid path, however, involves nodes at every point along the path. For long paths, there could be hundreds of nodes contained even though most of those nodes just follow a line and don't change the direction of the path.

Note: Paths are lists of a GridNode object.

I haven't tested this hypothetical issue in application yet so my first question is: Is this even an issue? For a game that requires real-time pathfinding for roughly 200 entities on a grid of 4,096 nodes, will the returned paths consume too much memory and resources? My main concern is related to how entities will handle paths, which is to check for reaching the target node before moving on to the next one and calculating the new direction needed. With more spaced out nodes, entities might have more leeway with following their paths if pushed off of it.

Secondly, if it is a potential issue, how would I solve it and cull out the insignificant nodes of a path?


texts: How can I defy competing games who are forcing their users to write 5 star reviews?

texts:
Background
I've developed an app in a pretty contested category. It's one of the top three games in terms of quality (out of about 200 relevant games in this category; there are no large publishers with this type of game).
The Problem
While I have the best ratings overall (4.92 of 5 stars; ~1000 reviews), nearly all competing games started to force their users to write 5 star reviews (including a minimum amount of characters). While these apps can't actually verify the rating afaik, most users are fulfilling their demand because of psychological reasons. They even write things like:

This app is ****, but I have to write this review... 5 stars.
Not that good, but I want to get XYZ, so I have to write this review... 5 stars.

Unfortunately the poor algorithms of Google Play will rank an app higher, the more ratings they have (My app does fine in Apples App Store, since the manual review process seems to punish these fraudulent apps).
But with Google, even if you are below a 4 star average, you'll rank better if you have a ton of reviews. Number of downloads and update frequency doesn't seem to count at all.
The Consequences
This all started about three years ago and since then my Play Store ranking is on a downward spiral but I refuse to join this unethical train of fake reviews. Not only that it's a huge financial loss, it's highly depressing.
From rank 1-3 my app went down to about 30 for the most relevant keywords.
What I tried
I talked to multiple people from Google, but none of them feels responsible and sends me to the Developer Policy over and over again. Some of them even had the nerve to recommend Adwords to me as a counter measure.
I also reported some of these apps using Google Plays "Report App" feature. Nothing happened.
What I have already thought about

Join the train of manipulated reviews

This would work for sure, but as stated above, it's a no-go to me.

Asking the competitors to stop

This would require massive administrative work and probably wouldn't work out well. Especially since there are many profit-oriented trash developers.

Making my users aware of this issue

Since my competitors already copied multiple unique features of my game, I know for sure they are constantly checking my app for new updates. So they would quickly notice this whiny cry for help, which could lead to a massive backlash and make things even worse. Also it's nearly as dishonorable as faked reviews.
The Question
Do you have any advices how I could preserve my game without risking its, and also my personal reputation?


texts: Render scene twice in OpenGL, overlay second render with tranparency

texts:
Is it possible to render two scenes (same scene with different setups) without any alpha, and after that is done just overlay the result from the second render on top of the first layer with a static transparency?

And how do I do it? I want it fast so the transparency should not be implemented
during rendering, only on the final overlay process.

Basically I am asking for an efficient OpenGL post-processing method to combine the two different renders when drawing to screen.


texts: Problem with Widget Event Reporting in Libgdx

texts:
So I'm trying to test an ImageButton on an Android device.  I can get the button to appear on the screen, but when I press it nothing happens or appears on the log.  Here is what I have in the Show() method of a class that implements the Screen class.

public void show() {
    uistage = new Stage();
    Texture tankSprite = new Texture(Gdx.files.internal("TankSpriteBase.png"));
    tank = new Tank(0, true, tankSprite);
    tank.rect.x = 100;
    tank.rect.y = 100;
    tank.rect.width = 44;
    tank.rect.height = 45;

    dropSound = Gdx.audio.newSound(Gdx.files.internal("drop.wav"));
    rainMusic = Gdx.audio.newMusic(Gdx.files.internal("rain.mp3"));

    rainMusic.setLooping(true);
    rainMusic.play();

    float w = 800;
    float h = 400;

    camera = new OrthographicCamera();
    camera.setToOrtho(false, w, h);
    batch = new SpriteBatch();
ImageButton.ImageButtonStyle ibs = new ImageButton.ImageButtonStyle();
    ibs.up = new TextureRegionDrawable(
                new TextureRegion(
                        new Texture(Gdx.files.internal("direction_left.png"))));
    ibs.down = new TextureRegionDrawable(
                new TextureRegion(
                        new Texture(Gdx.files.internal("direction_left_pressed.png"))));

    leftButton = new ImageButton(ibs);
    leftButton.setX(300);
    leftButton.setY(300);
    leftButton.addListener(new InputListener() {
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
                Gdx.app.log(LOG, "down");
                System.out.println("down");
                return true;
        }

        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
                Gdx.app.log(LOG, "up");
                System.out.println("up");
        }
    });
    leftButton.setWidth(ibs.up.getMinWidth());
    leftButton.setHeight(ibs.up.getMinHeight());
    leftButton.setBounds(0, 0, ibs.up.getMinWidth(), ibs.up.getMinHeight());
    leftButton.setTouchable(Touchable.enabled);

    uistage.addActor(leftButton);
            Gdx.app.log(LOG, "Width is "+Gdx.graphics.getWidth()+" and height is "+Gdx.graphics.getHeight());

    background = new Texture(Gdx.files.internal("background.png"));
    background.setFilter(TextureFilter.Linear, TextureFilter.Linear);

    TextureRegion region = new TextureRegion(background, 0, 0, 512, 301);

    sprite = new Sprite(region);
    sprite.setSize(0.9f, 0.9f * sprite.getHeight() / sprite.getWidth());
    sprite.setOrigin(sprite.getWidth()/2, sprite.getHeight()/2);
    sprite.setPosition(-sprite.getWidth()/2, -sprite.getHeight()/2);
            }

Might anyone know why this doesn't appear to be working?


texts: Why do I have to divide the origin of a quad by 4 instead of 2?

texts:
I'm currently transitioning from C#/XNA to C#/OpenTK but I'm getting stuck at the basics.

So I have this Sprite-Class:

public static bool EnableDebugDraw = true;
public float X;
public float Y;

public float OriginX = 0;
public float OriginY = 0;

public float Width = 0.1f;
public float Height = 0.1f;

public Color TintColor = Color.Red;
float _layerDepth = 0f;

public void Render()
    {
        Vector2[] corners =
        {
            new Vector2(X-OriginX,Y-OriginY), //top left
            new Vector2(X +Width -OriginX,Y-OriginY),//top right
            new Vector2(X +Width-OriginX,Y+Height-OriginY),//bottom rigth
            new Vector2(X-OriginX,Y+Height-OriginY)//bottom left
        };
        GL.Color3(TintColor);
        GL.Begin(BeginMode.Quads);
        {
            for (int i = 0; i < 4; i++) GL.Vertex3(corners[i].X,corners[i].Y,_layerDepth);
        }
        GL.End();

        if (EnableDebugDraw)
        {
            GL.Color3(Color.Violet);
            GL.PointSize(3);
            GL.Begin(BeginMode.Points);
            {
                for (int i = 0; i < 4; i++) GL.Vertex2(corners[i]);
            }
            GL.End();

            GL.Color3(Color.Green);
            GL.Begin(BeginMode.Points);
            GL.Vertex2(X + OriginX, Y + OriginY);
            GL.End();
        }

With the following setup I try to set the origin of the quad to the middle of the quad.

_sprite.OriginX = _sprite.Width / 2;
_sprite.OriginY = _sprite.Height / 2;

but this sets the origin to the upper right corner of the quad, so i have to

_sprite.OriginX = _sprite.Width / 4;
_sprite.OriginY = _sprite.Height / 4;

However this is not the intended behaviour, could you advise me how I fix this?


texts: Libgdx implement 2d drop shadow for transparent sprites

texts:
I am a libgdx learner. For an learning application that I am developing using libgdx on android, I need to show drop shadow or glow effect when a sprite is touched. The sprites are created from a TextureAtlas and can have any irregular shape as per the transparent image in the texture. There are a ton of images so it is not possible to create a separate shadow image for each one.

I have looked at some options but haven't been able to figure out how to do it. What I have tried include:

OpenGL ES drop shadows for 2D sprites
I tried the approach of taking the texture and bluring it using the blurutils class provided by Matt Deslauriers at https://github.com/mattdesl/lwjgl-basics/wiki/OpenGL-ES-Blurs. The code I have used is below. But the performance was very slow on android devices for the BlurUitls.blur call.

private Sprite getShadowSprite(String name,float width,float height) {
//Load the texture
Pixmap orig = new Pixmap(Gdx.files.internal(name));

//blur it
Pixmap blurred = BlurUtils.blur(orig, 16, 2, true);

//we then create a GL texture with the blurred pixmap
Texture blurTex = new Texture(blurred);
Sprite shadow=new Sprite(blurTex);
shadow.setSize(width,height);
shadow.flip(false,true);

//dispose our blurred data now that it resides on the GPU
blurred.dispose();
return shadow;
}

I do not have much of an understanding of shaders. Please advise as to what is the most performant way to be able to generate a drop shadow for a transparent image in libgdx.


texts: How can I round out the corners of a quad in OpenGL?

texts:
Even though I think the image is pretty self-explanatory, I'm going to explain what I am trying to achieve:

I was working on a game, and I needed a GUI framework, that I decided to build myself. As a first thing, I tried rendering a simple 2d quad with an orthographic projection. I was not satisfied with the boxy shapes windows had, so I tried fixing the problem by adding a texture; all this worked until I tried implementing resizing: whenever I changed the window size, the texture was warping, and it did not look good. Now I'm trying to use more than just two triangles, to smooth the corners of the windows. Now, my question is: how can I determine the number of triangles each window should have to have in order to obtain smoother corners? I would like to have some sort of "smooth" variable, that specifies how smooth(how many triangles are used) the window is. Thanks everyone for the help

EDIT:

I was thinking about this: do you guys think that generating the vertices of the window based on a condition in real time would be a good idea?

something like(proto code):

if(smooth == 1)
{
    //define quad vertices
    float vertices[] =
    {
       bla,bla,
       bla,bla,
       bla,bla....
    }
}

if(smooth == 2)
{
    float vertices[] =
    {
       bla,bla,
       bla,bla,
       bla,bla....
    }
}

In a way, this would work, but I'm pretty sure there is a much better way to do this...


texts:
I am trying to work out a way to add a text to the top left corner of the viewport when two of my sprites overlap. One of them is a item and the other is my character. I can already detect for overlap and even "pick" the item (kill the sprite) when I click a key. However I would like that a text saying something like "Click "E" to pick the sword!" appeared while the collision function is active and when I kill the sprite by picking it up the text would vanish.

I tryed including the text in the collision function itself but I suppose this way I am rendering the text multiple times ( the fps drop a lot) and I just want to create it once and remove it according to my purposes. My code:

function collisionHandler(dude,the_sword) {
pickObject.onDown.add(function () {
        the_sword.kill();
    }, this);
 }

game.physics.isoArcade.overlap(dude, the_sword, collisionHandler, null, this);

 // message saying to pick // Where to put this?
var style = { font: "30px Arial", fill: "#ff0044"};
var pick_message = this.game.add.text(0,20,"Click 'E' to pick up the sword!",style);
pick_message.fixedToCamera = true;

Any idea on how to do this? Thank you.


texts: Generate random starting points at same distance between them

texts:
Is there an algorithm to generate random 2D points that are at the same distance between each other? Useful for starting points. Check map:

Don't be picky, I know in the image points are not at the same distance, lol, but you get the idea.


texts: What gamepad functionality can be assumed?

texts:
When I offer gamepad support, the simplest solution seems to be to assume XBox controllers and use a library that maps the most frequent gamepads to a similar layout.

Now if I want to minimize customer complaints, can I just use all the buttons (in a sensible way), or are there some I should avoid because they are missing on some common controllers?

The question is primarily about PCs (Linux/Windows/Mac), but does the answer change if we consider gamepads for mobile devices?

The one thing I know about is that we cannot use any input scheme that requires the user to press LT and RT at the same time, but that limitation affects XBox controllers as well.


texts: Why do tutorials use different approaches to OpenGL rendering?

texts:
http://www.sdltutorials.com/sdl-opengl-tutorial-basics

http://www.opengl-tutorial.org/beginners-tutorials/tutorial-2-the-first-triangle/

These two tutorials use completely different approaches to get nearly the same result. The first uses things like glBegin(GL_QUADS). The second one uses stuff like vertexBufferObjects, shaders based on GLEW. But the result is the same: you get basic shapes.

Why do these differences exist?

The first approach seems much easier to understand. What's the advantage of the complicated second approach?


texts: How can I check if a point(Vector3) is in Matrix4x4

texts:
I'm placing random objects in an imaginary cube in front of my target. I am using following code to do this:

var center = Vector3.zero;
center.z = (m_size.z / 2) + m_offset.z;
center.x += m_offset.x;
center.y += m_offset.y;
var mat = Matrix4x4.TRS(m_target.position, m_target.rotation, m_target.lossyScale);
Vector3 pos = center + new Vector3(Random.Range(-m_size.x / 2, m_size.x / 2), Random.Range(-m_size.y / 2, m_size.y / 2), Random.Range(-m_size.z / 2, m_size.z / 2));
pos = mat.MultiplyPoint(pos);
m_instantiatedObject.Add(Instantiate(m_object, pos, Quaternion.identity));

And it's working as expected. but now my problem is as my target moves, the previously placed objects may not be in this imaginary cube anymore. how can I check if my placed objects are in this imaginary cube and if they are not I can remove them?


texts:
I don't understand the lerp example in this code :

if(dot(WorldNormalVector(IN, o.Normal), _SnowDirection.xyz)>=lerp(1,-1,_Snow))
                o.Albedo = _SnowColor.rgb;
            else

(Snow is in the range 0..1)

The article says :
We then compare the dot value with a lerp - if our Snow level is 0 (no snow) this returns 1 and if the Snow level is 1 it will return -1 (the entire rock is covered).  It's quite normal to only vary the snow level between 0..0.5 when we use this shader so that we only have snow on surfaces that actually face the snow direction.

Why does it return 1 (with Snow at 0) and -1 (with Snow at 1) ?

(source: http://unitygems.com/noobs-guide-shaders-2/ )

Thanks


texts:
I'm currently working on a 2.5D space shooter and there will be a survival mode in the game. I'd like a few suggestions on how to tackle the enemy generation problem.
This is not procedural generation at all, it's more like a sequence generation. The characteristics the system needs to have are:

Increasing difficulty based on time
Ability to use enemy
patterns as input and not only single enemies
It has to be beatable, it's quite easy to make a wall of thousand of enemies :)

I'm not looking for a fully-optimized, ready to use algorithm, just some suggestions or links to papers or articles. I have found many resources on procedural generation, but nothing that can be applied to this game genre.
The game is 2.5D but the level will be generated as it was 2D, in addition it's not omnidirectional, it will scroll in only one way (this should make the task easier).


texts: Creating a seamless open world 2d game map

texts:
I'm creating an open world game similar to Pokemon.
Should I load the full map, or divide it into chunks and load only the the nearby area? I don't want my user to get to a point where it will transition between maps, like Pokemon.

If I were to split it into chunks, how could I load them seamlessly?


texts:
I'm trying to fake terrain blending by using an opacity mask on my road mesh to reveal the grass underneath. I'm currently multiplying some Perlin noise by a Rectangle node displaying my texture at 80% width which is giving me the following:

Obviously this doesn't look great for reasons that should be apparent. The blotches are unnaturally spaced and they abruptly end with a sharp line at the end of the texture. What I would like to do is generate noise that looks more along the lines of this:

Is there a way to apply some sort of gradient to my noise to achieve this? I know I can just use the texture itself but I would like to be able to adjust properties like the extent of the noise during runtime.


texts: How do I pool a bullet in libgdx ashley ECS approach?

texts: I'm having problem creating bullet pool in ashley ECS approach, because i'm using PooledEngine, everything is pooled. So I've done is I just use engine.createEntity(), engine.addEntity() and engine.removeEntity() to spawn a bullet. The problem is, the bullet is not behaving properly. In this memory-management bullet pool example, is working properly but not in ECS aproach. Can someone give me a brief explanation how do I pool a bullet in ashley ECS approach?


texts: How to convert an octree to a polygon mesh?

texts:
So if I have dynamic voxel terrain data stored in an octree
  representation what would be the best way to go about converting the
  octree to a polygon mesh which I can render with OpenGL?

A lot of the meshing algorithms I have found online assume that voxel data is stored in a 3D Array however for the level of detail I am using storing chunk data in a massive array isn't really an option (chunk size 64x1024x64 with each block roughly 4bytes) split into several 64x64x64 small octrees, I could make the chunk size smaller but then that means more draw calls etc.

Basic searches on google for 'meshing an octree' seem to bring up lots of research on doing the inverse (converting from meshes to SVOs).

The problem with using these algorithms on the octree instead of the array is that the octree has a much slower access time not to mention the time cost of copying the data from the octree representation.

I have considered the possibility of converting to an RLE or spatial hashing system but these two systems both have their drawbacks especially since I plan to use the same octree when I come to implement collision detection.

I would guess that it would be best to traverse down the tree rather than iterating over it like  an array, but some more ideas about how I could optimise this would be appreciated.


texts:
TL;DR I need to switch from a vertex array passed to the pixel shader with a real vertex shader approach.

In my prototype, the terrain is procedurally generated and I have the following result:

The terrain vertices are passed directly to the pixel shader through an array:

//Number of vertices in terrain array
static const int verticesCount = 20;

//The vertices array, in pixel coordinates
float2 terrain[verticesCount];

//A fixed distance between neighbor vertices
float fixedDistance;

float4 PixelShaderFunction(float2 pixelCoords : VPOS,
                           float2 textureCoords :TEXCOORD0) : COLOR0
{
    float4 color = tex2D(s0, textureCoords);
    int i = pixelCoords.x / fixedDistance;
    float delta = (pixelCoords.x - terrain[i].x)/(terrain[i+1].x - terrain[i].x);
    if(smoothInterpolate(terrain[i].y, terrain[i+1].y, delta) >= pixelCoords.y)
    {
        color.rgba = 0;
    }
    return color;
}

As you can see I just interpolate between the vertices and mask the texture to the terrain.

Now I need a different approach because I'm using a view matrix for the camera and it does not affect these vertices that do not go through the vertex shader, how can I replace the terrain array with a vertex shader to get a similar result?

All suggestions are welcome!


texts:
So I have a Matrix of NxM. At a given position (for ex. [2][5]) I have a value which represents a color. If there is nothing at that point the value is -1. What I need to do is after I add a new point, to check all his neighbours with the same color value and if there are more than 2, set them all to -1.

If what I said doesn't make sense what I'm trying to do is an alghoritm which I use to destroy all the same color bubbles from my screen, where the bubbles are memorized in a matrix where -1 means no bubble and {0,1,2,...} represent that there is a bubble with a specific color.

This is what I tried and failed:

public class Testing {

    static private int[][] gameMatrix=
        {{3, 3, 4, 1, 1, 2, 2, 2, 0, 0},
        {1, 4, 1, 4, 2, 2, 1, 3, 0, 0},
        {2, 2, 4, 4, 3, 1, 2, 4, 0, 0},
        {0, 1, 2, 3, 4, 1, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        };

    static int Rows=6;
    static int Cols=10;
    static int count;
    static boolean[][] visited=new boolean[15][15];
    static int NOCOLOR = -1;
    static int color = 1;

    public static void dfs(int r, int c, int color, boolean set)
    {
        for(int dr = -1; dr <= 1; dr++)
            for(int dc = -1; dc <= 1; dc++)
                if(!(dr == 0 && dc == 0) && ok(r+dr, c+dc))
                {
                    int nr = r+dr;
                    int nc = c+dc;

                    // if it is the same color and we haven't visited this location before
                    if(gameMatrix[nr][nc] == color && !visited[nr][nc])
                    {
                        visited[nr][nc] = true;
                        count++;

                        dfs(nr, nc, color, set);

                        if(set)
                        {
                            gameMatrix[nr][nc] = NOCOLOR;
                        }
                    }
                }
    }

    static boolean ok(int r, int c)
    {
        return r >= 0 && r < Rows && c >= 0 && c < Cols;
    }

    static void showMatrix(){
        for(int i = 0; i < gameMatrix.length; i++) {
            System.out.print("[");
            for(int j = 0; j < gameMatrix[0].length; j++) {
                System.out.print(" " + gameMatrix[i][j]);
            }
            System.out.println(" ]");
        }
        System.out.println();

    }

    static void putValue(int value,int row,int col){
        gameMatrix[row][col]=value;
    }

    public static void main(String[] args){
        System.out.println("Initial Matrix:");
        putValue(1, 4, 1);
        putValue(1, 5, 1);
        showMatrix();

        for(int n = 0; n < 15; n++)
            for(int m = 0; m < 15; m++)
                visited[n][m] = false;

        //reset count
        count = 0;
        //dfs(bubbles.get(i).getRow(), bubbles.get(i).getCol(), color, false);

        // get the contiguous count
        dfs(5,1,color,false);
        //if there are more than 2 set the color to NOCOLOR
        for(int n = 0; n < 15; n++)
            for(int m = 0; m < 15; m++)
                visited[n][m] = false;
        if(count > 2)
        {
            //dfs(bubbles.get(i).getRow(), bubbles.get(i).getCol(), color, true);
            dfs(5,1,color,true);
        }

        System.out.println("Matrix after dfs:");
        showMatrix();
    }

}


texts: How can I search for players in the same wifi in Unity?

texts:
I am creating a game in Unity and I would like to create an ability for players to join the game that others have created on the same wifi. I would like it to be as effortless as possible(e.g. players don't have to find out their wifi, etc). The game is cross-platform - you could have one player on PC, other on Android device, etc.

Now I know that there is a game that has similar mechanism to what I would like to achieve: SpaceTeam. Basically you select whether you use BT or wifi, and wait for other players to join.

How can I do this in Unity, or something similar that satisfies my needs?


texts:
Not that long ago, Nintendo opened their developer program for access by anyone who registers a Nintendo Developer account, giving equal access to indie and commercial developers. Or, at least thats what the linked page says.

The tools page lists Unity and a HTML5 framework for game development, as well as the "Nintendo Dev Interface (NDI)." Since I am not really interested in developing using Unity (or HTML5, for that matter) I want to know what the NDI contains, at least in general terms.

(I don't doubt that at least some of that information is covered by an NDA, but I'd like to know as much as possible, since I can't register for a while)

I'm especially interested in what sort of compiler/languages are supported, what graphics APIs (and/or abstraction layers, like SDL) are allowed and how play testing works (some sort of compatability layer? Nintendo sanctioned emulation?).