texts: How can you allow a sphere to rotate 360 degrees inside a hollow cylinder in Unity?

texts:
I have a hollow cylinder, within which is a sphere. The forward vector is predefined, so the user can not change their forward speed. What they do have control of, however, is the rotation of the sphere around the cylinder by swiping the screen.

Again, I want this rotational movement to occur while the ball is traveling on a forward vector.

Here is the code I have thus far in C#:

public float speed;

private Rigidbody rb;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = 1;

    print(moveVertical);

    Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

    rb.AddForce(movement * speed);
}

The current controls are for the left and right arrow keys, but I will implement swiping later.

I would appreciate any help you could provide. Thank you.


texts: What is the correct and most efficient approach of streaming vertex data?

texts:
Usually, I do this in my current OpenGL ES project (for iOS):

Initialization:

Create two VBO's and one IndexBuffer (since I will use the same indices), same size.
Create two VAO's and configure them, both bound to the same Index Buffer.

Each frame:

Choose a VBO/VAO couple. (Different from the previous frame, so I'm alternating.)
Bind that VBO
Upload new data using glBufferSubData(GL_ARRAY_BUFFER, ...).
Bind the VAO
Render my stuff using glDrawElements(GL_***, ...);
Unbind the VAO

However, someone told me to avoid uploading data (step 3) and render immediately the new data (step 5). I should avoid this, because the glDrawElements call will stall until the buffer is effectively uploaded to VRAM. So he suggested to draw all my geometry I uploaded the previous frame and upload in the current frame what will be drawn in the next frame. Thus, everything is rendered with the delay of one frame.

Is this true or am I using the good approach to work with streaming vertex data?

(I do know that the pipeline will stall the other way around. Ie: when you draw and immediately try to change the buffer data. But I'm not doing that, since I implemented double buffering.)


texts:
I am currently trying to implement simple lighting into my game. My world is represented in a 2d array of numbers, each number being a certain tile. I am changing the color parameter in the spritebatch.Draw method to dim the tiles, and that is working quite well for me(I don't know how to use shaders).Each tile can have a light level from 0 to 5, and depending on its level it will be brighter/darker. The problem I have is that I used this code to simulate lighting:

public void Update()
    {
        foreach (NonCollisionTiles tile in nonCollisionTiles)
        {
            foreach (NonCollisionTiles otherTile in nonCollisionTiles)
            {
                if (otherTile.Rectangle.X  == tile.Rectangle.X && (otherTile.Rectangle.Y / size == tile.Rectangle.Y - 1 || otherTile.Rectangle.Y / size == tile.Rectangle.Y + 1))
                {
                    if (tile.Light < otherTile.Light)
                    {
                        tile.Light = otherTile.Light - 1;
                    }
                }
                else if (otherTile.Rectangle.X / size == tile.Rectangle.Y && (otherTile.Rectangle.X / size == tile.Rectangle.X - 1 || otherTile.Rectangle.Y / size == tile.Rectangle.X + 1))
                {
                    if (tile.Light < otherTile.Light)
                    {
                        tile.Light = otherTile.Light - 1;
                    }
                }
            }
        }
    }

But I'm not sure if it works or not and it lowers my FPS to 1. I have no idea as to how I can implement my lighting system. Essentially, I want it to look like a torch in Minecraft, but in 2d. Here is the code for my tiles:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;

namespace Tile_Map
{
class Tiles
{
    protected Texture2D texture;
    protected int light = 1;
    public int Light
    {
        get { return light; }
        set
        {
            light = value;
        }
    }
    protected Color color;
    private Rectangle rectangle;
    public Rectangle Rectangle
    {
        get { return rectangle; }
        protected set { rectangle = value; }
    }
    private static ContentManager content;
    public static ContentManager Content
    {
        protected get { return content; }
        set { content = value; }
    }

    public void Update()
    {
        color = new Color(light*51,light*51,light*51);
    }
    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, rectangle, null, color, 0, Vector2.Zero,SpriteEffects.None,0f);
    }
 }

class CollisionTiles : Tiles
{
    public CollisionTiles(int i, Rectangle newRectangle)
    {
        texture = Content.Load<Texture2D>(@"Images\Tile" + i);
        this.Rectangle = newRectangle;
    }
}
class NonCollisionTiles : Tiles
{
    public NonCollisionTiles(int i, Rectangle newRectangle)
    {
        texture = Content.Load<Texture2D>(@"Images\Tile" + i);
        this.Rectangle = newRectangle;
    }
}
}

This is what I am trying to do:

Any help is appreciated!


texts: Clientside anticheating in multiplayer game 1vs1

texts:
I'm developing a simple card game, where there will be a matchmaking system that will put you against another human player. This will be the only game mode available, a 1vs1 against another human, no AI.

I want to prevent cheating as much as possible. I have already read a lot of similar questions here and I already know that I cannot trust the client and I have to make all verifications server side. I intend to have a server (need one for the matchmaking anyway) and I intend to make some verifications server side but if I want to check everything server side this makes my server to be able to keep track of the state of all current games and check every action, and I don't have the money/infrastructure to support that server.

My idea is to make clients check and verify some of the actions made by their opponent* and if they find some illegal action notify the possible cheating to the server and make the server verify it. This will still require my server to keep track of all current games, but it will save resources only checking some things that cannot be checked at client side(like card order in the deck) and only checking other things when they are actually wrong.

*(only those they can check with out allowing themselves cheating! for example:they can't check if the played card was in hand cos that will need them to know all cards in hand)

Summing up, my questions are: is this a viable approach? will I actually save resources doing this or the extra complexity in the server and client for exchanging this messages is not worth it? do you know any game that has successfully or unsuccessfully tried a similar approach?

Thanks all for reading and answering


texts: Textures do not render on ATI graphics cards?

texts:
I'm rendering textured quads to an orthographic view in XNA through hardware instancing. On Nvidia graphics cards, this all works, tested on 3 machines. On ATI cards, it doesn't work at all, tested on 2 machines.

How come? Culling perhaps?

My orthographic view is set up like this:

Matrix projection = Matrix.CreateOrthographicOffCenter(0, graphicsDevice.Viewport.Width, -graphicsDevice.Viewport.Height, 0, 0, 1);

And my elements are rendered with the Z-coordinate 0.

Edit:

I just figured out something weird.

If I do not call this spritebatch code above doing my textured quad rendering code, then it won't work on Nvidia cards either. Could that be due to culling information or something like that?

        Batch.Instance.SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone);
        ...
        spriteBatch.End();

Edit 2:

Here's the full code for my instancing call.

    public void DrawTextures()
    {

        Batch.Instance.SpriteBatch.Begin(SpriteSortMode.Texture, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone, textureEffect);
        while (texturesToDraw.Count > 0)
        {
            TextureJob texture = texturesToDraw.Dequeue();
            spriteBatch.Draw(texture.Texture, texture.DestinationRectangle, texture.TintingColor);
        }
        spriteBatch.End();

#if !NOTEXTUREINSTANCING
        // no work to do
        if (positionInBufferTextured > 0)
        {

            device.BlendState = BlendState.Opaque;

            textureEffect.CurrentTechnique = textureEffect.Techniques["Technique1"];
            textureEffect.Parameters["Texture"].SetValue(darkTexture);
            textureEffect.CurrentTechnique.Passes[0].Apply();

            if ((textureInstanceBuffer == null) ||
                (positionInBufferTextured > textureInstanceBuffer.VertexCount))
            {
                if (textureInstanceBuffer != null)
                    textureInstanceBuffer.Dispose();

                textureInstanceBuffer = new DynamicVertexBuffer(device, texturedInstanceVertexDeclaration, positionInBufferTextured, BufferUsage.WriteOnly);
            }

            if (positionInBufferTextured > 0)
            {
                textureInstanceBuffer.SetData(texturedInstances, 0, positionInBufferTextured, SetDataOptions.Discard);
            }

            device.Indices = textureIndexBuffer;
            device.SetVertexBuffers(textureGeometryBuffer, new VertexBufferBinding(textureInstanceBuffer, 0, 1));

            device.DrawInstancedPrimitives(PrimitiveType.TriangleStrip, 0, 0, textureGeometryBuffer.VertexCount, 0, 2, positionInBufferTextured);

            // now that we've drawn, it's ok to reset positionInBuffer back to zero,
            // and write over any vertices that may have been set previously.
            positionInBufferTextured = 0;

        }
#endif
    }


texts: Quaternion to axis-angle, or ripping apart a full transform matrix

texts:
My game entities currently hold a quaternion for their orientation with the ability to return either a 3X3 full rotation matrix (based on that quaternion), or a full 4X4 transform matrix. though what I have come to find is that I am not able to convert from my matricies to DirectX matricies directly, so my next thought would be to force the conversion by hand. which of the following methods would work best/easiest/accurate?

take the quaternion, and break it down into the individual axis-aligned rotations
take either the full rotation matrix, or the full transform matrix and break it down

for either approach it would need to yield the component rotations (theta about X, phi about Y, rho about Z).

I have a feeling that breaking the quaternion down might be the easier rout, but I am not sure as to the actual operations to do this break down.


texts: Procedurally generating terrain in dead time before buffer swap

texts:
I'm using OpenGL/C++ in Windows, and my main loop looks like this:
    GLboolean done = GL_FALSE;
    auto_ptr l_world(new World);
    l_world->Init();

while (!done) {
    if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) {
        if (msg.message==WM_QUIT) {
            done = GL_TRUE;
        } else {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    } else {
        if (!world->Iteration() || keys[VK_ESCAPE]) {
            done = GL_TRUE;
        } else {
            LocalContext.SwapBuff();
        }
    }
}

where Iteration() is:

GLboolean World::Iteration() {
    DrawAll();
    MoveAll();
    CheckForCollisions();

    return GL_TRUE;
}

I've implemented the diamond-square algorithm to procedurally generate terrain, which I'm currently doing in World::Init(). Vertices, indices and textures are stored in buffers to be drawn every frame.

That's fine for a small area, but I want to make it much bigger if possible. To do that I'd like to generate on-the-fly as the camera moves, which would be done at the end of the iteration, after the drawing, moving and collision detection but before the buffer swap. It could be split over several frames, but I'd like to get as much done in a single frame as possible.

As I understand it, with vsync enabled SwapBuffers will block until the end of frame, so any time between the SwapBuffers call and the end of frame will be wasted. So that's my question: is there a way to tell how much time remains until the end of the frame, so I can keep generating terrain until the last possible instant but still maintain a consistent frame rate?

I've not found anything too helpful on the OpenGL Synchronisation page. I wondered if Triple Buffering might be the answer - if the other back buffer contains a completed frame, keep generating; if it's empty then SwapBuffers. It's not a great solution as it would make triple buffering mandatory, and how would you detect if one of the back buffers was free? Any better suggestions?


texts:
I was trying to do a pre-calculations of an SSAO effect by rendering normals and depth on a cubemap and doing a second ssao pass on each of these faces. The problem is I'm getting a timeout: "the nvidia opengl driver lost connection with the display driver...", when using high resolutions. Is there a good way to do such calculations without having to tweak registry values? I want this to be able to work for other people too.

In essence I'd love if there was also a way to add something like a loading bar so that people don't think the program crashed or something.


texts: object position handling for multiplayer a game

texts:
I am creating a multiplayer HTML game which focuses on manipulating planet trajectories with gravity points. I am creating bunch of planets with random initial velocity and random direction and i am sharing info about this planets
to a server. Though i am keeping track of every planets position on server, i am not sharing this values every second to each player. My idea  is that if i only share planets position whenever a new player joins then from that point onward clients should be able to calculate new position of planet every second because directions and speed of the planets will be same for all players.
This idea works for screens with same resolutions and aspect ratio but it fails for other cases.

can anyone suggest other idea for keeping track of planets position for screen with resolutions?

This game is multiplayer so i need something that will allow me to provide same scene to every player.


texts: Scale Matrix Transform without moving primitive

texts:
So I have the following....

GLbyte vShaderStr[] =
  "attribute vec4 vPosition;    \n"
  "uniform mat4 move;           \n"
  "uniform mat4 scale;           \n"
  "void main()                  \n"
  "{                            \n"
  "   gl_Position = vPosition;  \n"
  "   gl_Position = move * gl_Position;  \n"
  "   gl_Position = scale * gl_Position;  \n"
  "}                            \n";
...
void glScale2D(float y, float x){
float zoom[16] = {
    x, 0, 0, 0,
    0, y, 0, 0,
    0, 0, 1, 0,
    0, 0, 0, 1
};
GLint projectionUniform = glGetUniformLocation(userData.programObject, "scale");
glUniformMatrix4fv(projectionUniform, 1, 0, &zoom[0]);
}
...
glScale2D(userData.widthScreen/userData.heightScreen, userData.heightScreen/userData.widthScreen);

This works, however, it also moves the primitive so it goes from...

To...

Is there a matrix I can use to scale the primitive without moving it?


texts: How to stop an anmation and a loop in relation to a timer? Phaser javascript

texts:
I am not ajavascript or phaser expert, I just got stuck with this problem.
I'll try to explain it.
In  this game; is a 21 second timer in all this:  which starts AFTER a beginning 3 second animatiton.

var maxTime = 21; //in SECOND

There is a wheel (station) that spins over and over (loops) and scales up and down:

var init_station_scale = 0.5;
var scale_station = 0.40;

When the game resets the station (wheel) resets

function resetGame(){

station.scale.setTo(init_station_scale);

//station(middle anchor point).

  station = game.add.sprite(750,195,"station");
  station.anchor.setTo(.75,.75);
  station.scale.setTo(init_station_scale);
  station.animations.add("anim"); //Init animations
  station.animations.play("anim",15,true);  //play Animations "anim" with 30fps, loop true

Not to confuse you, but there is a lot going on in this 21 seconds, such as:

//hint  (this is hooked up with the station (wheel)

      hint = game.add.sprite(game.world.centerX+50,game.world.centerY+100,"hint");
  hint.anchor.setTo(0.5);
  hint.animations.add("anim");
  hint.animations.play("anim",15,true);
  hint.visible = false;

Playing a 3 second animation that only plays once at the very beginning of the game (including if game resets);
also starting
.play ("anim",15, true); //(above (station/wheel) code and looping it)

after that 3 second animation;
    console.log("FINISH ANIMATION and ADD TIMER");  TIMER is referring to the 21 second timer

timerEvent = game.time.events.add(Phaser.Timer.SECOND * maxTime,  moveToEndGame, this);  //(also the 21 second timer)

function moveToEndGame(){
  console.log("TIMER END");
  var twn = game.add.tween(bg).to({alpha:0},tween_speed,"Linear",true);
  twn.onComplete.addOnce(function(){flagGameover = true;},this);
}

 if(!flagGameover && !star.visible && idx_bullet < bullet_array.length)
        initBullet();
      else{
        if(flagGameover){
          console.log("GOTO GAMEOVER");
          window.location = "../EndGame.html";
        }
      }
    }

  }

Everything works up until the end of the 21 second timer, but station/wheel keeps spinning creating an 'infinite loop"
So there is nothing to stop the 'loop in the station"  after the 21 second timer finishes.  Coder left out a line that would do that?
Some line of code needs to be added to that last block of code (or somewhere else?)to stop the loop on the station timed with the end of the 21 second timer.  I think????

Or  some kind of javascript kill switch:  i.e. stop all javascript then go to endgame.html

Anyone know the answer?


texts: 2d animation on html5 canvas using a vector and speed

texts:
Im moving a starship from one location to the other. In creating a vector, normalize and magnitude it.

Lets assume my vector looks like this

Vector
    x: 156,
    y: -90,
    m:  180.0000000546,
    nx:  0.8661855860486004,
    ny: -0.49972245348957717,

The way im animating the ships movement currently is:

            if (! action.animated){
                if (action.type == "move"){
                    if (game.ships[i].actions[j].v.m > 0){
// v is the Vector above !
                       game.ships[i].x += action.v.nx;
                       game.ships[i].y += action.v.ny;
                       game.ships[i].actions[j].v.m--;
                    }
                    else {
                       game.ships[i].actions[j].animated = true;
                    }

So basicly, im using requestanimationframe and a loop to move the starship by what equals 1 magnitude / 1 unit length (px) per frame.
So far it is working (but for the fact that the vessel animates one more magnitude than it should).

However, assuming i have two starships and one has a vector magnitude of 180 while the other has a magnitude of 200 and im animating both at the same time, how can i create an animation that will move the faster starships quicker, i.e. both starships should begin moving and end moving in the same frame ?


texts:
Assume a left-handed coordinate system where x is right, y is up, and z is into the screen. You have a unit vector pointing up along the y-axis. What's the rotation matrix for pointing the unit vector along the y-axis to an arbitrary point p?
I was asked this question during a phone screen. The interviewer implied there's an easy way to get this rotation matrix by "dropping in" a few values. I'm reading a 3D math book hoping to find this easy way but no luck yet. The ways to get this matrix in the book all seem too long to recite over the phone during an interview.
I think I can see part of the solution. The rows of the matrix are the post-transformation basis vectors. So the middle row of the matrix is just the point p possibly normalized (since that's where the y-axis will be post-rotation).
Any help with this easy "drop in" way of getting the rotation matrix is much appreciated!
Edit: If it seems like the problem statement is missing information please call it out. I feel like I remember the interview clearly but I could have left something out (or the interviewer could have).


texts: Unreal modular character tutorial errors

texts:
I'm trying to follow the modular character tutorial for Unreal from this link
Specifically the mesh merge portion. How ever the code that is provided seems to not be working.
For example when I add this piece of code :
USTRUCT(BlueprintType)
struct VR_API FSkelMeshMergeSectionMapping_BP
{
    GENERATED_BODY()
        UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Mesh Merge Params")
        TArray<type> SectionIDs;
};

I get the following error : Unrecognized type 'type' - type must be a UCLASS, USTRUCT or UENUM
I;m guessing I should provide a certain type in the <> but I have no idea what it should be. I've been using unreal only for 2 days now so if anyone can help me figure this tutorial out and get it working I would be thankful.


texts: What are the consequences of adding a progress stat to a live Steam achievement?

texts:
Say I have an achievement in my game, "Collect your first thingamajig", and I publish this to the live version of the game without a progress stat. Later on I decide I want to add some new achievements in an update, including one based on the previous achievement: "Collect 10 thingamajigs".

I create a progress stat for this one which is updated in code, but I also edit the original achievement so that it's unlocked through the progress stat rather than an AwardFirstThingamajigAchievement() function in code.

What are the consequences of this? Will a player that already had this unlocked find the achievement has been relocked because the achievement has been edited, technically making it a new one? Will it remain unlocked, but still cause a little popup for the first achievement on the next Thingamajig collected? Or will Steam simply not touch already unlocked achievements?


texts:
I've been reading many papers about how to voxelize meshes using different GPU techniques, but I've ran into a problem that I'm not sure how to solve properly.  I understand the process of how to convert a 3D mesh into voxels stored in a 3D texture, but I don't know a very efficient way to display the voxelized mesh after this.  Many of the papers I have read gloss over this part.

The one way I can think of accomplishing this is to draw an instanced cube, one for each voxel.  Each instanced cube would have texture coordinates that correspond to it's location in the 3D texture.  Every instanced cube would also go through a geometry shader.  If the texture's entry at the current coordinates was 0 (empty voxel), then the geometry shader simply wouldn't output any triangles.

Is this an efficient method/good idea?


texts: Ideal way to instantiate abilities in a class give a dynamic list of abilities to use?

texts:
I have a PlayerClass class that is used to set my Player's class. For instance, this will make him a warrior:

 PlayerClass warrior = new WarriorClass();

WarriorClass will instantiate abilities like so:

 Ability ability1 = new LeapAbility();

Now my problem is that I will eventually dynamically update my Warrior's abilities (think talent trees or perks).

So say I give warrior a list of abilities to use. How do I do this in code? Right now I need to know the Abilities before hand and hard code their instantiation in.

Put another way, how do I instantiate a dynamic list of objects? I'm open to other solutions too if this doesn't make sense or is impossible.


texts: Advice creating build process for medium sized game project

texts:
I've been looking through the SCons build script for Doom3 and researching different approaches to build processes used by professional game developers/studios (C/C++) and I've come across a few questions:

When creating a build script (scons/make file etc.) is it used every build when coding within an IDE like say Visual Studio? In other words do you tend to just use the tools in Visual Studio (Project files etc.) when you want to test a small code change? Or do you step outside VS and run the scripts to get the project to a point that it can be run?
An extension of question 1, if you use VS entirely for these kinds of builds, how far do you take it? i.e. do you have it copy the game into a folder with all the assets or run any kind of install scripts?
If your feeling generous could anybody give me a quick overview of the kind of things you're including in your build steps? Asset creation/install scripts/folder structure creation etc.

Many thanks all.


texts: How should i have the key/mouse input in an advanced java game?

texts:
I am a self taught programmer, so I do not know the proper ways to do things. I have made simple games like asteroids and snake, but in those games, you can easily modify the variables within the keyevent functions. Here is how I did it in my simple Asteroids game:

/*
* key listener events
*/
public void keyReleased(KeyEvent k){
    int keyCode = k.getKeyCode();

    switch(keyCode){

        case KeyEvent.VK_LEFT:
            turnLeft = false;
            break;

        case KeyEvent.VK_RIGHT:
            turnRight = false;
            break;

        case KeyEvent.VK_UP:
            accel = false;
            break;

        case KeyEvent.VK_1:
            cls = true;
            break;
        case KeyEvent.VK_ENTER:
            break;
        case KeyEvent.VK_SPACE:
            fire = false;
    }
}
public void keyTyped(KeyEvent K){}
public void keyPressed(KeyEvent k){
    int keyCode = k.getKeyCode();

    switch(keyCode){

        case KeyEvent.VK_LEFT:
            turnLeft = true;
            break;

        case KeyEvent.VK_RIGHT:
            turnRight = true;
            break;

        case KeyEvent.VK_UP:
            accel = true;
            break;

        case KeyEvent.VK_1:
            cls = false;
            break;
        case KeyEvent.VK_ENTER:
            clearAllBullets();
            break;
        case KeyEvent.VK_SPACE:
            fire = true;
    }
}

If I were to make a more advanced game (with a main menu, options, main game, etc.), how should I do the key/mouse input?

Also, if I were to go into the single-player, should i put all of the gameplay code into one class? Is there a way to put the single player code into a separate class and somehow have the key input still modify the variables and such?


texts: Why does accessing ParticleSystem.IsAlive() raise this error?

texts:
I am trying to record if my particle system IsAlive with:

GameObject prefab = Instantiate (Prefab, myPosition, Quaternion.identity) as GameObject;

Component ps = prefab.GetComponent<ParticleSystem> ();
bool checkIfPSPlaying = ps.IsAlive ();
//bool playing = prefab.GetComponent<ParticleSystem> ().isPlaying // This works fine

The code above gives this error:

error CS1061: Type UnityEngine.Component does not contain a definition for IsAlive and no extension method IsAlive of type UnityEngine.Component could be found

What am I doing wrong?


texts: How do I change the sprite used for an object, while the game's running?

texts:
Engine Used: Gamemaker Studio

I want to be able to swap between two armors on the player character. They've each got their own unique animation / general sprite stuff. How do I "equip" the second armor while the game is running? Is there even a way?

Do I need to destroy the object, and instead replace it with a different object that just has a different sprite?


texts: I am creating an open-world in Unity 4.5.5 and I do not know how to make the clouds move. This video of The Legend of Zelda: Wind Waker HD is a perfect example of the clouds moving in the sky. How can I create this?


texts:
I'm developing an application for iPhone with a screen where the user will track his progress. Something like so, as seen in the Two Dots game:

Currently I plan on creating this using constraints and size classes. But I feel its too much of work for each screen size. I've set a background UIImageView and I place different circles, manually hardcoding the position. The curved path in my case is made of a texture. So I can't plot it using Bezier Curves either.

Is there an easier way to do it? Perhaps using SpriteKit or Cocos2D-x?


texts: What's the difference between Gameplay Programming and Graphic Programming?

texts:
I know the answers are obvious, someone told me this:
Graphics Programming: DirectX(or Direct3d), OpenGL, Vulkan, Metal..

Gameplay Programming: Bringing everything together. From design, music, levels, etc.

But could you please explain me in depth the difference?
This way i can focus on a specific role in game programming!


texts: How can I loop through pixels in the material editor?

texts: I am using Unreal Engine 4, and I want to try to procedurally generate a grass texture. For now, I am using a noise block. Now I want to loop through every 16 pixels or whatever (4x4 squares), take the average color of those pixels, and make that all one "pixel". I don't see any for loops, loops, etc. in the pallete though. Can you not do this with the material editor? Thanks.


texts: Mirror Create Player From Client and Change Scene

texts:
I'm very new to Mirror in Unity but I have a lot of experience in Network-programing.
I'm currently trying to create a Game, where the Player's data is stored on the client, and can join different games (not concurrent) with his/her character. (Likely to Terraria)
So I can't use the automatic Player creation of the default NetworkManager class. After clicking "Join/Host" in our Main-Menu I want to change to the scene the player has played in, Hosting/joining a server and create the player on the server with the specific position...
I have tried now multiple attempts to do this, but none of mine seemed to work.
Am I the even possible to have the players in different scenes with ease?
Where/When should I create the Player so isn't null on the Server?


texts:
I'm working on a boggle type game for android, using libgdx. The user is presented with a 4x4 grid of letters and must find words by dragging their finger over the letters.

Unlike boggle I want used letters to disappear. Remaining letters will fall down (to the bottom of the board, screen orientation is fixed) and the board is refilled from the top. Users can rotate the board to try and put hard to use letters in a better place by strategic word selection.

An example:

d g a o
u o r T
h v R I
d G n a

If i selected the word GRIT, those letters would disappear and the remaining fall down:

d
u g a
h o r o
d v n a

and then get replaced by new letters

d w x y
u g a z
h o r o
d v n a

I'm stuck figuring out how to represent the board and tiles.

I tried representing the board as a matrix to keep track of tiles selected and valid moves and the tiles stored in a matrix as well so that there was an easy mapping. This works, but I had to write some convoluted code to rotate the board.

How do other games handle this problem?

EDIT:
So thinking about it, I should really just process my touch point according to the board rotation so cells stay constant. Attached an image of what I'm thinking.


texts: Spawning Object 1 Within Object 2's Collision Box [Gamemaker]

texts:
I was wondering if any of you could help me with a specific Gamemaker question. Am using Gamemaker Studio.

I have an object (oSpecialSolid) which rotates and moves across my level. At random intervals, another object (oEmitter, an animated spark or flash of smoke) spawns somewhere within the x and y of oSpecialSolid, give or take 45px.

Unfortunately, oSpecialSolid has some transparent areas (the sprite is not perfectly rectangular, and has empty space at either side) where I would not like the oEmitter to spawn. However, as the object spins, I cannot tell if the x and y values that I am telling it to spawn in will be transparent or not in that moment. I would also like the oEmitter to spawn anywhere on the oSpecialSolid object,not just in a 45 x 45px box in its centre.

What I am looking for is a method of telling oEmitter to only spawn within the collision box of oSpecialSolid. Is there a way to do this? I am using the precise settings for collision.


texts: Creating an Isometric tile map with HTML5

texts: I'm trying to create an isometric tile map using HTML5 Canvas.  Everything I've found online points me towards using a pre-built engine.  I'd like to learn how to do this without using an engine.  Is it possible to do this?  If so, how?  Would I need to look into WebGL?


texts: Do Unity bunch up similar materials automatically?

texts:
Imagine I have materialA and materialB.

materialB is a direct copy of materialA with only a name change.

Does Unity recognize these as same materials due to their identical settings or process them as several materials?

Do they go to the GPU as bunched up(good) or solo(bad)?


texts: Online Identification for Desktop Games?

texts:
What methods are there for providing means of authentification for multiplayer?

A few thoughts:

I don't want to be restricted to a single publishing platform such as Steam.
Something like OpenID would be great, but OpenID itself seems to be limited to the world wide web.
It shouldn't be anything cryptic, so if you know the email or the user name of your friend you should be able to find him with that.
People shouldn't be required to create a additional account just for this one game.
OCS could be used for something like this but afaik it's not supported by any big vendor. So it would be somewhat useless.
Things like querying what the players friends are are optional.


texts: How to efficiently handle registration/anchor points for graphics?

texts:
I am currently working on an iPhone project, but most of my work has been in Flash. Flash has a feature where you can place a bitmap into a MovieClip, set its registration point with the mouse and it's automatically adopted. It's one of the lovelier Flash features.

Now I'm doing iPhone stuff, using TexturePacker for importing the graphics, and I'm having to write code like this:

if(graphic == "spikes1") setAnchorPoint(ccp(1, 0));
if(graphic == "spikes2") setAnchorPoint(ccp(.5f, 0));
if(graphic == "spikes3") setAnchorPoint(ccp(.5f, 0));
if(graphic == "spikes4") setAnchorPoint(ccp(.5f, 0));

if(graphic == "bush-a") setAnchorPoint(ccp(.5f, .25f));
if(graphic == "bush-b") setAnchorPoint(ccp(.5f, .25f));

if(graphic == "tree1") setAnchorPoint(ccp((float)134/209, (float)34/202));
if(graphic == "tree2") setAnchorPoint(ccp((float)96/236, (float)31/184));

I can obviously use macros or functions to shorten this a little, but is there a more intelligent way to go about this?

How do professional platformer games (on consoles and PC) handle this?


texts:
I need to implement tickrate into my engine to handle timed events such as pushing out entity updates and I don't know where to start.

I have access to a timer which allows me get the time in milliseconds since the device has been initialized.

When I try to brainstorm on the correct approach to take one of the main things that I get stopped up on is that on the client side I should allow the framerate to run as fast as it can, however if I want the tickrate to run at 60 and the client FPS is less than 60 how can 60 ticks execute if the main loop wont run at least 60 times a second due to it being slowed down by the fps?

Can anyone explain how to properly implement tickrate? Thank you for your time.


texts: Developing an iOS/Android game with the free Unity license - feasible?

texts:
I recall, when I looked up the Unity license comparison page several months ago, seeing that some iOS/Android features were disabled for the Free license. However I can't seem to find that page now, all I can find is http://unity3d.com/get-unity which isn't platform-specific.

But the Pro Android and Pro iOS licenses still exist, which means that there is SOME difference. I already know of the revenue limit and the mandatory Unity splash screen for Free. But are there any other differences? Notably, anything that would really impact the game's performance or flexibility?

Are there any serious iOS and Android game developers who use the Free license?


texts: Why does a 3D scene need to be voxelized before it can be transformed into a navmesh?

texts:
Why do solutions such as Recast voxelize a 3D scene before transforming it back into polygons?
Would it not be possible to just determine intersections of meshes, check for slope angles and adjust triangulations in that way? I think agent height problems could also be solved by testing sweeps upwards against the other meshes.


texts: How to define data for an input sequence game?

texts:
I'm starting to program my very first game, it's a clone of DDR/Stepmania done for research purposes and learning.

I (at this early stage) get most of the UI/Music/input work that should be done, but what i still can't grasp is scripting, i've read about Lua and that you shouldn't use it with XNA/Monogame as C# is capable enough, but i cannot get the utility of it.

Assuming the needs of my game, What would be the ideal way to implement the input sequences it needs?, i thought of XML/Json, let's say Stage 1

<game>
 <level id="1">
  <step id="1" key="up" time="00:00:01"/>
  <step id="2" key="left" time="00:00:02"/>
 </level>
</game>

Is that a correct implementation? or are there better ways with more benefits?


texts: Rendering two textures with blending and alpha test

texts:
What I am looking for is the following: I have a circle on a square image, alpha is 0 at the corners

and also a square shadow, alpha is 0 everywhere else

I would like to have as final result a blending of these two renders, plus the shadow not being rendered outside the circle

How could I achieve that?


texts: libgdx draw/animate curve (tentacle) according to Box2D spring wavering

texts:
The horizontally placed Box2D spring is made of distantJoint connected bars, and can bend up and down just like airplane wing does when you flight (bigger amplitude thou).

Ok, the physics part works, but how do I pull on a sprite/texture to have a smooth curve when it bends and waves in box2D?

Even if I compose the picture out of small bars, and spring bends 90 degrees down, there are whitespaces on the top of the spring where it is unclamped and messed up down part where it is compressed.
I wasn't able to beat this even for solid color tentacle, but what if there should be a nice picture of an octopus tentacle?

Can you please give a hint how the outer skin e.g. in this game
 implemented https://youtu.be/nakjRosCeH8?t=10 ? It is waving smooth curve, just like I need.
Thanks.


texts: Does decreasing rendering resolution also decrease the amount of polygons in my 3d models?

texts: When lowering my game resolution I reduce the pixel count of the final rendered output image, does the 3d model I use to render the final image also lose polygons?


texts: Rotate final image with projection matrix

texts: I'm trying to use space in my shadow (depth) maps in a more efficient way. If I could freely rotate the final image I get with projection matrix I could save a lot of pixels, but I don't know if it is possible to do so. Is it?


texts:
I want to show the current health and stamina of the player using GUI.Label. All is working fine however it shows the values with decimals to the millionth (example: http://gfycat.com/SkeletalSinfulKouprey). How would I go about showing only the whole number?

My code:

 var cur_stamina : float;
    var cur_health : float;

    var staminaRegenRate : float = 5;
    var healthRegenRate : float = 1;

    //regen
    if(cur_stamina < max_stamina){
        cur_stamina += staminaRegenRate * Time.deltaTime;
    }
    if(cur_health < max_health){
        cur_health += healthRegenRate * Time.deltaTime;
    }

    function OnGUI(){
        GUI.Label(Rect(1,1,100,20), "Health: " +cur_health);
        GUI.Label(Rect(1,15,1000,20), "Stamina: " +cur_stamina);
        GUI.Label(Rect(1,30,100,20), "Ammo: " +cur_ammo);
    }


texts: How can I scale my UI elements to the lesser screen dimension in Unity 5?

texts:
I want to create a custom mobile pad for my game. The mobile pad consists of two parts (both inside an ui canvas):

The D-Pad, which will be anchored to the bottom-left side.
The button group will be anchored to the bottom-right side.

I would like to resize the element on different resolutions, so that the element (in my case, the D-Pad is an image):

Has a size of 20% of the minimum of the width and the height.
Has pivot of x=0.5, y=0.5.
Having anchor of left-bottom, its coordinates are (15%, 15%) wrt the minimum of the width and the height.

What I tried is to use an Aspect Ratio Filter in the D-Pad image with ratio=1, but it did not work as intended (the coordinates led the image to an unexpected place).

Note: I am a n00b to Unity. I don't know whether it is right but my Canvas Scaler scales by Constant Pixel Size

These images should illustrate what I want to achieve:

What should I do to make it work like in the pictures?

Edit I attached this behavior, based on answer, to handle the change by runtime:

[RequireComponent(typeof(UI.CanvasScaler))]
class CanvasSmartScaler : MonoBehavior {
    private CanvasScaler _scaler;
    void Start() {
        _scaler=GetComponent<CanvasScaler>();
    }
    void Update() {
        //OMITTED CODE: here I set the scale mode as in the Editor but right now i am in my mobile device and cannot remember the exact lines
        if (Screen.currentResolution.width < Screen.currentResolution.height) {
            _scaler.matchWidthOrHeight=0;
        } else {
            _scaler.matchWidthOrHeight=1;
        }
    }
}

And attached that behavior to the canvas. However, for my debug exe (just for debug purposes) it always picks the 1-case regardless how do I resize the window. What am I missing?


texts: Creating “Run over by car” effect in unity using spotlights only

texts:
I'm doing a project where I need to simulate a car running the character over. It's happening in a completely dark space, so I want to create it using spotlights moving towards the camera until the screen gets completely white.

To create this "bright light" effect, I use volametric lighting on 2 spotlights:

But when I start moving the spotlights towards the player, the spotlights start moving away from each other (Which makes sense, and can be fixed somewhat by increasing the SpotAngle/Range by code while the spotlights are moving).

However, when the spotlights get to right in front of the player, they disappear before making the screen completely white. I could use a fade-in complete white screen transition, but this complete method seems extremely clunky. Is there another, better way, or maybe a simpler fix to my spotlight moving closer issue?


texts: What is a good free "game development organisation" site?

texts:
I'm searching for a site that will help me to design a game. I don't have a development team in the same location. They are all located somewhere over the world. I am searching for a kind of site that allows people to post ideas and suggestions, but moreover to have control over who has the control over what. For example, one makes the graphics and has several people "under" him that can get a certain task to make a certrain graphic. This has to be easily found on this site.

Does anyone know a good site like this? I prefer it to be free.


texts:
I am making a prefab of a simple building by combining sprites. As you can see in the Hierarchy view, this simple building is composed of very many gameobjects which I created via dragging sprites into the scene/Hierarchy and then manually editing their coordinate positions.

Is there a simpler way of doing this? I feel that the process of creating this building consumed too much time I could spend on other aspects of development. If this is the only way, then in what ways could I optimize my workflow?


texts:
I would hope that we have all played Zelda: A Link to the Past, please correct me if I'm wrong, but I want to emulate that kind of 2D, top-down character movement with a touch of correction. It has been done in other games, but I feel this reference would be the easiest to relate to.  More specifically the kind of movement and correction I'm talking about is:

Floating movement not restricted to tile based movement like Pokemon and other games where one tap of the movement pad moves you one square in that cardinal direction. This floating movement should be able to achieve diagonal motion.
If you're walking West and you come to a wall that is diagonal in a North East/South West fashion, you are corrected into a South West movement even if you continue holding left (West) on the controller. This should work for both diagonals correcting in both directions.
If you're a few pixels off from walking squarely into a door or hallway, you are corrected into walking through the hall or down the hallway, i.e. bumping into the corner causes you to be pushed into the hall/door.

I've hunted for efficient ways to achieve this and have had no luck. To be clear I'm talking about the human character's movement, not an NPC's movement. Are their resources available on this kind of movement? Equations or algorithms explained on a wiki or something?

I'm using the XNA Framework, is there anything in it to help with this?


texts: Port sandbox flash game to Android and iOS

texts:
I'm want port my sandbox game to Android and iOS. Game written in AS3 (i'm use my simple 2d engine on stage3d). What do you recommend I use?

Haxe + OpenFL
MonoGame + Xamarin (C#), or other 2D engine in C# for mobile?
LibGDX + robovm (Java)
or AIR? It's slowly (seems).

I'm know C#, but don't know Haxe and Java. Game render many sprites: tiles (walls/blocks/liquids), background, entities, particles + lighting system.

My game: http://www.youtube.com/watch?v=y_KbvZCljnA


texts:
I'm in my last year of high school, and I've been looking at colleges. I'm taking a C++ class at a local community college and I don't feel that it's worth it. I could have learned everything in that class in a week.

This had me thinking, would a CS degree even be worth it? How much can it teach me if I can learn everything on my own? Even if I do need to learn more advanced subjects, many colleges put their material online AND I can buy a book. Will companies hire me if I don't have a CS degree? If I have a portfolio will I stand a chance? What kind of things are needed in the portfolio?

I want to live doing what I love - programming. So I will do it. I'm just not sure that a CS degree will do anything to me. In addition, if there is a benefit to getting a CS degree, what places are the best?


texts:
I am working on a 2D engine in Xna and am running in a bit of trouble with Collision implementation.
What I want to do is have an interface ICollidable that I can add to GameObjects that are collidable.
I am trying to get it to work by using this awnser: https://gamedev.stackexchange.com/a/40432/33751

My question is how do I add the objects that use ICollidable to the List in the CollisionManager dynamically?

By case would be that the manager 'sees' what objects use the ICollidable interface and automatically add it to the list.

Second question is, how can I get the properties and stuff from the objects that contain the interface to actually preform the collision detection in CollisionManager? would a simple cast suffice?

ICollidable:

interface ICollidable
{
    void onCollision(ICollidable other);
}

CollisionManager:

class CollisionManager : GameObject
{

    private List<ICollidable> collidables = new List<ICollidable>();

    public CollisionManager(Game game)
        : base(game)
    {
        game.Components.Add(this);
    }

    void addCollidable(ICollidable obj){
        // This function needs to be called when ICollidable is inherited dynamically
        collidables.Add(obj);
    }

    public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
    {
        base.Update(gameTime);

        for (int i = 0; i < collidables.Count; i++)
        {
            for (int a = i + 1; a < collidables.Count; i++)
            {
                if(collision(collidables[i], collidables[a])){
                    collidables[i].onCollision(collidables[a]);
                }
            }
        }

    }

    private bool collision(ICollidable obj)
    {
        // How can i get obj's properties etc for checking collision.

        return false;
    }
}

PS. Never worked with interfaces in c# before, if I am doing it completely wrong, please let me know

Thanks in advance.
Yme-Jan


texts: How can I optimize this flood fill algorithm?

texts:
I'm creating a sprite and animation editor like this one. I'm having performance issues with my flood-fill algorithm.

Basically, I open an image with the different modules that are part of a frame of an animation. When I double-click a module I run a depth-first search algorithm that checks all the pixels of that part of the image that are surrounded by transparency. From that I get the rectangle of said module (the position and size). With large images, when I double-click that part of the image the application freezes.

How can I improve my algorithm?

Right now what I do is maintain an array of already-checked pixels and a list of pixels to check. I start with the pixel that I double-clicked and check if the surrounding pixels have transparency. If they do not, I check for the surrounding pixels of those pixels and so on until all the surrounding pixels are transparent. Then I can get the minimum and maximum position in the X-axis and Y-axis and use that to construct the bounding rectangle of the frame.

This is my code:

private Rectangle widthSearch(int posX, int posY)
{
    Rectangle result = new Rectangle();
    int leftX, topY, rightX, botY;
    leftX = rightX = posX;
    topY = botY = posY;

    List<Point> closedList = new List<Point>();
    List<Point> toProcessList = new List<Point>();

    Point processingNode;
    Color colorAux;
    int alphaAux;
    int offsetX = 0;
    int offsetY = 0;

    toProcessList.Add(new Point(posX, posY));

    int[] dx = { 1, 1, 0, -1, -1, -1, 0, 1 };
    int[] dy = { 0, -1, -1, -1, 0, 1, 1, 1 };

    while (toProcessList.Count > 0)
    {
        processingNode = toProcessList.ElementAt(0);
        closedList.Add(processingNode);
        toProcessList.Remove(toProcessList.ElementAt(0));

        for (int i = 0; i < dx.Count(); i++)
        {
            offsetX = dx[i];
            offsetY = dy[i];
            try{
                if (!closedListContains(closedList, processingNode.X + offsetX, processingNode.Y + offsetY) && !closedListContains(toProcessList, processingNode.X + offsetX, processingNode.Y + offsetY))
                {
                    colorAux = bmp.GetPixel(processingNode.X + offsetX, processingNode.Y + offsetY);
                    alphaAux = (colorAux.ToArgb() >> 24) & 0xFF;
                    if (alphaAux > 0)
                    {
                        toProcessList.Add(new Point(processingNode.X + offsetX, processingNode.Y + offsetY));
                    }
                }
            }
            catch (Exception e)
            {
                Console.Write(">>>>>>>>\n" + e + "\n>>>>>>>>>");
            }
        }
    }

    for (int i = 0; i < closedList.Count(); i++)
    {
        if (closedList.ElementAt(i).X > rightX)
            rightX = (int)closedList.ElementAt(i).X;
        if (closedList.ElementAt(i).X < leftX)
            leftX = (int)closedList.ElementAt(i).X;
        if (closedList.ElementAt(i).Y < topY)
            topY = (int)closedList.ElementAt(i).Y;
        if (closedList.ElementAt(i).Y > botY)
            botY = (int)closedList.ElementAt(i).Y;
    }

    result.X = leftX;
    result.Y = topY;
    result.Width = rightX - leftX;
    result.Height = botY - topY;

    return result;
}

private Boolean closedListContains(List<Point> closedList, int posX, int posY)
{
    Point pointer = new Point(posX, posY);
    for (int i = 0; i < closedList.Count(); i++)
    {
        if (closedList.ElementAt(i).Equals(pointer))
            return true;
    }
    return false;
}

I only call the widthSearch() method when I double-click a PictureBox. It is not inside a loop.


texts:
I tried to bind a bitmap texture. This bitmap is BGR format, and I'm trying to use
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data), but during compile, error: 'GL_BGR' undeclared appears.

I checked <GLES2/gl2.h> and <GLES2/gl2ext.h>, but there isn't any GL_BGR
. Is there any way to upload BGR format?


texts:
I'd like to get a better handle on how people in the real world are handling their animation.

Do you load 1 large image and then draw different rectangles based on the animation frame?

Do you load X image files into an array and draw the item in the array based on the animation frame?

How do you handle having different lengths of animations for various sprites.

Say a character walking takes 4 - 8 frames, and the waves on the beach only take 2 - 3 frames. How would you handle that situation? See Below

Dim Waves(1) as Sprite
Dim Char(5) as Sprite

Sub Animate()
     Frame += 1
     Draw Char(Frame)
     Draw Waves(Frame)
     If Frame = 5 Then Frame = 0
End Sub

Obviously Waves would end up with an out of bounds error.

Or do you have your sprite worry about it's own animation, and not care about the frame at all. Having each sprite know its own animation loop?


texts:
I'm making a single-screen scrolling platformer (OpenGL/SDL) and I've made a tilemap out of a 2D array, pre-sized with variables of the LEVEL_HEIGHT and LEVEL_WIDTH.  Each element in this 2D array corresponds to a position in the spritesheet that I'm loading from. In my render function, I have the following code to iterate through the matrix,and put each element into a 1D vertex buffer:

for (int y = 0; y < LEVEL_HEIGHT; y++) {
        for (int x = 0; x < LEVEL_WIDTH; x++) {
            if (levelData[y][x] != 0) {
                float u = (float)(((int)levelData[y][x]) % SPRITE_COUNT_X) / (float)SPRITE_COUNT_X;
                float v = (float)(((int)levelData[y][x]) / SPRITE_COUNT_X) / (float)SPRITE_COUNT_Y;
                float spriteWidth = 1.0f / (float)SPRITE_COUNT_X;
                float spriteHeight = 1.0f / (float)SPRITE_COUNT_Y;
                float vertices[] = {
                    TILE_SIZE * x, -TILE_SIZE * y,
                    TILE_SIZE * x, (-TILE_SIZE * y) - TILE_SIZE,
                    (TILE_SIZE * x) + TILE_SIZE, (-TILE_SIZE * y) - TILE_SIZE,
                    TILE_SIZE * x, -TILE_SIZE * y,
                    (TILE_SIZE * x) + TILE_SIZE, (-TILE_SIZE * y) - TILE_SIZE,
                    (TILE_SIZE * x) + TILE_SIZE, -TILE_SIZE * y
                };
                GLfloat texCoords[] =  {
                    u, v,
                    u, v + (spriteHeight),
                    u + spriteWidth, v + (spriteHeight),
                    u, v,
                    u + spriteWidth, v + (spriteHeight),
                    u + spriteWidth, v
                };
                glBindTexture(GL_TEXTURE_2D, sSheetIds[0]);
                glVertexAttribPointer(program->positionAttribute, 2, GL_FLOAT, false, 0, vertices);
                glEnableVertexAttribArray(program->positionAttribute);
                glVertexAttribPointer(program->texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords);
                glEnableVertexAttribArray(program->texCoordAttribute);
                glDrawArrays(GL_TRIANGLES, 0, 6);
                glDisableVertexAttribArray(program->positionAttribute);
                glDisableVertexAttribArray(program->texCoordAttribute);
            }
        }
    }

For some reason, when I run the code, the textures are overlapping between tiles. Consider the following example:

sprite sheet with tiles

2D Array for with the indices into the sprite sheet

int levelData[LEVEL_HEIGHT][LEVEL_WIDTH] = {
        { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 },
        { 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4 },
        { 4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,5,0 },
        { 0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0 },
        { 0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0 },
        { 0,5,0,0,0,0,0,6,6,6,6,6,6,6,6,0,0,0,0,0,5,0 },
        { 0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0 },
        { 0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0 },
        { 0,5,6,6,6,6,6,0,0,0,0,0,0,0,0,6,6,6,6,6,5,0 },
        { 0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0 },
        { 0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0 },
        { 0,5,0,0,0,0,0,6,6,6,6,6,6,6,6,0,0,0,0,0,5,0 },
        { 0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0 },
        { 0,5,0,0,0,0,0,6,6,6,6,6,6,6,6,0,0,0,0,0,5,0 },
        { 0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0 },
        { 0,5,0,0,0,0,0,6,6,6,6,6,6,6,6,0,0,0,0,0,5,0 }
    };

Tile map being rendered when the game is run

I've tried varying the size of each tile, but the textures just seem to scale up or down accordingly. I think the problem could be with the orthographic projection, but I'm not sure. What is causing the distortion here?

Here is the full code for reference


texts: Object transform rotation around correct pivot, but wrong pivot after colliding

texts:
I'm messing around a bit trying to create a table football table. So this involves create rods with players on them. The rod should be free to rotate around the Z axis with the players moving around the rods Z axis. I created a parent object for the rod with players to do any transforms on. I made sure that the pivot point is in the center of the rod so that rotating along the Z axis of the game object keeps the rod in its position while rotating. This worked as shown in the first picture, the object position remains unchanged while rotating.

The problem comes in when I run the game and have a ball collide with the 'player', this starts the player and rod spinning, but not around the right pivot point. The rod now moves in a circular/eliptical pattern. I checked that the rotation isn't happening around the center point either and it isn't. It rotates around an axis somewhere between the center point and the pivot point. Am I doing something wrong or am I tackling this from the complete wrong angle completely?


texts:
XNA seemed like a valid option a few years ago, but XNA was never a real success, and now it seems like a footnote, even Microsoft seems to treat it that way.

Should I just go the DirectX route instead?

Ideally, eventually, I'd like my games to be playable on all major platforms (Windows, Linux, Mac + all consoles), but my primary focus is getting the games out the door on Windows XP, 7 and 8.

EDIT: This question and releated might already be answered here: What is the future of XNA in Windows 8 or how will managed games be developed in Windows 8?


texts:
Say I have 4 buttons. I want to have button 2 always swap out with another button, randomly.
So, when the user taps button 2, it should swap with another button (randomly).

Now, button 2 is at the bottom right corner. So if the user taps button 2 again, it has the option to
swap with the other three buttons. How can I achieve this?

I have already tried to make an array of the four values:

top_right, top_left, bottom_right, bottom_left

And have successfully had them swap, but it was very memory inefficient, and took a while.


texts:
Hey guys I need some help I have 2 SkActions.
ball1.run(SKAction.moveTo(y: -self.size.height * 0.2, duration: 1.5))
ball2.run(SKAction.moveTo(y: self.size.height * 1.2, duration: 1.5))

and I want to randomize which one gets called I dont want to run a sequence and no clue how to do it. I've tried a switch statement and an enum but that didn't work.
this is what I have tried. so essentially when I move my player to the right it could be attacked form the top or the bottom.
switch swipeGesture.direction {

case .right:
bat.run(SKAction.moveBy(x: 50, y:0, duration:0.01))
    ball1.run(SKAction.moveTo(y: -self.size.height * 0.2, duration:
1.5)) || ball2.run(SKAction.moveTo(y: self.size.height * 1.2, duration: 1.5))

case .left:
bat.run(SKAction.moveBy(x: -50, y:0, duration:0.01))
       ball1.run(SKAction.moveTo(y: -self.size.height * 0.2, duration: 1.5)) || ball2.run(SKAction.moveTo(y: self.size.height * 1.2, duration: 1.5))

and it gives me an error: Cannot convert value of type 'Void' to expected argument type 'Bool'
If anybody know how to do so that would be great.


texts:
Whenever I change the maxDepth of the viewport from 1.0 to say 300.0f (just for kicks), everything on my screen disappears. Why is that? Is there anywhere else I have to account for this change in depth i.e. rasterizer?

PS: I tried values like 2.0 and 3.0 and still nothing.

Additionally, does this mean that the projectionMatrix is limiting my Z values to between 0 and 1.0 if the viewport#maxDepth = 1.0?


texts:
I'm trying to create a smooth moving 2d camera but the camera is shaking back and forth 1 pixel.

Player camera rectangle:

public Rectangle recCamPosition(Global global)
{
  return new Rectangle((int)Position.X, (int)Position.Y , 320, 240);
}

Camera rectangle:

public Rectangle recCamera(Global global)
{
  return new Rectangle((int)_pos.X / global.zoom, (int)_pos.Y / global.zoom, 320, 240);
}

The move method:

public void physic(Vector2 position, Player player, GameTime time, Global global)
{
  if(player.recCamPosition(global).X!=recCamera(global).X)
  {
    _pos.X+=(player.Position.X-160-recCamera(global).X)/16;
  }
}


texts: 5 Examples of game Development technology helping/using movie animation technology and vice versa

texts:
I wish to have information on the technology of game development say Unreal being used in the movie industry.
I also wish to have information on the technology of movie industry being used in the game development industry.

I guess there is a lot of similarity, yet a lot of differences between the games development industry and movie animation software industry. I have also seen companies related to the movie animation industry hiring Unity or Unigene or Unreal developers. I have also heard that models made in a specific software say Maya are used in the game development industry or vice versa. Please share a detailed information about this.

Please give 5 examples, where a certain movie house used game development technology or vice versa. Say for example, (hypothetically), Shrek being made in Unreal, etc.


texts: TextAsset thinks file is ~6856 bytes when it is 120123 bytes

texts:
So I've created a text asset in Unity of a binary file which i'm attempting to read in as a byte array.

The result I'm getting is a byte array tht is almost half the size it's supposed to be.

The file is a serialized mesh file from here: http://wiki.unity3d.com/index.php?title=MeshSerializer2

What I do then is find the file unity created, move it to the assets folder and drag it into a component as a TextAsset. For smaller files it works but larger ones appear to fail to load completely.

If I load the same file separately from a C# console application using filestream it loads correctly.


texts: LWJGL 3 - problem with flickering when rendering terrain with colors

texts:
For while now I m trying to built a terrain generator for my game engine and again I'm stuck with problem.

I'm trying to generate a terrain using colors, so no textures. In short my problem is flickering. Hope this pictures will describe better my problem.

The way I'm generating this is using shared vertices. If I'm generating 2*2 terraing, I'm actually only creating 9 points.
Something like this.

For color , I made that every second point will get slightly darker green.

When I add height generation, there is no flickering.

EDIT:
It probably got something to do with using shared points. I now tried using all unique points for each square and no flickering.

EDIT:
I found was the cause. I was generating indices wrong way.

    public void generateSharedIndices(int rowVertices,int columnVertices){
    for(int row = 0; row < rowVertices - 1 ; ++row){
        for(int column = 0; column < columnVertices -1 ; ++column){
            int leftDownPoint = ((row * columnVertices) + column);
            int rightDownPoint = leftDownPoint + 1;
            int rightUpPoint = rightDownPoint + columnVertices;
            int leftUpPoint = rightUpPoint - 1;

            addNewValueToCurrentPointer(leftDownPoint);
            addNewValueToCurrentPointer(rightDownPoint);
            addNewValueToCurrentPointer(rightUpPoint);
            addNewValueToCurrentPointer(rightUpPoint);
            addNewValueToCurrentPointer(leftUpPoint);
            addNewValueToCurrentPointer(leftDownPoint);
        }
    }
}

In the end indices should look like this
( 0  1  5  5  4  0  )
( 1  2  6  6  5  1  )
( 2  3  7  7  6  2  )
( 4  5  9  9  8  4  )
but I made mistake and it was generating them wrong.


texts: Creating a Melee Weapon in Box2D (libGDX)

texts:
I am struggling with how to implement a melee weapon that can swing when a key is pressed.

I am imagining two different attacks (stab and swing)

I have tried creating two fixtures (character + weapon), two different bodies, two different bodies + revolute joint, but I can not code it to behave the way I imagine it to look like.

STAB:

So with the press of a button, a body/fixture (sensor) would come out for ~1 second and then disappear (alternatively, the body/fixture could always be on the hero and just rotate 90 degrees around the vertices when pressed, and then rotate back to normal)

SWING:

Same thing, but now the weapon will start from the top and swing downwards. Weapon will also be a sensor.

What I have tried:

I created two dynamic bodies.

The weapon has to follow the hero, so I used a revolute joint to hold them together. When a key is pressed, I set the angular velocity of the weapon to a number. However, the weapon will continue to spin after I let go of the key. I tried implementing an if check (if angle is greater than ___, set angular velocity to zero). However, that just means the weapon will stop spinning when I press the key a second time.


texts: How to change a sprite via script at runtime when using an animator?

texts:
I am making a simple 2D shooter.
I have my character's body and head as different objects, as I want him to look up/down regardless of the movement.
So, I basically use the following script:
public class PlayerHead : MonoBehaviour
{
    public static PlayerHead instance;
    public SpriteRenderer theSR;
    public Sprite netural, down, up;

    private void Start()
    {
        instance = this;

    }
    public void Up()
    {
        theSR.sprite = up;
    }

    public void Down()
    {
        theSR.sprite = down;
    }

    public void Netural()
    {
        theSR.sprite = netural;
    }

}

However, the head is also used in the player animations:

This is because head must move with the body during the idle animation (breathing and moving up&down slowly).
I suspect that because of this animation, the sprite of the head is somehow fixed. It does not change in runtime even though I change it manually inside Unity.
How can I make the Animator let me change the sprite?


texts: Why does the platform created with for cycle go over the border limit?

texts:
ve started programming just recently and I've learned the basic concepts of classes and objects and how to create them. So I decided to try and create a simple game of breakout with what I've learned so far. I've only created the main movable platform with a for cycle and make it move horizontally with the directional keys so far. I've also created a void so the platform doesn't go over the border of the screen but it doesn't work and I've tried all I could think of. Can someone please tell me what I'm doing wrong?
 Game::Game( MainWindow& wnd )
    :
    wnd( wnd ),
    gfx( wnd )
{
}

void Game::Go()
{
    gfx.BeginFrame();
    UpdateModel();
    ComposeFrame();
    gfx.EndFrame();
}

void Game::UpdateModel()
{
    if (wnd.kbd.KeyIsPressed(VK_RIGHT))
    {
        platform.vx += 3;
    }

    if (wnd.kbd.KeyIsPressed(VK_LEFT))
    {
        platform.vx -= 3;
    }

    platform.ScreenLimit();
}

void Game::ComposeFrame()
{
    for (platform.x = 460; platform.x <= platform.w; platform.x++)
    {
        for (platform.y = 500; platform.y <= platform.h; platform.y++)
        {
            gfx.PutPixel(platform.x + platform.vx, platform.y, 255, 255, 255);
        }
    }
}

and here's the header file and source file of the class I created for the platform:
Platform.h
#pragma once
#include "Graphics.h"
class Platform
{
public:

    int x = 460;
    int y = 500;
    int vx = 0;
    int width = 60;
    int heigth = 10;
    int w = x + width;
    int h = y + heigth;

    void ScreenLimit();

private:

};

Platform.cpp
#include "Platform.h"

void Platform::ScreenLimit()
{
    const int left_base = x;
    const int right_base = w;

    if (right_base >= Graphics::ScreenWidth)
    {
        x = (Graphics::ScreenWidth - 6) - width;
    }
    else if (left_base <= 0)
    {
        x = 0;
    }
}


texts:
I have a strange problem with XNA 4. I'm constructing a SpriteBatch using this.spriteBatch = new SpriteBatch( GraphicsDevice );.
This leads to a memory leak up to 600 MB memory consumption.

This problem didn't exist two days ago.

I have a static class called Resources:

public static GraphicsDeviceManager gdm;

This gets set in the Game-constructor

public class Game : Microsoft.Xna.Framework.Game {
    public Game() {
        Resources.gdm = new GraphicsDeviceManager( this );
        Content.RootDirectory = "Content";
    }
}

In the Initialize-Method I'm creating a SpriteBatch in the Resources

protected override void Initialize() {
    base.Initialize();
    Resources.Game = this;
    Resources.spriteBatch = new SpriteBatch( GraphicsDevice );
}

At the point Resources.spriteBatch = new SpriteBatch( GraphicsDevice ); it allocates up to 600 MB memory.

Why is XNA allocating so much after I created a SpriteBatch? How can I fix it? (It worked two days ago and I didn't change anything that could cause this problem.)


texts:
Every time I try to attach my C# Script to my Player, it gives me this error message:

  "Can't add script component 'Player' because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match."

Here is my script, just for good measures

using UnityEngine;

using System.Collections;

public class Player : MonoBehaviour
{
    public float speed = 50f;
    public float jumpPower = 150f;
    public bool grounded;
    private Rigidbody2D rb2d;
    // Use this for initialization
    void Start ()
    {
        rb2d = gameObject.GetComponent<Rigidbody2D>();
    }

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

    }

    void FixedUpdate()
    {
        float h = Input.GetAxis ("Horizontal");
        rb2d.AddForce ((Vector2.right) * speed * h);
    }
}

I have no Idea how to fix that...

Anyway, I am using Unity Engine 5

EDIT: I HAVE FOUND THE ERROR. (I forgot to save the script XD)


texts: Efficient billboarding sprites in Unity 5

texts:
What's the most efficient way to do billboarding sprites in Unity 5?

I want to make a forest of sprite trees in 3d space. Those sprites need to face the camera at all times. I am working on VERY performance restricted hardware - I need the game to run on mobile at 60+ FPS - the scripts have their overhead and moving/turnign trees cannot be static, so I cant use static batching for them.

The naive method of adding a script to each tree that makes it LookAt the camera each update is not good enough in terms of FPS.

I know the grass/details for terrain uses billboards, but it uses the sprite only as a silhouette for the grass and paints it with a flat colour.


texts:
I'm developing a game similar to Don't Starve - 2D billboards in a 3D world. Now I have encountered a problem with resolutions. I want the player to be able to change resolution, but I don't want to change how much of the world that can be seen on screen. This is how it works in Don't Starve.

So will the resolution just decide the size of the textures? Do I use a set internal resolution and then scale the textures according to the resolution? Do I then need to scale the world coordinates?

I want the field of view to be the same and also so the camera angle(it's looking down with an angle as in most strategy games). I might also mention I'm coding with Monogame.


texts:
In more than just 1 occasion, i read about 2 ways of doing a light's system in OpenGL:

normal way? i don't know how to call this one
with the shaders ( GLSL )

The problem is i don't get the difference in terms of rendering performance and system usage, what are the pros and cons for each one ?

Thanks.


texts: Should I code game logic separately from game engine scripts

texts:
I'm developing a game in Unity3d, economic strategy.
I wonder if I should code logic inside unity scripts, or write it as an external module/library?

By game logic I mean game model, which describe game entities, they relation with each other, their methods. And this logic has nothing to do with and doesn't need to know anything about networking, rendering, representation etc.

If I do it inside unity scripts, then logic is tied to unity engine and I don't see a way to implement multiplayer(client-server) without rewriting whole logic for server-side, where unity cannot be used.

I would like to define logic outside of scripts, and later, reference it inside some "main" unity script. This way I could implement multiplayer easily.

Is this a common practice, or should I avoid it, or maybe there is some alternative patterns?


texts: 3.3x OpenGL Camera - how to do 3d rotation?

texts:
I'm trying my hardest to understand what this code is doing so far I think the sin(theta) and cos(theta) of the code is representing a point with an angle.

This point with an angle sin(theta) and cos(theta) will allow the xmouse/16 value and ymouse/16 value to rotate or translate on this point with an angle because of their layout representation in the GLM::LookAt() function (view/camera matrix).

The result of doing this is that the view matrix rotates on the x axis left and right when I move the mouse left and right and the y axis up and down when I move the mouse up and down.

Is this correct? It took a lot work to understand this and if I am correct does anyone know how to move the mouse left, right, up and down from the centre of the screen (as in the mouse cursor at centre of the screen when moved to the left, right, up and down will move the camera respectively) rather then from a small region of the top left hand corner thanks!.

N.B.: I'm using Model Matrix and Perspective Projection Matrix with this in the middle so  Model * View * Perspective

C++ OpenGL 3.3x  GLSL 3.30 CORE Windows 10

Code:

GLuint OpenGL_Engine::SetupViewCamera(GLFWwindow *RenderWindow, glm::vec3 eyepos, glm::vec3 originpos, glm::vec3 viewrotationpos, GLuint program, GLfloat RotAng)
{
    double xmouse = 0.0f, ymouse = 0.0f;
    glfwGetCursorPos(RenderWindow, &xmouse, &ymouse);

    double theta = glm::radians(RotAng);

    glm::vec3 camera(cos(theta), 0.0f, sin(theta));
    camera *= 5;
    glm::mat4 ViewMatrix = glm::lookAt(
    camera,
    glm::vec3(xmouse/16, ymouse/16, 0.0),
    glm::vec3(0.0, 1.0, 0));

    glm::mat4 IViewMatrix = glm::inverse(ViewMatrix);

    GLint Viewmatrixloc = glGetUniformLocation(program, "VM");
    glUniformMatrix4fv(Viewmatrixloc, 1, GL_FALSE, &IViewMatrix[0][0]);

    return 80;
}


texts:
I'm having trouble understanding this tutorial.  It defines the importance of classes, but it doesn't show an outline of the project file so far.  From what I got from that tutorial was that there is a stage and actors.  Stage would be the static parts of the game, while the actors are the ones moving.  After that I got confused with the drawing method. I tried modifying it so I can draw a shape, but it wouldn't work.

How, if possible, would I create sprites using LibGDX's scene2d?


texts: how to disable enum if bool is not true in inspector unity

texts:
I want to enable an enum when a bool value is true through the inspector and disable it when the value is false.
Please see the relevant code below:

public bool hasWeapon;

[System.Serializable]
public enum WeaponType {HandGun, Sword, ShotGun, Spear, BowAndArrow};

public WeaponType weaponType;

From the above code weaponType should only appear in the inspector if hasWeapon is true.

How can this be done?


texts:
I am making a game similar to Asteroids. The ship always points toward the mouse cursor. I want to know how to move towards the mouse so if I press w I will drive towards the mouse and if I press s I will move away from the mouse. How can I do this? Here is my code so far:

public class player {

    public int x,y;
    private Image img;

    float xDistance;
    float yDistance;
    double rotationAngle;

    public player(int x,int y){
        this.x = x;
        this.y = y;
    }

    public void tick(){
         xDistance = Comp.mx - x;
         yDistance = Comp.my - y;
         rotationAngle = Math.toDegrees(Math.atan2(yDistance, xDistance));
         handleinput();
    }

    public void render(Graphics g){
        Graphics2D g2 = (Graphics2D) g;

        RenderingHints rh = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
        g2.setRenderingHints(rh);

        ImageIcon i2 = new ImageIcon("res/player.png");
        img = i2.getImage();

        AffineTransform at = AffineTransform.getTranslateInstance(x, y);
        at.rotate(Math.toRadians(rotationAngle) ,20,20);

        g2.drawImage(img, at, null);

    }

    public void handleinput(){
        if(Keys.isPressed(Keys.w)){

        }
    }

}


texts:
I've been working on making Pong in OpenGL and SDL and currently have both paddles and the game ball set up properly. I have an Object (or Entity) class which is used to instantiate each of the entities in the game. The Object class constructor takes a width and a height for the object, the direction in which it moves (x and y), its position, its speed, and rotation.

In order to detect whether the ball has collided with either a paddle or the top or bottom of the screen, I do the following checks:

// Collision with the top
            if ((ballTop >= topWallBottom) || (ballBottom <= bottomWallTop)) {
                ball.yDir = -ball.yDir;
            }

            // Collisions Left Paddle - Ball
            if ((
                (leftPaddleBottom > ballTop) ||
                (leftPaddleTop < ballBottom) ||
                (leftPaddleLeft > ballRight) ||
                (leftPaddleRight < ballLeft))) {

            }
            else{
                ball.xDir = -ball.xDir;
                ball.yDir = -ball.yDir;
            }
            if ((
                (rightPaddleBottom < ballTop) ||
                (rightPaddleTop > ballBottom) ||
                (rightPaddleLeft > ballRight) ||
                (rightPaddleRight < ballLeft))) {

            }
            else{
                ball.xDir = -ball.xDir;
                ball.yDir = -ball.yDir;
            }

The dimensions of each object are defined by essentially using the width and height of each object, dividing either value by two (for either the x or the y direction) and checking if the ball's (collision box) position has intersected with that of a paddle or a border:

// Ball dimensions
            float ballTop, ballBottom, ballLeft, ballRight;
            ballTop = ball.posY + (ball.height / 2.0f);
            ballBottom = ball.posY - (ball.height / 2.0f);
            ballLeft = ball.posX - (ball.width / 2.0f);
            ballRight = ball.posX + (ball.width / 2.0f);

            // Wall Dimension
            float topWallBottom = topWall.posY - (topWall.height / 2.0);
            float topWallTop = topWall.posY + (topWall.height / 2.0);
            float bottomWallBottom = bottomWall.posY - (bottomWall.height / 2.0);
            float bottomWallTop = bottomWall.posY + (bottomWall.height / 2.0);

            // Left Paddle Dimensions
            float leftPaddleTop = leftPaddle.posY + (leftPaddle.height / 2.0f);
            float leftPaddleBottom = leftPaddle.posY - (leftPaddle.height / 2.0f);
            float leftPaddleRight = leftPaddle.posX + (leftPaddle.width / 2.0f);
            float leftPaddleLeft = leftPaddle.posX - (leftPaddle.width / 2.0f);
            // Right Paddle Dimensions
            float rightPaddleTop = rightPaddle.posY + (rightPaddle.height / 2.0f);
            float rightPaddleBottom = rightPaddle.posY - (rightPaddle.height / 2.0f);
            float rightPaddleRight = rightPaddle.posX + (rightPaddle.width / 2.0f);
            float rightPaddleLeft = rightPaddle.posX - (rightPaddle.width / 2.0f);

For some reason, the ball seems to be passing right through the paddle and not redirecting at all. I'm pretty sure that I have everything set up correctly but I can't really determine what is preventing the ball's collisions from being detected.

Is there something that I'm doing wrong conceptually, or is there just a small mechanical issue? I feel like its the latter, but I can't be sure.

Here is the full code for reference.

Of course, any other specific suggestions about how to implement collision detection here would be welcomed, thanks!


texts: Event Driven Behavior Tree: deterministic traversal order with parallel

texts:
I've studied several articles and listen some talks about behavior trees (mostly the resources available on AIGameDev by Alex J. Champandard).

I'm particularly interested on event driven behavior trees, but I have still some doubts on how to implement them correctly using a scheduler.

Just a quick recap:

Standard Behavior Tree

Each execution tick the tree is traversed from the root in depth-first order
The execution order is implicitly expressed by the tree structure. So in the case of behaviors parented to a parallel node, even if both children are executed during the same traversing, the first leaf is always evaluated first.

Event Driven BT

During the first traversal the nodes (tasks) are enqueued using a scheduler which is responsible for updating only running ones every update
The first traversal implicitly produce a depth-first ordered queue in the scheduler
Non leaf nodes stays suspended mostly of the time. When a leaf node terminate(either with success or fail status) the parent (observer) is waked up allowing the tree traversing to continue and new tasks will be enqueued in the scheduler
Without parallel nodes in the tree there will be up to 1 task running in the scheduler
Without parallel nodes, the tasks in the queue(excluding dynamic priority implementation) will be always ordered in a depth-first order (is this right?)

Now, from what is my understanding of a possible implementation, there are 2 requirements I think must be respected(I'm not sure though):

Now, some requirements I think needs to be guaranteed by a correct implementation are:

The result of the traversing should be independent from which implementation strategy is used.
The traversing result must be deterministic.

I'm struggling trying to guarantee both in the case of parallel nodes. Here's an example:

Parallel_1
-->Sequence_1
---->leaf_A
---->leaf_B
-->leaf_C

Considering a FIFO policy of the scheduler, before leaf_A node terminates the tasks in the scheduler are:

P1(suspended),S1(suspended),leaf_A(running),leaf_C(running)

When leaf_A terminate leaf_B will be scheduled (at the end of the queue), so the queue will become:

P1(suspended),S1(suspended),leaf_C(running),leaf_B(running)

In this case leaf_B will be executed after leaf_C at every update, meanwhile with a non event-driven traversing from the root node, the leaf_B will always be evaluated before leaf_A.

So I have a couple of question:

do I have understand correctly how event driven BT work?
How can I guarantee the depth first order is respected with such an implementation?
is this a common issue or am I missing something?


texts: Ways to manage changing designer data alongside changing player data

texts:
I have an online game where players get to shape the world in some way - eg. Ultima Online's housing, where you get to build your houses directly onto certain parts of the world map. These are changes that should persist over time as part of the persistent world.

At the same time, the design team are adding new content and amending old content to improve and extend the game for new players. They will do this on a development server first during testing and then later have to merge their work in with the players' "work" on the live server.

Assuming we fix the game design issues - eg. players can only build in designated areas, so they never clash geographically with designer edits - what are good ways to handle the data or arrange the data structures so as to avoid conflicts when new designer data is merged in with new player data?

Example 1: a player crafts a new type of item, and the game assigns the ID 123456 to it. Instances of that item all refer back to 123456. Now imagine the game designers have a similar system, and a designer creates a new item also numbered 123456. How can this be avoided?

Example 2: someone makes a popular mod that gives all your dragons a French accent. It includes a script with a new object called assignFrenchAccent which they use to assign the new voice assets to each dragon object. But you are about to deploy your "Napoleon vs Smaug" DLC which has an object of the same name - how can you do this without a lot of customer service problems?

I've thought of the following strategies:

You can use 2 separate files/directories/databases, but then your read operations are significantly complicated. "Show All Items" has to perform one read on the designer DB and one read on the player DB (and still has to distinguish between the 2, somehow.)
You can use 2 different namespaces within one store, eg. using strings as the primary key and prefixing them with "DESIGN:" or "PLAYER:", but creating those namespaces may be non-trivial and dependencies aren't clear. (eg. In an RDBMS you may not be able to efficiently use strings as primary keys. You could use integers and allocate all the primary keys below a certain number, eg 1 million, to be designer data, and everything above that point to be player data. But that info is invisible to the RDBMS and foreign key links will cross the 'divide', meaning all tooling and scripts need to explicitly work around it.)
You can always work on the same shared database in real-time, but performance may be poor and the risk of damage to player data may be enhanced. It also doesn't extend to games that run on more than 1 server with different world data.
...any other ideas?

It occurs to me that although this is primarily an issue for online games, the concepts may apply to modding too, where the community creates mods at the same time that the developers patch their game. Are any strategies used here to reduce the chance of mod breaking when new patches come out?

I've also tagged this as "version control" because on one level that's what this is - 2 branches of data development that need merging. Perhaps some insights might come from that direction.

EDIT - some examples added above to help clarify the problem. I am starting to think the issue is really one of namespacing, which could be implemented in a store via composite keys. That simplifies the merge strategy, at least. But there may be alternatives I'm not seeing.


texts:
I am at the moment trying to come up with a simple method to extract some data points, given two corners.

A***************
****************
***************B

I tried to illustrate my situation above.
Given corner A and B (x,y,z) how do generate the (x,y,z) coordinate for all the * in the square?


texts: Converting 3D coordinates to 2D and back?

texts:
I'm wondering if there is a simple way to convert 3D coordinates to 2D coordinates. Also, if it's possible, to convert in the reverse direction.

I'm using OpenGL(GLUT) in my C++ project.

I am also using SFML for the 2D information (sprites text etc.)

I found out that I can use gluProject(), but I have no idea how to use this.

I'm asking for a simple example of using gluProject() or another example to convert 3D coordinates (such as from the player) to 2D coordinates.

If I can't get the simple process I'm confident that I can figure out the rest.


texts: Merging geometry/mesh without losing benefits

texts:
In three.js we can simply merge geometry to limit the amount of draw calls and thus increase performance. In a simple test with one material, I could draw 50.000 cubes + shadows @ 60fps on my GTX660 GPU. Without geometry merging, 5.000 cubes already caused a problem.
I wonder how to preserve the benefits of rendering each cube mesh on it's own. For example, how to pick a cube mesh when everything is merged into one geometry? By default that's not possible of course.
Is there any common technique for this problem? After all I do have all the unmerged mesh objects even after merging. So there must be some way to utilize them for picking?
What I want to do in a nutshell

SimCity like game for learning purposes
Each house is a cube mesh
Want to render 50.000 houses and be able to add & remove houses
House-selection via mouse-cursor (picking) must be possible


texts: Object pooling in Multiplayer Game. Physics not synchronizing well

texts:
I implemented object pooling for my multiplayer project. Following Unity Manual I used custom spawn handler for shooting bullets. Bullets game object has rigidbody so selected Sync Rigibody 3D in Network Transfrom. My pool size is 5.

While shooting when all 5 projectile is shooted then they have to have to come back to initial position one by one that is the concept of pooling.

When projectile moving back they just instantly go back to initial position on host but on client their position are lerping and can easily be seen that we are reusing projectile.

How will I fix this ?
I've added GIF for better understanding

Code For SpawnManager where I'am using Custom SpawnHandler

public class SpawnManager : MonoBehaviour {

public int m_ObjectPoolSize = 10;
public GameObject m_Prefab;
public GameObject[] m_Pool;

private Queue<GameObject> objectPool;
public NetworkHash128 assetId { get; set; }

public delegate GameObject SpawnDelegate(Vector3 position, NetworkHash128 assetId);
public delegate void UnSpawnDelegate(GameObject spawned);

void Start()
{
    assetId = m_Prefab.GetComponent<NetworkIdentity>().assetId;

    objectPool = new Queue<GameObject>();
    for (int i = 0; i < m_ObjectPoolSize; ++i)
    {
        GameObject obj = (GameObject)Instantiate(m_Prefab, Vector3.zero, Quaternion.identity);
        obj.SetActive(false);
        objectPool.Enqueue(obj);
    }

    ClientScene.RegisterSpawnHandler(assetId, SpawnObject, UnSpawnObject);
}

public GameObject GetFromPool(Vector3 position)
{
    GameObject obj = objectPool.Dequeue();
    obj.transform.position = position;
    obj.SetActive(true);
    objectPool.Enqueue(obj);

    return obj;
}

public GameObject SpawnObject(Vector3 position, NetworkHash128 assetId)
{
    return GetFromPool(position);
}
// Not calling this function yet
public void UnSpawnObject(GameObject spawned)
{
    Debug.Log("Re-pooling GameObject " + spawned.name);
    spawned.SetActive(false);
}

}

And this is the code where I am calling these function.

public class PlayerTest : NetworkBehaviour {

SpawnManager spawnManager;

private void Start()
{
    spawnManager = GameObject.Find("Spawn Manager").GetComponent<SpawnManager>();
}

private void Update() {

    if (!isLocalPlayer) return;

    if(Input.GetKeyDown(KeyCode.Space)) {

        CmdFire();
    }
}

[Command]
void CmdFire() {

    // Set up prefab on server
    var prefab = spawnManager.GetFromPool(transform.position + transform.forward);
    prefab.GetComponent<Rigidbody>().velocity = transform.forward * 4;

    // spawn prefab on client and server
    NetworkServer.Spawn(prefab, spawnManager.assetId);
}


texts: How to keep AI goalkeeper inside their bounds

texts:
I'm making a soccer-themed top-down 2D endless game, but I have a problem with the goalkeeper AI.
My game looks like this:

As you can see, the goalKeeper is moving out of bounds.
I have tried to clamp them with
transform.Translate(Mathf.Clamp(target.transform.position.x,-1,1),0,0)

...but I think this for clamping the speed, not the area boundaries. What should I do instead?

What I want is to have two kinds of goalkeeper:

Active Goalkeeper (Call them GKA)
This goalkeeper should chase the player, but only within the bounds of the goal area.

Stationary Goalkeeper (Call them just GK)
This goalkeeper should just stand in the middle of the goal, like in the first animation. But before the player reaches them I want this goal keeper to move forward slightly, to pretend it's defending the goal.

Here is my goalkeeper script:
if (gameObject.CompareTag("GK"))
    {
        anim.SetBool("GKRun", false);
        gkballInRange = Physics2D.OverlapCircle(transform.position, gkballRange, playerMask);
        float distancePlayer = Vector2.Distance(target.position, transform.position);

        if (gkballInRange)
        {
            transform.Translate(0, -.3f * Time.deltaTime, 0);
            if (distancePlayer <= gkballRange)
            {
                if (theBall.isOver)
                {
                    anim.SetBool("GkC", true);
                    anim.SetBool("GKRun", false);
                    transform.Translate(0, 0, 0);
                }
                else
                {
                    //Animation
                    anim.SetBool("GKRun", true);
                    transform.Translate(target.transform.position.x * speed * Time.deltaTime, 0, 0);
                }
            }

        }

    }

and this one is GKA script:
if (gameObject.CompareTag("GKA"))
    {

        //Animation
        gkballInRange = Physics2D.OverlapCircle(transform.position, gkballRange, playerMask);
        float distancePlayer = Vector2.Distance(target.position, transform.position);

        if (gkballInRange)
        {
            transform.Translate((target.position.x * Time.deltaTime), 0, 0);

            if (distancePlayer <= gkballRange)
            {

                if (theBall.isOver)
                {
                    anim.SetBool("GkC", true);
                    anim.SetBool("GKRun", false);
                    transform.Translate(0, 0, 0);
                }
                else
                {
                    anim.SetBool("GKRun", true);
                    transform.Translate(0, -speed * Time.deltaTime, 0);
                }
            }
        }
    }


texts: how to make turret only shoot when pressing in specific location?

texts:
im using this code to shoot bullets from turrets, it is working perfectly but what i want to do is that, if i ll click mouse at the bottom of it it will still shoot i want it to only shoot if i will click on those positions i ll attach image to explain what i want to do here is my code:

 using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class shoot : MonoBehaviour {
    public Rigidbody2D projectile;
    public Transform fireTransform;
    public GameObject missilePrefab;
    public float fireForce = 90000;
    public Transform projectileSpawnPoint;
    public float projectileVelocity;
    public float timeBetweenShots;
    private float timeBetweenShotsCounter;
    private bool canShoot;
    protected Animation Animation;

    void Awake() {
        Animation = GetComponent<Animation> ();
    }
    void Start () {
        canShoot = false;
        timeBetweenShotsCounter = timeBetweenShots;
    }

    void Update () {
        if (Input.GetMouseButton(0) && canShoot)
        {
            GameObject missile = Instantiate(missilePrefab, fireTransform.position, transform.rotation);
            Animation.Play ();
            Rigidbody2D missileBody = missile.GetComponent<Rigidbody2D>();
            AudioSource audio = gameObject.AddComponent < AudioSource > ();
            audio.PlayOneShot ((AudioClip)Resources.Load ("sh"));
            missileBody.AddForce(transform.forward * fireForce);
            canShoot = false;
        }
        if (!canShoot)
        {
            timeBetweenShotsCounter -= Time.deltaTime;
            if(timeBetweenShotsCounter <= 0)
            {
                Animation.Stop ();
                canShoot = true;
                timeBetweenShotsCounter = timeBetweenShots;
            }
        }
    }
}


texts: Picking a local origin as the centroid of given three points in 3D

texts:
Given three points non-collinear P, Q, R in 3D, I need a generic method to generate x', y', z' unit vectors that behave like origin of local coordinate system.

x' and y' vectos should be on the plane that is defined by P Q and R.

The part that I could not figure out was:
After calculating the centroid C, I can pick x' as normalize(vec(PQ) + vec(PC)) but could not figure out how to generate y' and z'.

The method should be generic. I know this is possible without rotations etc. but how?

I'm going to write a program in Java, so I'd appreciate answers with step-by-step.


texts: I'm looking to build an automated LAN matchmaking system for games and wondering if/how it would differ from the online applications (like FaceIt, ESEA) that serve a similar function. Ideally, a user would first select the game they wanted to play (PUBG, LoL, etc) then be paired up with others on the LAN who are playing the same game. Is that possible?


texts:
I and a couple of friends are doing a game on our spare time and we've finished about 80% of the game.. so all the obvious stuff and core mechanincs. We've done a couple of games before and we always have problems finishing.

The problem isn't that we're not passionate enough about the game, it's rather that no one of us sees those last details that need to be added, we've become blind somehow with the game. It's really frustrating. It can be stuff like.. "maybe we should have a pause function?" "Uhh, yeah, of course, why didn't we think of that earlier?"

Sometimes even though it takes a long time to realise the need, afterwards it's really obvious that it needed to be done/added.

Do you use any kind of checklist to force a finish or do you rely on your keen senses to know when it's done?

A checklist would be nice to have when estimating project time as well..