texts: Why is the SFML shape not being displayed when I make it a member of the Game class instead of a local function variable?

texts:
I created a window successfully in SFML using a Game class which hold all of the key components of the game. I then tried to start rendering shapes on the screen. When I first rendered the shapes, I was creating local copies inside of the render function. Of course, that doesn't allow me to do much and it isn't good organization of code, so I moved the main shape of the game I have in mind to the Game class. Now the shape doesn't show up at all. The application doesn't crash but it just doesn't show the shape. I feel like this might have something to do with the scope of the shape, but I just can't make sense of it. I looked at "The white square problem" on SFMLs site but I do not feel like this relates since the shape is a member of the class (which I thought meant it shouldn't go out of scope until the instance of the class does). I'm using g++ and am on a iMac running El Capitan if that helps any. Any help at all is greatly appreciated! Please help me understand this if you can!

p.s. Feel free to comment on any part of my code that isn't even directly related to the question but rather should just be improved.

Main.cpp

#include "Game.hpp"

int main(int argc, char** argv)
{
    Game game;

    game.setup();

    while (game.isRunning())
    {
        game.events();
        game.update();
        game.render();
    }

    game.cleanup();

    return 0;
}

Game.hpp

#ifndef GAME_H
#define GAME_H

#include <SFML/Graphics.hpp>

class Game
{

private:
    enum GameState
    {
        GAME_STATE_RUNNING,
        GAME_STATE_CLOSING
    };

    sf::RenderWindow window;
    GameState state;
    sf::CircleShape leader;

public:
    Game();
    ~Game();

    void setup();
    bool isRunning();
    void events();
    void update();
    void render();
    void cleanup();

};

#endif

Game.cpp

#include <SFML/Graphics.hpp>

#include "Game.hpp"

Game::Game()
{
}

Game::~Game()
{
}

void Game::setup()
{
    this->window.create(sf::VideoMode(1000, 750), "Follo");

    this->leader.setFillColor(sf::Color::Black);
    this->leader.setPosition(100, 100);

    this->state = GAME_STATE_RUNNING;
}

void Game::events()
{
    sf::Event event;

    while (this->window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
        {
            this->state = GAME_STATE_CLOSING;
        }
    }
}

bool Game::isRunning()
{
    return this->state != GAME_STATE_CLOSING;
}

void Game::update()
{
}

void Game::render()
{
    this->window.clear(sf::Color(203, 209, 219, 255));
    this->window.draw(this->leader);
    this->window.display();
}

void Game::cleanup()
{
}

Makefile

COMPILE         = g++ -c
LINK            = g++ -o
FLAGS           = -g -Wall -O2
O_FILES         = Main.o Game.o
LIB_PATH        = /usr/local/lib
INCLUDE_PATH    = /usr/local/include
LIBS            = -lsfml-graphics -lsfml-window -lsfml-system
EXE_NAME        = Follo

program: build
    ./$(EXE_NAME)

build: $(O_FILES)
    $(LINK) $(EXE_NAME) $(O_FILES) -L$(LIB_PATH) $(LIBS)

Main.o: Main.cpp
    $(COMPILE) $(FLAGS) Main.cpp

Game.o: Game.cpp Game.hpp
    $(COMPILE) $(FLAGS) Game.cpp


texts: How to synchronise the acceleration, velocity and position of the monsters on the server with the players?

texts:
I'm building an MMO using Node.js, and there are monsters roaming around. I can make them move around on the server using vector variables acceleration, velocity and position.

acceleration = steeringForce / mass;

velocity += acceleration * dTime;

position += velocity * dTime;

Right now I just send the positions over, and tell the players these are the "target positions" of the monsters, and let the monsters move towards the target positions on the client with a speed dependant on the distance of the target position. It works but looks rather strange.

How do I synchronise these properly with the players without looking funny to them, taking into account the server lag?

The problem is that I don't know how to make use of the correct acceleration/velocity values here; right now they just move directly in a straight line to the target position instead of accelerating/braking there properly. How can I implement such behaviour?


texts: how get collision callback of two specific objects using bullet physics?

texts:
I have got problem implementing collision callback into my project. I would like to have detection between two specific objects. I have got normall collision but I want one object to stop or change color or whatever when colides with another. I wrote code from bullet wiki:

int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds();
    for (int i=0;i<numManifolds;i++)
    {
        btPersistentManifold* contactManifold =  dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
        btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0());
        btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1());

        int numContacts = contactManifold->getNumContacts();
        for (int j=0;j<numContacts;j++)
        {
            btManifoldPoint& pt = contactManifold->getContactPoint(j);
            if (pt.getDistance()<0.f)
            {
                const btVector3& ptA = pt.getPositionWorldOnA();
                const btVector3& ptB = pt.getPositionWorldOnB();
                const btVector3& normalOnB = pt.m_normalWorldOnB;
                bool x = (ContactProcessedCallback)(pt,fallRigidBody,earthRigidBody);
                if(x)
                    printf("collision\n");
            }
        }
    }

where fallRigidBody is a dynamic body - a sphere and earthRigiBody is static body - StaticPlaneShape and sphere isn't touching earthRigidBody all the time. I have got also other objects that are colliding with sphere and it works fine. But the program detects collision all the time. It doesn't matter if the objects are or aren't colliding.

I have also added after declarations of rigid body:

    earthRigidBody->setCollisionFlags(earthRigidBody->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
fallRigidBody->setCollisionFlags(fallRigidBody->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);

So can someone tell me what I am doing wrong? Maybe it is something simple?


texts: Loading tile maps from files on the fly in Crafty JS

texts:
I'm fairly new to Crafty and have been having problems loading large world maps.

So i have a world split up into multiple js files. They are represented by two arrays of tiles: one for background (which grass sprite to use) and one for detail (which cliff to use). When i start crafty I load the 3x3 surrounding files and render them like so:

for(var i = 0; i < Game.map_grid.map_entities.length; i ++){
    if(Game.map_grid.map_entities.hasOwnProperty(i))
      Game.map_grid.map_entities[i].keep = false;
}

//render background terrain
for (var i = 0; i < view_map["background"].length; i++) {

    var tile_object = view_map["background"][i];
    var tile = tile_object["type"];
    var x = tile_object["x"] - view_map["xoffset"];
    var y = tile_object["y"] - view_map["yoffset"];

    if(Game.map_grid.map_entities.length && (tile+"_"+x+"_"+y) in this.map_grid.map_entities)
    {
        tile_ent.keep = true;
        continue;
    }

    var tile_ent = Crafty.e("Actor", "spr_"+tile);
    tile_ent.at(x, y);
    tile_ent.z = 0;
    tile_ent.keep = true;
    this.map_grid.map_entities[tile+"_"+x+"_"+y] = tile_ent;
}

//render background terrain
for (var i = 0; i < view_map["detail"].length; i++) {

    var tile_object = view_map["detail"][i];
    var tile = tile_object["type"];
    var x = tile_object["x"] - view_map["xoffset"];
    var y = tile_object["y"] - view_map["yoffset"];

    if(Game.map_grid.map_entities.length &&
     (tile+"_"+x+"_"+y) in this.map_grid.map_entities)
    {
        tile_ent.keep = true;
        continue;
    }

    var tile_ent = Crafty.e("Actor", "Solid", "spr_"+tile);
    tile_ent.at(x, y);
    tile_ent.shift(tile_object["xoffset"], tile_object["yoffset"]);
    tile_ent.z = 1;
    tile_ent.keep = true;
    this.map_grid.map_entities[tile+"_"+x+"_"+y] = tile_ent;

}

for(var i = 0; i < Game.map_grid.map_entities.length; i ++){

    //Check if the entities need to be moved

    if(Game.map_grid.map_entities.hasOwnProperty(i) &&
       !Game.map_grid.map_entities[i].keep)
    {
        Game.map_grid.map_entities[i].destroy();
        delete Game.map_grid.map_entities[i];
    }
}

I also use the view port to track the player, showing only a portion of the map.

When the player reaches edge of the 3x3 loaded map, I need to request new maps and render them instead. What i have been using is the "Moved" event to check where the player is near the edge. Once that triggers, all of the original tile entities are .destroyed()'ed (i know i can destroy only the ones i need). The above code is ran again to draw the new map and the player is shifted to keep consistent with the new 3x3 coordinates.

The problem is: it looks like the maps are loaded and rendered, but the destroyed ones don't seem to be refreshed and i think are still there. But also the player isn't being redrawn properly, the Moved events are still triggered but the animation isn't updated

My main question is: Is there a better approach to this?


texts: How do they made Pokémon games so flawlessly balanced?

texts: I find it hard to believe how well balanced the Pokémon games are. Not just within the games, where you'll find amazing balance from the very beginning to the very end, but, surprisingly, even when things get more competitive. If you have ever played the simulators that are available, you'll know what I'm talking about www.smogon.com. There are thousands of unique Pokémon characters, moves, traits and items. Yet, if you try to find a single broken strategy, You can't. And if you do find something obscure that could give you a good advantage, you'll realize it's impossible. The emerging competitive scenario is one of the most amazing strategy games I've ever seem, and it's not even a feature of the Pokémon games!


texts:
I have been trying to learn about GUI frontends for Nethack, but I have been unable to determine how do they get the game information (map, inventory, player info, enemy locations, etc) from Nethack? As in, is there some API that allows these frontends to query these information? If so, how are they used?
I have looked up everywhere but unable to find any documentation that describes how to do so.


texts: Unity Editor equivalent of Playmode Start()

texts:
I am attempting to draw gizmos for easy debug in the editor. The gizmos code uses an array that gets populated during the start function. The array only needs to be populated once and may cause issues if its modified during runtime. As such, I cant call the method to populate the array in the OnDrawGizmos() method.

I could possibly use a singleton populate the array but that would require many other things to be changed as well. I am looking for an equivalent to Start() for when it is in Editor Mode. Is there a method in editor mode that execute once or an attribute for the Start() method to execute in editor mode?


texts: Finding Closest of 8 Possible Angles to Theta Value

texts:
I'm working on creating a gesture recognition system, and I saw one simple implementation that isn't as accurate, but is really easy to implement. The idea is that you have a unit circle with the 8 significant angles (0, 45, 90, 135, 180, etc) and you map those angles to a value of 1-8. So 45 would be 2, 180 would be 5, etc. Then you just use the Levenshtein distance algorithm to find the closest matching gesture.

I have a prototype that is "almost" working, but I'm having some trouble getting the math functions to play nicely with my algorithm. Right now, I have a list of points representing segments of a defined size that make up the gesture. I iterate over these points and get the theta value of the segment like so:

start = points[i]
end = points[i + 1]
theta = math.atan2((p2[1] - p1[1]), (p2[0] - p1[0]))
theta = ((theta + (math.pi * 2)) % (math.pi * 2))

The math.pi correction is so that I'll have all positive radian values. Makes it a lot easier to compare them. I also have a list containing the radian equivalent values of [0, 45, 90, 135, 180, 225, 270, 315, 360]. I iterate over the segments and compare the theta value to each of those 8 directions (360 is a redundancy so that I can compare values greater than 315 to 0). I use the index of the direction + 1 to get my mapped value.

So if I have a drawing of a box like so:

Then according to the algorithm, I should get the values "1357" to indicate the directions being 0, 90, 180, and 270 degrees in change.

However, something seems to be off about the way I calculate my theta values, or the way I compare them, because for that drawing, I get "1753" indicating that it's flipping the theta values for the second and third lines (the vertical ones). Here is how I'm comparing the points:

for i in range(len(points) - 1):
    p1 = points[i]
    p2 = points[i + 1]
    theta = math.atan2((p2[1] - p1[1]), (p2[0] - p1[0]))
    theta = ((theta + TWO_PI) % TWO_PI)
    closest = 0
    cDiff = TWO_PI
    for i in range(len(DIRECTIONS)):
        direction = DIRECTIONS[i]
        diff = abs(direction - theta)
        if diff < cDiff:
            cDiff = diff
            closest = I
    if closest == (len(DIRECTIONS) - 1):
        dir.append(1)
    else:
        dir.append(closest + 1)

So my theta values seem to be increasing clockwise, rather than counter-clockwise, so for the following angle:

...I would expect the theta value to be (pi / 4), but instead, it seems to be (7pi / 4).

Can anyone spot a flaw in my logic? This same math works in my game written in Java. Are Python's math functions different somehow?

Edit: Added a diagram to explain the encoded gesture movement values.


texts: How do I stop rotation after colliding with a specific object? I want player to stop rotating when they collide with walls. I am using Unity, with C#.


texts: How can you easily determine the textureRect for tiled maps in SFML 2.0?

texts:
I'm working on creating a 2d map prototype, and I've come across the rendering bit of it. I have a tilesheet with tiles, each tile is 30x30 pixels, and there's a 1px border to delimitate them.

In SFML the usual method of drawing a part of a tilesheet is declaring an IntRect with the rectangle coordinates then calling the setTextureRectangle() method to a sprite.

In a small game it would work, but I have well over 45 tiles and adding more every day, I can't declare 45 intRects for every material, the map is not optimized yet, it would get even worse if I would have to call the setTextureRect() method, aside from declaring 45 rectangleInts.

How could I simplify this task? All I need is a very simple and flexible solution for extracting a region of the tilesheet.

Basically I have a Tile class. I create multiple instances of tiles (vectors) and each tile has a position and a material. I parse a map file and as I parse it I set the materials of the map according to the parsed map file, and all I need to do is render.

Basically I need to do something like this:

switch(tile.getMaterial())
{
   case GRASS:
       material_sprite.setTextureRect(something);
       window.draw(material_sprite);
       break;

   case WATER:
       material_sprite.setTextureRect(something);
       window.draw(material_sprite);
       break;

  // handle more cases
}


texts:
I'm working on a top down Strategy/RPG/Tower Defense XNA Game for Windows, and I'm running into an issue while scaling.

My display mode is 1680 X 1050, and that is what I'm setting the PreferredBackBuffer width and height to.

What I'm finding is that when I use my camera object to zoom in and out (changing the scale on a matrix that is passed to the SpriteBatch.Begin method, it changes the scale of my sprites... but I'm still confined to the BackBuffer (0,0,1680,1050)...

Can I use something like a RenderTarget to extend the actual area that is accessible when zooming/panning across the "map"?

I'm looking at making it something like 5000 X 3125...

Any thoughts/examples of how I should approach this?

I've added a video of what I'm experiencing... http://www.youtube.com/watch?v=jIiAeXbAnec

For the record I have also posted this question on Stack Exchange - Stack Overflow


texts:
I want to have an object follow around my mouse on the screen in OpenGL. (I am also using GLEW, GLFW, and GLM). The best idea I've come up with is:

Get the coordinates within the window with glfwGetCursorPos.

The window was created with

window = glfwCreateWindow( 1024, 768, "Test", NULL, NULL);

and the code to get coordinates is

double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);

Next, I use GLM unproject, to get the coordinates in "object space"

glm::vec4 viewport = glm::vec4(0.0f, 0.0f, 1024.0f, 768.0f);
glm::vec3 pos = glm::vec3(xpos, ypos, 0.0f);
glm::vec3 un = glm::unProject(pos, View*Model, Projection, viewport);

There are two potential problems I can already see. The viewport is fine, as the initial x,y, coordinates of the lower left are indeed 0,0, and it's indeed a 1024*768 window. However, the position vector I create doesn't seem right. The Z coordinate should probably not be zero. However, glfwGetCursorPos returns 2D coordinates, and I don't know how to go from there to the 3D window coordinates, especially since I am not sure what the 3rd dimension of the window coordinates even means (since computer screens are 2D). Then, I am not sure if I am using unproject correctly. Assume the View, Model, Projection matrices are all OK. If I passed in the correct position vector in Window coordinates, does the unproject call give me the coordinates in Object coordinates? I think it does, but the documentation is not clear.

Finally, to each vertex of the object I want to follow the mouse around, I just increment the x coordinate by un[0], the y coordinate by -un[1], and the z coordinate by un[2]. However, since my position vector that is being unprojected is likely wrong, this is not giving good results; the object does move as my mouse moves, but it is offset quite a bit (i.e. moving the mouse a lot doesn't move the object that much, and the z coordinate is very large). I actually found that the z coordinate un[2] is always the same value no matter where my mouse is, probably because the position vector I pass into unproject always has a value of 0.0 for z.

Edit: The (incorrectly) unprojected x-values range from about -0.552 to 0.552, and the y-values from about -0.411 to 0.411.


texts: Constructing a building in the "Past" scene, and finding a different version of it in the "Future" scene

texts:
I am trying to create a game where one scene would be the "Past" and one scene would be the "Future". The player can travel through a portal to move between the past and future scenes.
In the past scene, the player makes a wooden house and in the future scene it will be turned into something else.
There can be multiple instances of these buildings in different places in the scene.
So far, I've tried...

Using DontDestroyOnLoad to carry the object through from the past to future when loading between scenes.

Using singletons to avoid duplicating the object multiple times when loading back and forth.
But that has a problem: using singletons causes restricts me to just one instance of the building per scene, and I want to have several.

The reason why I wouldn't want to unload the old object when the scene unloads is because I wanted the player to be able to build in any area available within the scene. Something like the Fallout 4 building mechanics, where you can build in certain areas and keep those buildings, but I want it to become a different prefab in the future scene.
How can I implement a feature like this?


texts: Best way to go about collision between rectangle and bool array containing pixel data?

texts:
Basically, if I have an array along the lines of

    bool[] collision;

Filled with a value for each pixel in the sprite I am checking collision against (pixel 1 = true, pixel 2 = false etc), how do I use it to check collision between the player and the texture?

      protected void GetCollisionData()
    {
    // Declare an array to hold the pixel data
        uint[] pixelLevelData = new uint[textureLevel.Width * textureLevel.Height];
        // Populate the array
        textureLevel.GetData(pixelLevelData, 0, textureLevel.Width * textureLevel.Height);

        for (int x = 0; x < textureLevel.Width; x++)
        {
            for (int y = 0; y < textureLevel.Height; y++)
            {
                 if (x < textureLevel.Width && x > 0 && y > 0 && y < textureLevel.Height)
                {
                    //If it's black, make a note that collision will happen
                    if (pixelLevelData[(x + y * textureLevel.Width)] == 4278190080)
                    {
                        collision[x + y * textureLevel.Width] = true;
                        debug = 9;
                    }
                    //else it's either something black already covers or transparent; no collision necessary
                    else
                        collision[x + y * textureLevel.Width] = false;
                }
            }
        }
    }

This is the relevant part that covers how I got my array of bools. How to I check collision between the set of bools and a normal rectangle?


texts: Appropriate use for prefabs in Unity in a coordinate based game?

texts:
I am wondering how exactly to use prefabs in Unity for my discretely coordinate-based game. Should they only be for gameObjects that are exactly the same? Or can they have small variations?

Example: a treasure chest is interactable and it holds items, so I would make it an empty gameObject, add an interactable component and then an itemContainer component and then drag and drop it into my prefabs folder and delete the instance in the scene.

But the question remains, if I make this treasure chest a prefab, how do I edit the itemContainer component of this treasure chest? Moreover, how would I serialize it for later use, and organize my data? Would I have to use external data files and reconstruct the ItemContainerComponent, just for a treasure chest? That sounds like a lot of work.

If I edit the itemContainer component as a prefab, then all treasure chests will have the same items. Obviously this is not feasible.

Do I drag my treasureChest prefab from the prefabs folder and then simply drop it in the game? That's how most people use it, right?

I would prefer not to just drag and drop the prefabs, because I want a more industrialized approach, and I do want some way of saving what is in each treasure chest. I can't for the life of me figure out a good way. Help appreciated!

EDIT: I see the link provided that marks this as a possible duplicate. However, none of the answers in that link are clear enough to be useful to me, e.g., the "factory." It would be nice if someone could explain the factory idea in more concrete terms.


texts: How to make the background tilemap in Unity3D have a "far away fog effect" filter in a sidescroller game?

texts:
I would like my background made of the same tiles as my foreground but with a filter which makes it appear further away from the camera.

Making the objects smaller is easy, I just have to decrease the scale of the tilemap.

But I also want it to have a "fog effect". So for example if the sky is blue then the tiles will be as blueish as far they are from the camera.

How could I implement this?

Example for fog effect:


texts: Best way to notify a user on Facebook that it's their turn to act

texts:
I'm creating a turn-based game that I'd like to integrate into Facebook.  Players may not necessarily be playing in real time so having a way for them to know when it's their turn is desirable.

I was initially thinking facebook notifications, but it appears that has been deprecated:
https://stackoverflow.com/questions/4619164/how-to-send-a-facebook-notification-through-their-api

The alternatives don't sound terribly pleasant (writing on their wall, or having the player that just finished their turn send a request)

Are there any better alternatives?


texts: Client/Server best way of telling client which player it is

texts:
I'm making a client/server, everything works grand its very simple, a simple login system, ID, empty variable and the X and Y positions of the player.

Should my server tell my client who it is? and if so what kind of relationship would a client/server usually have?

My server currently stores each connection so I can communicate with one, or all clients - is this the right type of architecture?


texts: Why don't objects far away from the camera experience floating point issues?

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


texts: Different implementation use case of component based approach

texts:
Inspired by this question I made a small demo for an enemy that has a HP component. Basically there is a main enemy script and a HP script that considers you died on collision and lets the enemy script know on different ways. I could think of three different ways how to let the main script know that you died and included a basic implementation of each. The focus is more on how to let the main script know that you died.
Broadcast
public class EnemyBroadcast: MonoBehaviour
{
    void HandleDeath()
    {
        Debug.Log("Died via broadcast");
    }
}

public class HPBroadcast: MonoBehaviour
{
    private void OnCollisionEnter2D(Collision2D other)
    {
        BroadcastMessage("HandleDeath");
    }
}

Pro: This seems to be the shortest code.
Con: IDE can't see the call and you need to know the broadcastevent
Interface
public interface IDeathHandler
{
    void HandleDeath();
}

public class EnemyInterface: MonoBehaviour, IDeathHandler
{
    public void HandleDeath()
    {
        Debug.Log("Death via Interface");
    }
}

public class HPInterface: MonoBehaviour
{
    private void OnCollisionEnter2D(Collision2D other)
    {
        GetComponent<IDeathHandler>().HandleDeath();
    }
}

Pro: Not possible to forget to implement methods
Con: Possible overhead of methods, reusibility
Delegate
public class EnemyDelegate: MonoBehaviour
{
    void Start()
    {
        GetComponent<HPDelegate>().handleDeathDelegate = HandleDeath;
    }
    void HandleDeath()
    {
        Debug.Log("Died via delegate");
    }
}

public class HPDelegate: MonoBehaviour
{
    public delegate void voidDelegate();
    public voidDelegate handleDeathDelegate;
    private void OnCollisionEnter2D(Collision2D other)
    {
        handleDeathDelegate();
    }
}

Pro: Outside objects are able to observe changes/ events
Con: more complicated to setup/ longer code
Now the question is, what other ways are there in a component based approach, are there more pro/ con for each approach and when is which kind of implementation prefered over the others?


texts:
I'm having rendering issues in Tiled with a border tile I'm applying to shapes.

In Tiled:

In game:

I'm using Tile Flipping to reduce work. I thought this may be the issue, so I tested out a few tiles by themselves:

Tiled:

In game: They render as expected

What may be the cause of this?

My game engine is Melon JS


texts:
I'm wondering how I can incorporate reusable tilemap segments in my workflow.

For example: I construct a room out of my tile palette, and I want to reuse this room in multiple places.

Is there some way to "prefab" a section of a tilemap? I haven't found such a thing.

Or perhaps I should just prefab the whole tilemap, and use multiple tilemap objects within one grid? Won't that introduce significant overhead?

What if I want to prefab a section of a tilemap with some additional, non-tilemap objects?


texts: How do I make my character stop going left in Unity?

texts:
I have this code and my character can go left, right and jump. I don't want the character going left, so how can I remove that. (I'm very new with coding)

public class Player: MonoBehaviour {

    public float maxspeed = 10f;
    bool facingRight = true;

    Animator anim;

    bool grounded = false;
    public Transform groundCheck;
    float groundRadius = 0.2f;
    public LayerMask whatIsGround;
    public float jumpFocre = 500f;

    bool doubleJump = false;

    void Start ()
    {
        anim = GetComponent<Animator> ();
    }

    void FixedUpdate () {
        grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
        anim.SetBool ("Ground", grounded);

        if (grounded)
            doubleJump = false;

        float move = Input.GetAxis ("Horizontal");
        anim.SetFloat ("Speed", Mathf.Abs (move));

        GetComponent<Rigidbody2D>().velocity = new Vector2(move * maxspeed, GetComponent<Rigidbody2D>().velocity.y);
    }

    void Update()
    {
        if((grounded || !doubleJump) && Input.GetKeyDown ("up"))
        {
            anim.SetBool("Ground", false);
            GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpFocre));

            if(!doubleJump && !grounded)
            doubleJump = true;
        }
    }

    void Flip()
    {
        facingRight = !facingRight;
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }
}


texts: Game Loop: Should resources be initialized in the game loop or in the respective classes? (both?)

texts:
For example, lets say we have an enemy class in my Android game project. I am initializing the enemy bitmap to be used with certain sprites in my game loops init. I am then calling the respective classes init, which is passed this loaded bitmap.

What is the process associated with initializing resources and classes in the game loop?

If I am totally off course just point me in the right direction.

Thanks! :D


texts: Can I use the idea of grappling hook and wingsuit from just cause 3 and use it in my game?

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


texts: Why does my code dividing a 2D array into chunks fail?

texts:
I have a 2D-Array representing my world. I want to divide this huge thing into smaller chunks to make collision detection easier.

I have a Chunk class that consists only of another 2D Array with a specific width and height and I want to iterate through the world, create new Chunks and add them to a list (or maybe a Map with Coordinates as the key; we'll see about that).

world = new World(8192, 1024);

Integer[][] chunkArray;

for(int a = 0; a < map.getHeight() / Chunk.chunkHeight; a++)
{
    for(int b = 0; b < map.getWidth() / Chunk.chunkWidth; b++)
    {
        Chunk chunk = new Chunk();
        chunkArray = new Integer[Chunk.chunkWidth][Chunk.chunkHeight];

        for(int x = Chunk.chunkHeight*a; x < Chunk.chunkHeight*(a+1); x++)
        {
            for(int y = Chunk.chunkWidth*b; y < Chunk.chunkWidth*(b+1); y++)
            {
                // Yes, the tileMap actually is [height][width] I'll have
                // to fix that somewhere down the line -.-
                chunkArray[y][x] = map.getTileMap()[x*a][y*b];
                // TODO:Attach to chunk
            }
        }

        chunkList.add(chunk);
    }
}

System.out.println(chunkList.size());

The two outer loops get a new chunk in a specific row and column. I do that by dividing the overall size of the map by the chunkSize.

The inner loops then fill a new chunkArray and attach it to the chunk. But somehow my maths is broken here.

Let's assume the chunkHeight = chunkWidth = 64.

For the first Array I want to start at [0][0] and go until [63][63]. For the next I want to start at [64][64] and go until [127][127] and so on. But I get an out of bounds exception and can't figure out why.

Any help appreciated!

Actually I think I know where the problem lies:

chunkArray[y][x] can't work, because y goes from 0-63 just in the first iteration. Afterwards it goes from 64-127, so sure it is out of bounds.

Still no nice solution though :/

EDIT:

if(y < Chunk.chunkWidth && x < Chunk.chunkHeight)
    chunkArray[y][x] = map.getTileMap()[y][x];

This works for the first iteration... now I need to get the commonly accepted formula.


texts: Adding local wireles multiplayer mode to my Android game

texts:
I've created a little game on Android. Now, I want to add a multiplayer mode which works with bluetooth or WiFi, so you can play together with other "smartphones" in your neighborhood . Which is the best way to offer a fast, good working mulitplayer mode that supports so many devices as possible? I heard about Alljoyn, but Im not quite sure if it fits my needs. Which way do you recommend?

regards Lisa


texts: Changes to one Unity trail renderer causes all of them to flicker

texts:
I'm using Unity. So I have a prefab, and this prefab has a trail renderer component attached to it.

However, for some of the game objects I want to stop the trailer renderer at certain points in time. But doing so seems to make all of the trail renderers blink; flash off and on. I've tried changing time, disabling the component, and using Clear() while hiding the trail renderer behind the background before needing to be used. All of these makes all trail renderers flicker on the frame the change happens.

I believe providing the code won't be helpful, it's just if(x) disable-action, if(y) enable_action. What can I do?


texts: How to calculate random new position base on original position on map

texts:
I am making a 2D game with HTML5 Canvas. The game has several shapes and I want them to move all over the map randomly.

  However, if I just give them a constant angle to follow, they will
  all end up in a corner after a certain amount of time.
  Also, I am building this game with client-server so I don't want to
  send a lot of data. For example, I don't want to constantly update
  the angle on the server side and send it to the client.

That's why I want to generate a random position base on the shape's position on the big map.

For example, it's angle of movement will be tangent of it's (x,y). (It obviously won't work because it will get stuck on the sides of the map).

So what's a good way of generating the new coordinates base on it's current one?


texts: Matrix operations to flip 3d models front to back, without changing position

texts:
Multiple 3D objects look to be in the correct screen position, and I can move around them and this continues to be true, but each one looks like it is flipped back to front (I can see the backside of the object as if the camera were on the other side of it).

Any clues to why this may be happening in addition to correcting it would be welcome also- I'm getting a transform matrix from one api what is documented as OpenGL 4x4 matrix format, but my underlying api (bgfx) is wrapping opengl so may be assuming another format.  I can probably go get the transform in different format, but now I'd really like to know how to correct this also if there was no option but to start with the opengl matrix.


texts: How to flip 2d skinned quadruped character?

texts:
just would like to know is flipping 2d skinned character with one of scale axis good way for left or right movement(flipping direction and animation)?
Normal direction would change.(UPDATED)
for example i have a 2d skinned dog, and i wanna dog move left when i press left with same animation as right direction.
or is there any better way?
Thanks.


texts: Extra sprite spawning when the enemies are redrawn SFML

texts:
I am making a game in sfml and at the moment when all of the enemies die. They are set to respawn however when this is happening they are respawning with one extra sprite than before.

The code for loading in the sprites is

unsigned int orcNumber = 5;
for (int i = 0; i < orcNumber; i++)
{
    SpriteVector.push_back(ogreSprite);
    SpriteVector[i].setPosition(spawnPointX[i], spawnPointY[i]);
}

The code for removing the enemies if they are offscreen or shot is similar to below using erase.

for (unsigned j = 0; j < SpriteVector.size(); j++)
{
    if (this->SpriteVector[j].getPosition().x < 0 - 80 )
    {
        //this succesfully removes the object from the vector
        SpriteVector.erase(SpriteVector.begin() + j);
        std::cout << "Container size..." << SpriteVector.size() << "\n";
    }
}

The statement for redrawing them is:

unsigned int orcNumberRespawn = 5;
if (SpriteVector.size() <= 1)
{
    for (int i = 0; i < orcNumberRespawn; i++)
    {
        SpriteVector.push_back(ogreSprite);
        SpriteVector[i].setPosition(spawnPointX[i], spawnPointY[i]);
    }
}

window.draw(SpriteVector[i]);

Can anyone identify why when the sprites need to be redrawn it draws with + 1 sprite everytime?


texts:
I am writing a shader to achieve a laser show effect example.
For now I am just focusing on the lines. One line ist represented as one triangle.
When I save my shadercode, unity gets inactive and I can see in the task manager that the shader compiler has 30% cpu -> is compiling. But this takes forever, and when I restart unity, it isn't able to load the shader from the assets.
I found out that this doesn't happen when I comment the line:

const int TRI_STRIP[TAM] = tmpTriStrip;

Obviously I then get an error that TRI_STRIP is undefined, but the shadercompiler did its work and Unity is still running.
Then I put the line back into the code and the above desribed behaviour appears.
Thanks for any tipps and advices.

Here is the complete geometryshader code:

    void myGeometryShader(point gIn vert[1], inout TriangleStream<v2f> triStream)
{
    float f = _PointSize / 20.0f * sin(_Time * _Speed); //half size

    float4 vctmp[TAM];

    int i;
    float y;
    for (i = 0; i < TAM; i += 3) {

        y = sin(_Time * _Speed + _SinValue) * _MovHeight + _HeightOffset;
        vctmp[i] = float4(0.0f, 0.0f, 0.0f, 0.0f);
        vctmp[i + 1] = float4(_Distance, y, i / _MarginFactor - _EndWidth / 2.0f, 0.0f);
        vctmp[i + 2] = float4(_Distance, y, i / _MarginFactor + _EndWidth / 2.0f, 0.0f);
    }

    const float4 vc[TAM] = vctmp;

    float2 UV1tmp[TAM];
    for (i = 0; i < TAM; i += 3) {
        UV1tmp[i] = float2(0.0f, 0.0f);
        UV1tmp[i + 1] = float2(1.0f, 0.0f);
        UV1tmp[i + 2] = float2(1.0f, 1.0f);
    }

    const float2 UV1[TAM] = UV1tmp;

    int tmpTriStrip[TAM];

    for (i = 0; i < TAM; i++) {
        tmpTriStrip[i] = 1;
    }

    const int TRI_STRIP[TAM] = tmpTriStrip;

    v2f v[TAM];

    // Assign new vertices positions
    for (i = 0; i < TAM; i++) { v[i].pos = vert[0].pos + vc[i]; v[i].col = vert[0].col; }

    // Assign UV values
    for (i = 0; i < TAM; i++) v[i].uv_MainTex = TRANSFORM_TEX(UV1[i],_MainTex);

    // Position in view space
    for (i = 0; i < TAM; i++) { v[i].pos = mul(UNITY_MATRIX_MVP, v[i].pos); }

    // Build the cube tile by submitting triangle strip vertices
    for (i = 0; i < TAM / 3; i++)
    {
        triStream.Append(v[TRI_STRIP[i * 3 + 0]]);
        triStream.Append(v[TRI_STRIP[i * 3 + 1]]);
        triStream.Append(v[TRI_STRIP[i * 3 + 2]]);

        triStream.RestartStrip();
    }
}


texts:
I am trying to draw a chessboard pattern using VBO. Geometrywise, I have it implemented and working nicely. However, I have come to the point where I want to color up the board and I have realized that I cannot do it because vertices should be black and white at the same time, depending which square they are drawing. So, looks like I cannot create a color array the same way I create a vertex array.

Any ideas how I can sort this out? Is there anyway to assign two colors to the same vertex, and select one or another depening on the actual square being rendered?

This is the code I am using so far, which is generating a nice "white to black" diagonal pattern instead of the chessboards-like.

glGenBuffersARB(1, &VBOfloorVerticesAndNormals);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, VBOfloorVerticesAndNormals);
glBufferDataARB(GL_ARRAY_BUFFER_ARB, numVertices*sizeof(float), vertices, GL_STATIC_DRAW_ARB);

glGenBuffersARB(1, &VBOcolors);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, VBOcolors);
glBufferDataARB(GL_ARRAY_BUFFER_ARB, numColors*sizeof(float), colors, GL_STATIC_DRAW_ARB);

glGenBuffersARB(1, &VBOfloorIndex);
glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, VBOfloorIndex);
glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, numIndices*sizeof(int), indices, GL_STATIC_DRAW_ARB);

glEnableClientState(GL_VERTEX_ARRAY);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, VBOfloorVerticesAndNormals);
glVertexPointer(3, GL_FLOAT, 0, 0);

glEnableClientState(GL_COLOR_ARRAY);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, VBOcolors);
glColorPointer(4, GL_FLOAT, 0, 0);

glIndexPointer(GL_UNSIGNED_SHORT, 0, 0);
glDrawElements(GL_QUADS, numIndices, GL_UNSIGNED_INT, 0);

glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);

glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);

And this is the pattern I get:


texts:
So, I've been working on a project for a while which is basically just a little 2D game. The fun/hard part is that I've been trying to make it work as a multiplayer game. Right now, the game is just a bunch of entities, both players and projectiles shot from players. I have a question about how to keep the entities in sync on both the client and the server.

Is it better to send many many little "update packets" for each entity whenever it is updated? What I mean is, should I send a packet containing an entity's x and y position whenever it moves?

or

Is it better to send larger update packets that contain the updated info for many entities? What I mean here is should I send a bigger packet that has an array of smaller "update packets" that each have updated info on a specific entity?

I'm not sure which will cause less lag and be more scalable. What about if I had a hundred or more entities to update? Which method would work better in that case?

Thanks.


texts:
I'm really interested about the capabilities of Entity System. I'm trying to search for a good book on this one, but failed.

I don't want to get lost on learning this paradigm so a book will be a big help. Can someone recommend a good book?

Also, is this language agnostic? Or are there languages that will have a hard time implementing this paradigm (eg. Objective-C)?

Thanks.


texts: What audio method works across all web browsers and mobile for HTML5/JavaScript?

texts:
I have looked at a number of ways to trigger audio in HTML5/JavaScript, but each time I find something that might be workable, I find web browsers and mobile devices it doesn't work on at all.

What is considered the best method that works across all web browsers and mobile for creating a game with sound using HTML5/JavaScript?

What do experienced interactive game programmers do? Do you check the user's web browser or mobile device and serve up different code to make it work? Or do you have a single solution for this? Or do you warn the user by supplying a list of web browsers and mobile devices the software is known to work with?

Additional Information: I found out that audio in some web browsers, like Safari on the Mac, it will load the audio file each time it is triggered, which causes a problem. I saw once solution using what is called Audio Sprites:
https://phaser.io/examples/v2/audio/audio-sprite
This way, you load one audio containing all your sounds needed, and then you pass a pointer to where in the audio file to start playing the sound and where to stop. That sounded like a solution, but this doesn't work on the Safari web browser, it produces no sound at all.

Then I looked into Web Audio API, and this is impressive:
https://forestmist.org/share/web-audio-api-demo

While this worked on the Mac for Safari, Firefox and Google Chrome, and the iPhone, it doesn't work on Windows with Internet Explorer (or Safari on Windows either).

I've not tested Web Audio API on the android phone yet, because I don't have access to one at the moment. So I was wondering what experienced interactive programmers do to provide audio to work across most or all platforms? It seems a huge step-backwards to have to alert visitors to a website that they can only use the functions on it by using a short list of web browsers.

The issues as I see it seem to have to do with being able to load the audio file and not have it re-loaded over the internet each time it is referred as play(). I realize Web Audio API might provide much more capability than most of us needs, but is that the current gold-standard for audio in a HTML5/JavaScript game?

Here is a simple example, using audio that works on Google Chrome/Mac, but it doesn't work on Safari/Mac:
https://rawgit.com/mehaase/js-typewriter/master/example3-typewriter/index.html


texts:
I have three objects. All of them in the create event contain an action each (execute a piece of code):

obj_r01 => r01=0;

obj_r02 => r02=0;

obj_r03 => r03=0;

Image (to clarify what I have tried to explain):

So far so good, but I have one more object that modifies the variables of these other three: obj_control

The obj_control contains two events: create and draw.

crete event (obj_control):

obj_r01.r01=irandom(9);
obj_r02.r02=irandom(9);
obj_r03.r03=irandom(9);

draw event (obj_control):

This event contains three actions, precisely three "execute a piece of code":

piece one:

draw_text(x,y,obj_r01.r01); => applies to obj_r01

piece two:

draw_text(x,y,obj_r02.r02); => applies to obj_r02

piece three:

draw_text(x,y,obj_r03.r03); => applies to obj_r03

The objects are arranged as follows in the room:

In execution this is what happens:

The value of r01 is randomized, but that of r02 and r03 is not. I also tried to modify the obj_control creation event code to:

randomize();
obj_r01.r01=irandom(9);
randomize();
obj_r02.r02=irandom(9);
randomize();
obj_r03.r03=irandom(9);

However the result does not change. With this I could only suspect that the irandom () function can only create a storable random value, would it solve such a problem?

EDIT 1:

I tried putting randomize() only at the beginning of the code as suggested to me by @Philipp and @DH.:

randomize();
obj_r01.r01=irandom(9);
obj_r02.r02=irandom(9);
obj_r03.r03=irandom(9);

But there was no change in the result.

I also did a test to be sure if the value was not even being randomized or if the values of r02 and r03 were being randomized to 0 and for that I modified their values in the creation of each object:

In obj_r02:

r02=10

In obj_r03:

r03=100

The result:

The first value (not surprisingly) was randomized, but the second and third values were not. Thus it is clear that the randomization is not being made or that the draw event is occurring before the radomization of r02 and r03.


texts:
I am attempting to understand how OpenGL (ES) blending works. I am finding it difficult to understand the documentation and how the results of glBlendFunc and glBlendEquation effect the final pixel that is written.

Do the source and destination out of glBlendFunc get added together with GL_FUNC_ADD by default?

This seems wrong because "basic" blending of GL_ONE, GL_ONE would output 2,2,2,2 then (Source giving 1,1,1,1 and dest giving 1,1,1,1).

I have written the following pseudo-code, what have I got wrong?

struct colour {
    float r, g, b, a;
};

colour blend_factor( GLenum factor,
    colour source,
    colour destination,
    colour blend_colour ) {

    colour colour_factor;
    float i = min( source.a, 1 - destination.a );

    // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glBlendFunc.xml
    switch( factor ) {
        case GL_ZERO: colour_factor = { 0, 0, 0, 0 }; break;
        case GL_ONE: colour_factor = { 1, 1, 1, 1 }; break;
        case GL_SRC_COLOR: colour_factor = source; break;
        case GL_ONE_MINUS_SRC_COLOR: colour_factor = { 1 - source.r, 1 - source.g, 1 - source.b, 1 - source.a }; break;
        // ...
    }

    return colour_factor;
}

colour blend( colour & source,
    colour destination,
    GLenum source_factor, // from glBlendFunc
    GLenum destination_factor, // from glBlendFunc
    colour blend_colour, // from glBlendColor
    GLenum blend_equation // from glBlendEquation
    ) {

    colour source_colour = blend_factor( source_factor, source, destination, blend_colour );
    colour destination_colour = blend_factor( destination_factor, source, destination, blend_colour );
    colour output;

    // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glBlendEquation.xml
    switch( blend_equation ) {
        case GL_FUNC_ADD: output = add( mul( source, source_colour ), mul( destination, destination_colour ) );
        case GL_FUNC_SUBTRACT: output = sub( mul( source, source_colour ), mul( destination, destination_colour ) );
        case GL_FUNC_REVERSE_SUBTRACT: output = sub( mul( destination, destination_colour ), mul( source, source_colour ) );
    }

    return output;
}

void do_pixel() {

    colour final_colour;

    // Blending
    if( enable_blending ) {

        final_colour = blend( current_colour_output, framebuffer[ pixel ], ... );
    } else {

        final_colour = current_colour_output;
    }

}

Thanks!


texts:
I implemented SSAO in my game based on the tutorial at gamerendering.com. But the results I get are disappointing. Instead of a smooth effect as seen in the nvidia demos, my implementation causes either squashy dark noise or results in a huge performance hit for all the blurring.

This is my scene without SSAO applied.

And this is how the result looks.

For now I use the same code as provided in the example I linked above. How can I improve the result of the ambient occlusion shader? A lot of blurring seems to be very slow on the GPU. I would like to get a result similar to this by Nvidia. How do they do that?


texts: What is the name of perspective of Age of Empires II?

texts:
One would describe Age of Empires 1's "perspective" as a 2D sprite game:

Below is a screenshot of Age of Empires II. How would you describe the "perspective"? Is it also a 2D sprite game?

"Perspective" may not even be the correct word. If it isn't, what should I use?


texts: How to detect if a 2D object overlaps any other 2D objects

texts:
I am programmatically placing 4 large dots on my 2D scene which already has some objects on it. If the new dot overlaps an existing object I want to destroy the existing object. All the objects have 2Dcolliders and all are on the same layer ("Action").
Since I only do this once during the initial setup of the game I don't want to use collision detection events, instead it would seem that Collider2D.OverlapCollider would be the way to do this but I can't get it to work. The following code is called from Start() after all the objects have been placed, and thinking it might be something to do with the colliders not being active until the first frames, I also called it from a mouse click with the same result (no overlaps).
    void EraseOverlapDots()
    {
        GameObject[] largeDots = GameObject.FindGameObjectsWithTag("LargeDot");
        foreach(GameObject ldot in largeDots)
        {
            Debug.Log("Object:" + ldot.tag + "(" + ldot.transform.position + ")");

            Collider2D collider = ldot.gameObject.GetComponent<Collider2D>();
            ContactFilter2D contactFilter2D = new ContactFilter2D();
            contactFilter2D.SetLayerMask(ldot.layer);
            contactFilter2D.useLayerMask = true;

            List<Collider2D> collisions = new List<Collider2D>();
            int colCount = collider.OverlapCollider(contactFilter2D, collisions);
            int i = 0;
            foreach (Collider2D col2d in collisions)
            {
                i++;
                Debug.Log("HIT"+i+":" + col2d.tag + "(" + col2d.transform.position + ")");
            }
        }
    }

In an attempt to debug this I purposely put 4 small dots in exactly the same position as the large dots to ensure they overlap. When I run the game they are visibly exactly on top of each other but the result is always zero overlaps.


texts: Unity3d FullScreen Mode Vertical Aspect Ratio in WebGl

texts:
My game has vertical aspect ratio and looks like this:

When I press full screen button

My game start to look like this:

I need to save aspect ratio of the game - how can I do that?


texts: Java libgdx Game Screens and rendering tile map

texts:
I'm working on a 2D tiled game with Java and libGDX. I'm having problems implementing gamescreens. I'm trying to set the screen to gameScreen and start rendering tiles, but I'm getting a nullpointer exception on my camera and my renderer.

I think what's happening is that it's calling the render method before the create method for some reason. The create method is where the camera and renderer are set up.

This is my entry point, gameClass

package com.psillicoder.farmGame;
import com.badlogic.gdx.Game;

public class gameClass extends Game {
    gameScreen gameScreen;

    public static final String TITLE="Farm Game";
    public static final int WIDTH=800,HEIGHT=600;

    @Override
    public void create() {
        gameScreen = new gameScreen(this);
        setScreen(gamaeScreen);
    }

    @Override
    public void render () {
        super.render();
    }
}

This is my gameScreen class:

package com.psillicoder.farmGame;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;

public class gameScreen implements Screen {
    gameClass game;

    private OrthographicCamera camera;
    private OrthogonalTiledMapRenderer renderer;
    private TiledMap map;

    SpriteBatch batch;

    float unitScale = 1/16f;

    public gameScreen(gameClass game) {
        this.game = game;
    }

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

        camera.update();
        renderer.setView(camera);
        renderer.render();

        batch.begin();

        batch.end();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void show() {

        TiledMap map = new TmxMapLoader().load("tdmap1.tmx");
        OrthogonalTiledMapRenderer renderer = new OrthogonalTiledMapRenderer(map,unitScale);

        OrthographicCamera camera = new OrthographicCamera();

        camera.setToOrtho(false,40,40);
        renderer.setView(camera);
        camera.update();

        batch = new SpriteBatch();
    }

    @Override
    public void hide() {
        dispose();
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }

    @Override
    public void dispose() {
        System.out.println("Disposed");
        batch.dispose();
        renderer.dispose();
    }
}


texts: How do I create a camera for a strategy game?

texts:
How do I make a camera for a strategy game? Think something in the style of Warcraft 3, so you can lower the camera angel and view the world in a somewhat 3D format. Do I need to have some coordinate system where you put every single unit, building, etc., in it and then use an algorithm for the camera to render everything between certain coordinates?

Edit: To clearify the question abit more. How do you render the graphics for a strategy game when the map of the game is bigger then what the players camera view is?


texts:
I wanted to know how should I determine a good texture size ?
Currently, I always create UV texture that are 1024x1024px but if I create for example, a big house with a 1024px texture size, it will looks pretty bad.

So, should I create different texture size (512, 1024, ...) for different mesh size like this ? :

or is it better to always do high-resolution texture and then reduce it in the software (ie : increase the LODBias settings in UDK reduce the size of the texture) ?

Thanks for your answer.

ps : sorry for my english !


texts: Implementing an existing (but out of print) game electronically

texts:
One of my favorite games is the old Avalon Hill class, PanzerBlitz.

I would like to implement it electronically, and have a couple questions related to that:

Would I be in legal trouble if I do this? (note - this is not for sale or distribution)
How would I go about implementing the hex grid and piece database most effectively (each piece has a variety of 'factors' (movement, carryability, attack, defense, unit type)?

The game play and mechanics are already well-defined in the written rules - so I'm not writing the game from scratch - just programming it to follow the board game.


texts: Pixel Shader from Visual Studio Graphics Diagnostics

texts:
i want to check my pixel shader variables in graphics diagnostics but unfortunately when i click start debugging in pixel history (mentioned below), a new tap will open and says source is not available. am i have to do anything before start debugging my shader in graphics diagnostics tool ?

Thanks

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


texts: C# XNA AABB vs AABB collision resolution, AABBs ghost through each other

texts:
I've been learning a bit of collision resolution through a tutorial here and I can't seem to get the AABBvsAABB resolution working, I have CirclevsCircle and AABBvsCircle resolution working with the same method,ResolveCollision

Essentially what happens is I have a test scenario where two AABBs collide with each other. The collision gets detected however, the AABBs will just keep going through each other. If two circles collide, they show the correct response.

If you need the full code you can nab it from my github. This has both Windows and Linux versions.

Here is the data class that is passed to the AABBvsAABB method:

public struct Manifold
{
    public PhysicsObject A, B;
    public float PenetrationDepth;
    public Vector2 Normal;
    public bool AreColliding;
}

Here is the code for testing the collision between the AABB and AABB

public static bool AABBvsAABB (AABB a, AABB b, ref Manifold m)
{
    m.A = a;
    m.B = b;
    m.Normal = b.Position - a.Position;

    //Calculate the extent on the X axis
    float aExtent = (a.Right - a.Left) / 2;
    float bExtent = (b.Right - b.Left) / 2;

    //Find the X overlap
    float xExtent = aExtent + bExtent - Math.Abs (m.Normal.X);

    //SAT Test on X
    if (xExtent > 0) {
        //There was overlap on the X axis, now lets try to Y
        aExtent = (a.Bottom - a.Top) / 2;
        bExtent = (b.Bottom - b.Top) / 2;

        //Calculate Y overlap
        float yExtent = aExtent + bExtent - Math.Abs(m.Normal.Y);

        //SAT Test on Y axis
        if (yExtent > 0){
            //Find which axis has the biggest penetration ;D
            if (xExtent > yExtent){
                if(m.Normal.X < 0)
                    m.Normal = new Vector2(-1,0);
                else
                    m.Normal= Vector2.Zero;
                m.PenetrationDepth = xExtent;
                m.AreColliding = true;
                return true;
            }
            else {
                if(m.Normal.Y < 0)
                    m.Normal = new Vector2(0,-1);
                else
                    m.Normal= Vector2.Zero;
                m.PenetrationDepth = yExtent;
                m.AreColliding = true;
                return true;
            }
        }
    }
    return false;
}

Lastly here is the ResolveCollision Method.

public static void ResolveCollision(Manifold m)
{
    Vector2 relVelocity = m.B.Velocity - m.A.Velocity;
    //Finds out if the objects are moving towards each other.
    //We only need to resolve collisions that are moving towards, not away.
    float velAlongNormal = PhysicsMath.DotProduct(relVelocity, m.Normal);
    if (velAlongNormal > 0)
        return;
    float e = Math.Min(m.A.Restitution, m.B.Restitution);

    float j = -(1 + e)*velAlongNormal;
    j /= m.A.InvertedMass + m.B.InvertedMass;

    Vector2 impulse = j*m.Normal;
    m.A.Velocity -= m.A.InvertedMass*impulse;
    m.B.Velocity += m.B.InvertedMass*impulse;
}


texts:
I have drawn 5 tentacles which are shown in red. I have drew those tentacles on a 2D Circle, and positioned them on 5 vertices of the that circle. BTW, The circle is never be drawn, I have used it to simplify the problem. Now I wanted to attached that circle with tentacles underneath the jellyfish. There is a problem with the current code but I don't know what is it.

You can see that the circle is parallel to the base of the jelly fish. I want it to be shifted so that it be inside the jelly fish. but I don't know how. I tried to multiply the direction vector to extend it but that didn't work.

// One tentacle is constructed from nodes
// Get the direction of the first tentacle's node 0 to node 39 of that tentacle;
   Vec3f dir = m_tentacle[0]->geNodesPos()[0] -  m_tentacle[0]->geNodesPos()[39];

    // Draw the circle with tentacles on it

    Vec3f pos = m_SpherePos;

    drawCircle(pos,dir,30,m_tentacle.size());

    for (int i=0; i<m_tentacle.size(); i++)
    {
        m_tentacle[i]->Draw();

    }

 // Draw the jelly fish, and orient it on the 2D Circle
    gl::pushMatrices();
    Quatf q;
    // assign quaternion to rotate the jelly fish around the tentacles
    q.set(Vec3f(0,-1,0),Vec3f(dir.x,dir.y,dir.z));
    // tanslate it to the position of the whole creature per every frame
    gl::translate(m_SpherePos.x,m_SpherePos.y,m_SpherePos.z);
    gl::rotate(q);

    // draw the jelly fish at center 0,0,0
    drawHemiSphere(Vec3f(0,0,0),m_iRadius,90);

    gl::popMatrices();


texts:
I'm using SFML 2.1, it's much more straightforward for me so I can jump directly to learning the shading language.

I'm trying to do something similar to conway's game of life. I already learned that I will need to use 2 textures since I need to read and write at the same time.

My questions:

How do I read neighbor pixels ? Do I need to pass a vec2 from the vertex shader to the fragment shader like this ? :

vertex shader:

out vec2 pixelpos;
void main(){
    pixelpos = gl_Position;
}

fragment shader:

in sampler2d mytexture;
in vec2 pixelpos;
void main(){
    if(mytexture[pixelpos.x][pixelpos.y].r > 0.5)
    {}
}

How do I write to a texture ?


texts: Is it possible to build an app with Corona with only a PC, and expect it to reasonably run well on an iPhone?

texts:
So I understand that Corona allows me to "write once," and deploy on both iPhone and Android. And I understand that I cannot get any iPhone app into the app store without having (at the moment of submission/distribution) an (Intel-based?) mac (physical hardware).

I assume that if I only own PC hardware, I will not be able to test-deploy my game to an iPhone, nor see how the performance might be on an iPhone; but given those limitations, can I expect my Corona app to work decently if it performs decently on the Windows SDK and iPhone versions?


texts: Is the "impossible object" possible in computer graphics?

texts:
This may be a silly question but I want to know the answer to it. I saw this thing called the "impossible object", while they're many different images of this online, it's suppost to be impossible geometry.

Here is an example:

Now as far as logic goes, I know you don't have to obey it in games, such as a flying cow, or an impossible object. So that's out of the way, but what stands in my way is whether or not there is a way to draw this onto a 3D scene. Like is there a way to represent it as a 3D object? Thanks!


texts: Create Bezier curves with random heights that connect

texts:
In unity, I am trying to create several curved platforms that connect using bezier curves, however I am having issues. I understand the basics of genertating a bezier curve and I have something working well

My goal is to generate a series of forward moving Bezier curves, that are all connected to each other, while also having varying lengths and points. I have something working, however I am having issues connecting the curves, while retaining random Y values for different heights in the 4 points.

Below is my attempt:

Below is a Sketch I did in MS Paint to help explain goal:

From the sketch you can see that there is a diffrence in height between gameobject 0 and 1 but they are still connected. How can I generate the next points with random Y values, while still accounting for the previous curve? Any help would be greatly appreciated,

Thank you for your time.


texts: Can I use a SkinnedMeshRenderer animation in a Canvas?

texts:
I just downloaded an asset from the store: https://www.assetstore.unity3d.com/en/#!/content/67122

They're just animated characters. If you drag & drop the prefabs on the scene, it works fine.

The thing is, I work exclusively with Unity's new 2D Canvas/Image/Button/etc. These prefabs instead use a SkinnedMeshRenderer so it's not like you can put them inside your Canvas.

I want to have the prefabs work in my Canvas. For all intents and purposes I want those animations to act like a Image inside the Canvas.

This is what one of those prefabs looks like:

I want to take advantage of the Unity's canvas because it makes a lot of things easier - like scaling for all devices, scroll views, easy masks, etc.


texts: How do you enable a script while releasing the mouse & colliding with another game object?

texts:
I am trying to have it so when you click and drag on the object it disables its motion scripts. That part is done. However when I place it back in a certain gameobject window I want it to snap into place and begin the motion script again. I can get it to snap but it does not want to reenable the script.

Here is the code for attempting to reenable the script that doesn't work.

public class snap : MonoBehaviour {
public GameObject mass;
public harmonic scriptH;
public DrawLine scriptD;
public GameObject spring;

void Start() {
    scriptH = mass.GetComponent<harmonic>();
    scriptD = spring.GetComponent<DrawLine>();
}

void OnTriggerEnter(Collider other) {

    if(other.gameObject.CompareTag("mass")) {
        other.GetComponent<Rigidbody>().MovePosition(transform.position);
        scriptH.enabled = true;
        scriptD.enabled = true;
    }
}

The position transform works but not the script enable. Here is the mouse dragging script though I think I narrowed it down to the point where it is not the problem.

public void OnMouseDown()
{
    isDragging = true;
}

public void OnMouseUp()
{
    isDragging = false;

}

void Update()
{
    if (isDragging) {
        Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        transform.Translate(mousePosition);
      //  scriptH.enabled = false;
      //  scriptP.enabled = false;
      //  scriptD.enabled = false;

    }

I am currently beginning with the scripts as disabled and removed the disabling portion in Update(). The first script(snap) still does not enable the scripts on collision. I tried OnTriggerStay as well as OnTriggerEnter, the box does transform position so I know the collision is registering but do not understand why the script enabling does not work.

They are in different game objects so is it an issue with my declaring the scripts wrong in the first script?

EDIT: Turns out even disabling the first script the box still snaps into position because it is colliding with the gameobject so seems nothing in my first script works. So any input on why the collision doesn't trigger would be appreciated.


texts:
I am trying to make bullets bounce of walls, but I can't figure out how to correctly do the collision detection. What I am currently doing is iterating through all the solid blocks and if the bullet hits the bottom, top or sides, its vector is adjusted accordingly. However, sometimes when I shoot, the bullet doesn't bounce, I think it's when I shoot at a border between two blocks.

Here is the update method for my Bullet class:

def update(self, dt):
    if self.can_bounce:
        #if the bullet hasnt bounced find its vector using the mousclick pos and player pos
        speed = -10.
        range = 200
        distance = [self.mouse_x - self.player[0], self.mouse_y - self.player[1]]
        norm = math.sqrt(distance[0] ** 2 + distance[1] ** 2)
        direction = [distance[0] / norm, distance[1 ] / norm]
        bullet_vector = [direction[0] * speed, direction[1] * speed]

        self.dx = bullet_vector[0]
        self.dy = bullet_vector[1]

    #check each block for collision
    for block in self.game.solid_blocks:
        last = self.rect.copy()
        if self.rect.colliderect(block):
            topcheck = self.rect.top < block.rect.bottom and self.rect.top > block.rect.top
            bottomcheck = self.rect.bottom > block.rect.top and self.rect.bottom < block.rect.bottom
            rightcheck = self.rect.right > block.rect.left and self.rect.right < block.rect.right
            leftcheck = self.rect.left < block.rect.right and self.rect.left > block.rect.left
            each test tests if it hit the top bottom left or right side of the block its colliding with
            if self.can_bounce:
                if topcheck:
                    self.rect = last
                    self.dy  *= -1
                    self.can_bounce = False
                    print "top"

                if bottomcheck:
                    self.rect = last
                    self.dy  *= -1 #Bottom check
                    self.can_bounce = False
                    print "bottom"

                if rightcheck:
                    self.rect = last
                    self.dx  *= -1 #right check
                    self.can_bounce = False
                    print "right"

                if leftcheck:
                    self.rect = last
                    self.dx  *= -1 #left check
                    self.can_bounce = False
                    print "left"

            else:
                # if it has already bounced and colliding again kill it
                self.kill()

    for enemy in self.game.enemies_list:
        if self.rect.colliderect(enemy):
            self.kill()
    #update position
    self.rect.x -= self.dx
    self.rect.y -= self.dy

This definitely isn't the best way to do it but I can't think of another way. If anyone has done this or can help that would be awesome!


texts: How do i make AI move along with the generated instantiate waypoints?

texts:
public GameObject[] waypoints;
private float waypointSpawn = 0;
public float WayPointLength = 25;

public int num = 0;

public float tigerSpeed;

private void Update()
{
    SpawnPoint(0);
    GoesToPoint();
}

void SpawnPoint(int TileIndex)
{
    Instantiate(waypoints[TileIndex], new Vector3(-3, 1 , 0) + transform.forward * waypointSpawn, Quaternion.identity);
    waypointSpawn += WayPointLength;
}

void GoesToPoint()
{
    float dist = Vector3.Distance(gameObject.transform.position, waypoints[num].transform.position);

    gameObject.transform.LookAt(waypoints[num].transform.position);
    gameObject.transform.position += gameObject.transform.forward * tigerSpeed * Time.deltaTime;

    if(num + 1 == waypoints.Length)
    {
        num = 0;
    }
    else
    {
        num++;
    }
}

I wanted AI to move along with the generated waypoints that was been instantiated and then I make my AI move along with the waypoints but it keeps getting stuck at the very first waypoint. How should i make my AI progress forward?


texts: Why is my 2D mouse aim not working properly?

texts:
I'm trying to program 2D mouse aim, where the arms and the gun in the arms rotates to point at the mouse. But for some reason, the arms and gun rotate and do not follow the mouse position.

The each of the arms and the guns are separate node that are parented to an orbit node that is located on at the shoulder of the arms.

The following code is script that is attached and running on the orbit.

    var mousePos = get_viewport().get_mouse_pos();
    var dir = get_pos();
    var angle = (atan2(dir.x,dir.y))+(2*PI);
    var arm_gun_dir = gravGun_Ref.get_pos()-get_pos();
    var arm_gun_angle = (atan2(arm_gun_dir.x,arm_gun_dir.y))+(2*PI);
    set_rot(angle-(PI/2));

Here is a GIF of the result of this setup:

Here is an image showing where the positions of the upper arm and the gun.


texts: Does anyone have a example of Dual Contouring in C#?

texts:
I'm trying to develop a method of creating terrain using Perlin. I've followed plenty of the Minecraft tutorials, and got them to function. I've done some playing around with MarchingSquares, but I'm not digging it.
Now, I've been trying to create a method of dual contouring, and I'm also trying to get the concept of Octrees down at the same time. I used to segment my array of data in small chunkes, but the whole Collapsing and making a larger "chunk" function like a smaller chunker is just not regiserting.

I was hoping someone can share some C# code, preferably for Unity but really just something for me to try to pick apart to understand would help.

When it really comes down to it, I'm not trying to make a game where different "voxels" aren't different types of blocks, just represent where dirt is and where dirt isn't. In game, I want dirt to be taken away due to explosions, but not have a method of placing dirt. I'd like this effect for large enclosed game levels.

Any comments or advice are appreciated.


texts: Drag object with mouse in diagonal direction

texts:
I have a gameobject which i want to move using mouse. Currently i can do that in x-axis and y-axis:

public bool moveDiagonal;
 public bool moveX, moveY;
 public float distanceXmin, distanceXmax, distanceYmin, distanceYmax;
 if (moveX)
 {
     if (curPosition.x >= distanceXmin && curPosition.x <= distanceXmax)
          goToMove.transform.position = new Vector3(curPosition.x, goToMove.transform.position.y, 0);
 }
 else if (moveY)
 {
    if (curPosition.y >= distanceYmin && curPosition.y <= distanceYmax)
          goToMove.transform.position = new Vector3(goToMove.transform.position.x, curPosition.y, 0);
 }

I wanted to move my object diagonally as well how to do that according to its direction using mouse? The object should move along the line or the x and y axis limits.


texts: Using IGameComponent and related interfaces in MonoGame

texts:
I am trying to port a XNA project to MonoGame which involves a DLL game library that I created. This library uses the IGameComponent, IUpdateable and IDrawable interfaces to load one of my library classes as a GameComponent.

The compiler gives errors related to these interfaces, saying, for example: The type 'Microsoft.Xna.Framework.IUpdateable' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.Xna.Framework.Game'...

This would require me to add Microsoft.Xna.Framework.Game to my reference list, which defeats the point of porting to MonoGame. Is there any way these interfaces can be made compatible with MonoGame


texts: Sanitise a high score table to remove offensive terms / usernames

texts:
I'm building an app for a client, which they've requested to have a publicly-visible high score table. It'll be displaying their username, which is a free-text field that the players can input. Player count is likely to be extremely low - I’d expect 10s or 100s/day at most.

The username field will be longer than 3 characters. The names will be tied to Firebase Auth accounts, but these are created through the app, not tied to anything like Google Play or a Facebook account or anything like that. I think they’re going to be fine with deleting obviously offensive names, but they’re not going to have massive resources devoted to manual moderation.

When I was a young lad, 100% of my local arcade cabinet high score tables consisted of a bunch of swear words and offensive terms (or variations of such words).

I can't imagine the internet has improved matters at all.

How can I sanitise usernames to make them safe for display?


texts: How to: Duplicating and updating component data in systems

texts:
I am new to game development. Coming across the ECS (entity-component system) pattern I generally quite liked the idea. I have implemented the current version of my engine using the OOP style approach. In other words, Components are objects that have both state and behaviour and methods that can be polymorphic. My entity manager also means that when a SpriteRenderComponent has been added to an entity, entity.GetComponent<RenderComponent>() will return a reference to the SpriteRenderComponent. Of course, the problem with this is that components have to communicate with each other. E.g. the draw method will access the TransformComponent's transform data.
Now I have dug a bit deeper and found that most sources recommend the pure ECS approach where the entities are an id or a list of components, components are just structs with public data and the systems are where all the magic happens ie where all the functions are. Of course, components don't depend on each other and the same is ideally true for systems as well.
So now when I want to draw a sprite I create a SpriteRenderSystem which knows how to draw a sprite. The problem is that drawing concerns all kinds of drawable things e.g. to sort them depending on a zOrder and layer. This is what lead me to the idea of nodes as objects that are local to the system. So now the SpriteRenderSystem would add a 'SpriteRenderNode' to the RenderManager. The SpriteRenderNode could inherit from an abstract RenderNode and implement the virtual draw method. The SpriteComponent would only hold the data specific to the sprite such as colour. The vertex array and all the other stuff that is purely related to rendering is kept encapsulated in the derived RenderNodes.
Problem #1
In order to be drawn by the RenderManager, the SpriteRenderNode would need to know and therefore store its transform data. The only way to keep this data up to date would be to copy the entity's transform component's transform data to the SpriteRenderNode every frame. I am not so much concerned about performance here but about the practice of duplicating the data in the systems. It feels like this is a violation of general good programming practices though I can't see any immediate reasons why it may prove harmful.
Problem #2
Taking the data out of the components.
From what I understand, the data should live in the components. However, taking the above-presented idea a step further, there may be cases where storing data in components isn't necessary at all. Such an example may be an animation system which may simply store and update animation nodes for each entity and then change their components such as texture, position... The problem with this is that it would take away the ability to save the game by simply serialising all the components.
As you see I am quite confused about how a good pure ECS should look like. Any help would be much appreciated.


texts: How can I get a velocity vector for an object moving in a circle?

texts:
I am simply trying to make an object move in a circle around a point. Let's say I have an object with a position vector going from that point to the object, and also the angle of the object with the x axis.

What is the equation I can use to obtain a velocity vector for that object so that it continues to move in a circle? What other information do I need?


texts:
I'm a single dev making simple mobile games.  I was looking at corona sdk for my next project.  I don't understand what the difference between the paid version and the free version is. It seems that the whole SDK is free, so what does the paid version give you that the free version doesnt?  I've been reading through the site, but I'm not quite getting it.

I will need to interface with apple's game center etc.. is that not accessible to me without paying?


texts: How can I make an attached gameobject behave correctly on character flip?

texts:
I have a character that on start-up is equipped with another gameobject/prefab as a weapon, attaching it to a hand.

void Start()
{
    handFront = transform.Find ("root/Hip/BodyBone/OverArmFrontBone/UnderArmFrontBone/HandFrontBone/HandFrontMount");

    instance = (GameObject)Instantiate(Resources.Load<GameObject>("VioletClub"), new Vector3(-0.5f,2f,1f), new Quaternion(0f,0f,45f,-45f));
    instance.transform.parent = handFront;
}

As long as I move the character in the initial direction (right) the attached object behaves as it should, staying in the hand no matter the animation played. But when I flip the character, the attached object doesn't flip correctly. In the initial position (standing still) it looks correct but when I start to move the character, the item flips and rotates the wrong way. It does not follow the arm movement like it should.

This is what I do on flip:

void Flip ()
{
    facingRight = !facingRight;

    Vector3 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;

}

When I flip the character back to the right again it all work as it should.

Can anyone help me?


texts: How to export a terrain from Unity to Blender?

texts:
I'm trying to make an environment for my scene that consists animations and other objects such as trees.

Making a terrain in Unity seem to be a lot easier than in Blender, so I want to export that environment which I've made in Unity to Blender. How can I do this?


texts: Would this 2D Lighting and Shadows implementation work?

texts:
I'm writing a top-down 2D tile-based game and I'm trying to decide on how to implement lighting and shadows. The game will have a large number of light sources, some static and some moving around the game world. However each light will only have a radius of a few tiles so I don't expect a large number of lights to affect the same pixel. Also, ideally, I'd like to be using normal-mapped sprites combined with the direction of lighting to give some depth to the lighting in the game.

My current plan is to render the whole screen to an off-screen buffer without lighting applied (diffuse) and at the same time rendering the UV normal maps to a similar offscreen buffer, much like in this excellent post from Wholehog Games.

At the same time, I plan to calculate and store the geometry of areas that are to be lit by each light as a triangle-fan mesh, similar to this truly excellent post on 2D shadows by Amit Patel (Red Blob Games).

Given this set of light geometry and the diffuse and normal maps to work from, I believe I should then be able to draw the final scene to the screen, first just as the diffuse drawn with low ambient lighting, then blended with each light source using its geometry of which areas to affect and shaded using UV/bump mapping for that light source. This will end up rendering the light's geometry for each visible light to only the area it affects.

Does this seem like a valid approach to 2D lighting that's going to be performant enough with a lot of lights on screen? As a relatively inexperienced graphics programmer, I don't want to set off down this route without at least sanity-checking it with the community :)

Although I'm trying to keep this question platform-agnostic, I'm using Java/LibGDX/OpenGL on modern desktops only (so I'm not accounting for less powerful tablets and mobiles).


texts: Correcting Lighting in Stencil Reflections

texts:
I'm just playing around with OpenGL seeing how different methods of making shadows and reflections work.

I've been following this tutorial which describes using GLUT_STENCIL's and MASK's to create a reasonable interpretation of a reflection.

Following that and a bit of tweaking to get things to work, I've come up with the code below.

Unfortunately, the lighting isn't correct when the reflection is created.

glPushMatrix();
plane();                                                //draw plane that reflection appears on

    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
    glDepthMask(GL_FALSE);
    glEnable(GL_STENCIL_TEST);
    glStencilFunc(GL_ALWAYS, 1, 0xFFFFFFFF);
    glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);

plane();                                                //draw plane that acts as clipping area for reflection

    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
    glDepthMask(GL_TRUE);
    glStencilFunc(GL_EQUAL, 1, 0xFFFFFFFF);
    glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

    glDisable(GL_DEPTH_TEST);
    glPushMatrix();
    glScalef(1.0f, -1.0f, 1.0f);
    glTranslatef(0,2,0);
    glRotatef(180,0,1,0);

sphere(radius, spherePos);                              //draw object that you want to have a reflection

    glPopMatrix();
    glEnable(GL_DEPTH_TEST);
    glDisable(GL_STENCIL_TEST);

sphere(radius, spherePos);                              //draw object that creates reflection
glPopMatrix();

It looked really cool to start with, then I noticed that the light in the reflection isn't correct.

I'm not sure that it's even a simple fix because effectively the reflection is also a sphere but I thought I'd ask here none-the-less.

I've tried various rotations (seen above the first time the sphere is drawn) but it doesn't seem to work. I figure it needs to rotate around the Y and Z axis but that's not correct.

Have I implemented the rotation wrong or is there a way to correct the lighting?


texts: Where to put SFML Window in GameStateManager

texts:
I have a Pong game using SFML organized after this tutorial.

This is the UML diagram from the tutorial.

Now I am not sure where I should put my SFML RenderWindow variable (and other things that might need to be shared between game states.

I have a PlayingGameState with a shared_ptr to a GameStateManager. So the right place should be the GameStateManager class. Or should I put it into the DirectRenderingGameStateManager and change the shared_ptr to DirectRenderingGameStateManager?


texts: How to make a simple HUD with no library

texts:
I am writing a simple game in c++ using opengl in a windows system.

I have the scene and I need some informative text to appeared to the left top/bottom of the screen

I am printing these messages with a little plane and the text on it, but I want them to be aligned at the corners of the screen.

So I've read this question here and I thought it seemed quite good and closer to my needs.

So, this is some of my code already used:

In init function of openGL:

glShadeModel (GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glClearDepth(1);
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);

In the Resize function:

if (window_height == 0) window_height = 1;
glViewport(0, 0, window_width, window_height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, (float)window_width/(float) window_height, 1.0, 550.0);

And finally in the render function:

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0, 0, -250); //is used for making the scene visible
RenderScene();
glutSwapBuffers();

I've tried using the ready3D() and then RenderScene() functions but the scene looked a lot different to what I was aiming.

How can I achieve this simple HUD (printing messages aligned to the window's corners)?

Edit #1:

This is what I see (terrain and message below):

I want the message to be aligned at the bottom left corner as well as other messages.


texts:
I am making a game with multiplayer split screen mode using SDL. Basically, I like the idea of having each player plug in his own keyboard to the PC, set custom controls via options and being able to play it with controls that he likes.

However, there's a problem. This code gets the keyboard event:

SDL_Event event;
SDL_PollEvent(&event);

SDL_Event has member SDL_KeyboardEvent key, which has member Uint8 which. In short:

event.key.which;

According to this, it should represent keyboard device index, however, I've tried connecting three keyboards to my PC and press the buttons at the same time and the result wasn't satisfying: they all had same keyboard indexes. Is there a solution to this? Or am I missing something?


texts:
I've been researching this for a while, and had no luck yet. I figured I'd ask here to see if anyone had any good ideas.

Essentially what I want is a shader that can make only part of an object transparent based on a slider. Similar to fill effects on 2D sprites, the object would fill from the bottom up, when the slider was set to 0 the whole object would be transparent, when it was set to 50 just the bottom half would be visible, and when it was set to 100 the whole object would be visible.

I've tried various masking effects, but it would be best if I could build this in to existing shaders or have a separate mask. Is there perhaps a way to adjust the alpha on individual pixels used for the diffuse texture without incurring great performance loss?


texts: How do I let game maker know that recieved json data is an array?

texts:
In python I created an array called lobbyList = ["Awesome","Funny","Epic"]

I sent this array to Game maker studio 1.4 using JSON, I made a variable called RecievedData and made the following script

var name = argument0;
var data = argument1;

RecievedData = json_decode(data);
show_message(RecievedData); //Let's me know data has been recieved

I can recieve data fine, but when I show_message(RecievedData) it returns 4, when I do show_message(data) it gives me a string of ["Awesome","Funny","Epic"]

So how do I tell game maker that this is an array and not just a number or string? I want to draw this array coming from the server into a lobby list but for the life of me, I can't figure out how say this is an array.


texts: Does one's choice of 3d modeling software used during asset creation affect performance at runtime?

texts:
Does software used to create 3d assets (for game development specifically) have an impact on the efficiency of the program?

In other words, is it possible to reduce the operating footprint of an application merely by utilizing alternative development software during production of 3d assets? If you use two different applications to create a 3-dimensional image of a box, can one of them result in better performance if aspects of the image are identical?

I am attempting to get the information I need without causing unnecessary debate over specific software choice.


texts: How do i properly make a skybox in Unity?

texts: I have some trouble creating a sky box from a panoramic texture. Everything appears to be working. However there are some artifacts in one place. How do i get rid of them?


texts: What matrix operations do I perform to translate then rotate then translate then rotate?

texts:
In an android game I want to draw a running leg. To output the thigh I do something like:

// legCX,legCY is the location on screen about which the leg rotates.
Matrix m = new Matrix();
m.postTranslate(-legCX,-legCY);
m.postRotate(legRot);
m.postTranslate(legCX,legCY);

So, the above translates the 0,0 point over to the point of rotation about which I want to rotate the leg, then it rotates by the amount I want the leg rotated, then it translates 0,0 back to the original origin.

I then use that matrix to draw the thigh. It ends up rotated as expected. So far so good.

How do I draw the second part of the leg below the knee? It rotates differently than the part of the leg above it and has a center point which moves with the leg above it. I tried the following, but it turns out that the end result is rotation around some single point which doesn't follow the thigh.

Matrix m = new Matrix();
m.postTranslate(-legCX,-legCY);
m.postRotate(legRot);
m.postTranslate(0,-thighLength);
m.postRotate(shinRot);
m.postTranslate(0,thighLength);
m.postTranslate(legCX,legCY);

I suspect that it's probably necessary to do the two rotations in two different Matrix objects and then combine them somehow, but I can't figure out how exactly to do that.

I've tried reading the various wikipedia articles on matrix operations, but I'm having trouble finding the sort of operation that I'm trying to perform.

EDIT: This type of matrix seems to be called a "transformation matrix". Combining multiple operations is called composition of transformations. However, none of the pages on this topic mention how to do a series of translations and rotations.

Surely, if you can use a matrix to do rotation about one point, it must be possible to do multiple matrix operations somehow to allow rotation about one point and then an additional rotation around a different point.

I've tried looking at pages on skeletal animation, but I can't make head nor tail of what they're talking about. My game won't involve many characters, so I don't need to use a physics engine to do super complex stuff. I just want to do the calculations to draw a character that runs.

EDIT: Hooray! Thanks dkantowitz! Your answer wasn't quite right, but you got me really close. I've edited your answer to be correct now. The second matrix needed to translate from the origin, not relative to the leg's center of rotation. And, the combined matrix needs to preConcat the shin matrix first and then the thigh's matrix. Thanks!


texts: Do unused vertices in a 3D object affect performance?

texts:
For my game I need to generate a mesh dynamically. Now I'm wondering does it have a noticeable affect in FPS if I allocate more vertices than what I'm actually using or not? and does it matter if I'm using DirectX or OpenGL?

Edit

Final output will be a w*h cell grid, but for technical issues it's much easier for me to allocate (w+1)*(h+1) vertices. Sure I'll only use w*h vertices in indexing, and I know there is some memory wasting there, but I want to know if it also affect FPS or not? (Note that mesh is only generated once in each time you play the game)


texts: Checking game objective status in efficient way on each update call

texts:
I am creating a 2d mobile game where there are three levels. Each level has 20 objectives. This can increase in the future.

Examples:

Level 1
Current Objective: 2/20
Objective : Collect 1000 coins
Rewards: 100  coins.

Level 1
Current Objective: 20/20
Objective : Kill 100 aliens
Rewards: Shotgun

The question is, when a user is playing a game, how do you check if he has already completed his current objective in efficient way? This is not involving any third party listener like GameCenter, Scoreloop, etc.

I do not want to have a method with zillions of switch/if-else/or any other conditional blocks to be checked in every update call since this will affect the FPS. Some frameworks are not thread-safe. So having a separate thread is not an option either since I am going to port it to some other platforms using some other frameworks.

How do I go about it?


texts: How scanline rendering finds an intersection with an object

texts:
I'm a newbie with graphics and after I read many articles on the web I still don't understand how in rasterizing from a pixel coordinate like (0;0) on the screen the intersection with an object (let's say a sphere) is found before determining its color and how the Z buffer comes into play.

I know something about ray tracing.. is a ray shot from the 0;0 pixel and the intersection point thus determined by the equality between the ray equation with the sphere equation? If it works that way I don't see what the Z buffer is useful to.

I don't know if I explained myself correctly, if not please let me know and I'll try to be as clear as I can on my doubt.


texts: How to setup a Visual Studio 2015 Android C++ project to use SFML and targets an Android device?

texts:
In Visual Studio I have installed the cross platform tools to set up a C++ project for Android and iOS such as the Android SDK, NDK and the corresponding USB drivers required to debug the program on a connected android device as well as varying sdk levels allowing for compilation on devices from different periods in time. My first question is: using the default C++ application template in visual studio for android:

How would I go about rendering an sfml window to the screen of the device I am debugging on within the project’s main function code?:

void android_main(struct android_app* state) {
struct engine engine;

memset(&engine, 0, sizeof(engine));
state->userData = &engine;
state->onAppCmd = engine_handle_cmd;
state->onInputEvent = engine_handle_input;
engine.app = state;

// Prepare to monitor accelerometer
engine.sensorManager = ASensorManager_getInstance();
engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager,
    ASENSOR_TYPE_ACCELEROMETER);
engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager,
    state->looper, LOOPER_ID_USER, NULL, NULL);

if (state->savedState != NULL) {
    // We are starting with a previous saved state; restore from it.
    engine.state = *(struct saved_state*)state->savedState;
}

engine.animating = 1;

// loop waiting for stuff to do.

while (1) {
    // Read all pending events.
    int ident;
    int events;
    struct android_poll_source* source;

    // If not animating, we will block forever waiting for events.
    // If animating, we loop until all events are read, then continue
    // to draw the next frame of animation.
    while ((ident = ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events,
        (void**)&source)) >= 0) {

        // Process this event.
        if (source != NULL) {
            source->process(state, source);
        }

        // If a sensor has data, process it now.
        if (ident == LOOPER_ID_USER) {
            if (engine.accelerometerSensor != NULL) {
                ASensorEvent event;
                while (ASensorEventQueue_getEvents(engine.sensorEventQueue,
                    &event, 1) > 0) {
                    LOGI("accelerometer: x=%f y=%f z=%f",
                        event.acceleration.x, event.acceleration.y,
                        event.acceleration.z);
                }
            }
        }

        // Check if we are exiting.
        if (state->destroyRequested != 0) {
            engine_term_display(&engine);
            return;
        }
    }

    if (engine.animating) {
        // Done with events; draw next animation frame.
        engine.state.angle += .01f;
        if (engine.state.angle > 1) {
            engine.state.angle = 0;
        }

        // Drawing is throttled to the screen update rate, so there
        // is no need to do timing here.
        engine_draw_frame(&engine);
    }
}