texts: How to Move a Player in a Tile-Based RPG

texts:
I've been following a JavaHub tutorial that basically uses a pixel engine similar to MiniCraft. I've attempted to make a Player Class as such, and I'm basically making a mock Pokemon game for learning's sake:

    package pokemon.entity;

    import java.awt.Rectangle;

    import pokemon.gfx.Screen;
    import pokemon.levelgen.Tile;
    import pokemon.entity.SpritesManage;;

    public class Player
    {
      int x, y;
      int vx, vy;
      public Rectangle AshRec;
      public Sprite AshSprite;
      Screen screen;
      Sprite[][] AshSheet;

      public Player()
      {
        AshSprite = SpritesManage.AshSheet[1][0];

        AshRec = new Rectangle(0, 0, 16, 16);

        x = 0;
        y = 0;

        vx = 1;
        vy = 1;

        screen.renderSprite(0, 0, AshSprite);
      }

      public void update()
      {
        move();
        checkCollision();
      }

      private void checkCollision()
      {

      }

      private void move()
      {
        AshRec.x += vx;
        AshRec.y += vy;
      }

      public void render(Screen screen, int x, int y)
      {
        screen.renderSprite(x, y, AshSprite);
      }

    }

I guess what I really want to do is have the Player centered in the screen and have the sprite drawn based on an Input Handler.

I have a render method in the main Game Class that I'm using to render the tiles for the map.  I'd imagine I'd just need to add some parameters or methods in the Player Class?  Do I create and render the sprite for the Player in the Main Class or Player Class?

Main render method:

    private void render()
    {
      BufferStrategy bs = getBufferStrategy();
      if(bs == null)
      {
        //Technically 3 dimensions;
        requestFocus();
        createBufferStrategy(3);
        return;
      }

      level.renderBkgrd(xScroll, yScroll, screen);
      level.renderSprite(0, 0, Ash.AshSprite);

      for(int i = 0; i < screen.pixels.length; i++)
      {
        pixels[i] = screen.pixels[i];
      }

      //Here are the graphics that you meticulously use to put in a separate paint method.
      Graphics g = bs.getDrawGraphics();
      g.drawImage(image, 0, 0, getWidth(), getHeight(), null);

      //If they are already drawn, don't show them again.
      g.dispose();
      bs.show();
    }

...And level.renderSprite() is what I thought would work...But without it the code gives me a NullPointerException.

Update:

Normally, a Game/Board/World class can aggregate all of the object updates and renderings.  Knowing what I do now, in a World update() method, I typically throw the player.update() method in there and the drawing method in the World draw() method.  The answer concerning through objects into an object manager is also a good suggestion, especially considering you could have multiple different enemies that will probably be deleted or updated synchronously in the near future as the game runs.

It appears I had a specific problem with an NPE (as general as it can be).  It looks like I was over-complicating things way too much: I could just abstract the render/draw method out and have a player sprite (determined by the Player Class, if need be) rendered at the player's coordinates (again, determined by the Player Class).  As you can see in the Player Class above I have a render method which calls the screen render method while I'm fiddling around with the Level instances rendering something in the main render() method and it's just a hot mess.

Moral of the story: A good game dev tutorial will offer you the reason for their methodology based on design patterns like separation of concerns that make the code much more maintainable.


texts: How To Get Current Selected Tiles and Neighbour

texts:
I've 2D array that store each planes that instantiate using code.

Tile[][] map;

Then in Update()function, I try to Raycast and i can get the tile from RaycastHit game object.

How to get which Tile in my 2D array map is hovered base from RaycastHit without loop each tiles in array and check it ?


texts: How to get all keys and values of the PlayerPrefs in Unity?

texts:
I'm storing player name and scores in the Unity PlayerPrefs. I'd like to list all the names and scores stored in PlayerPrefs and display a high score page:

Is it possible to display all the keys values previously stored in the PlayerPrefs? Or can someone provide me by a JavaScript to do this?


texts: How to handle movements of objects in a platformer with a cylindrical map?

texts:
I was wondering what would be the best approach for a game with a perspective like  Resogun, where the world wraps around in a cylinder:

In my opinion, the easiest approach is to:

have a "Center Parent" for each moving object

Offset the child object by the wanted  radius

Rotate the parent

=> The objects will move, though this will become super limited very quickly, especially if you want to do any sort of physics.
The 2nd approach is math:
x = centerX + cos(angle)*radius;
x = centerY + sin(angle)*radius;

Now i wonder if there is another way, I was thinking of another method which basically consist of changing the Forward direction of the moving objects based on their position in "the circle", so basically the objects always move forward but adjust their rotation according to their position so they are always facing the right angle.
My main question is that if you want to create a puzzle platformer game like Limbo for example, but in a "cylindrical" map like Resogun, how would you tackle it ?
Thanks!


texts: Unity5 TextAsset not functioning in WebPlayer

texts:
Preface

I am working on a 2D Platformer in Unity5 utilizing TileMap techniques.  I have a working system to read "Room Tile Data" from JSON files with the Unity TextAsset Class and the Newtonsoft JSON.Net library.  My level files are within a folder inside of the Resources Directory and the Resources.Load is working on the json files with and without their .json file extension.

Code

FileName = "MapFiles/room_three";
TextAsset mapDataFile = Resources.Load(FileName) as TextAsset;
string text = mapDataFile.text;
Map thisLevel = new Map();
thisLevel = JsonConvert.DeserializeObject<Map>(text);

Problem

This works in the standalone builds for win + mac as well as in the Unity Editor.  But a unity Web player Build entirely fails to load the TextAsset and my characters are left falling endlessly.

The only error I receive is a reference to mapDataFile.text being null.  Leading me to believe my TextAsset is failing to load from the web player.  The documentation says nothing I could find about using the TextAsset differently in the web player.  Is there a different technique I must use to solve this issue for the Web Player?  I'm certain I could change things to grab files on the web using WWW, but I want this data to be loaded from within the application.

Thanks in advance!

(edit) Updates:

Created a public property for the TextAsset and drag dropped the file into it. Still fails to load from the web player and worked in the standalones + editor. Assuming this means we can rule out Resources.Load as our culprit.
Tried the same functionality with Resources.LoadAssetAtPath which was only intended for use in the editor.  When running this in the web player I received a similar verbose message.  Nothing like this appears with Resources.Load
Updated "sample code" containing FilePath variable with file path string  value being used in my application
Tested web player in FireFox / Chrome / Safari on Mac OSX 10.8 Yosemite
Pursued a potential cause found here: LINK TO ARTICLE I copied this technique implementing a scene 0 menu and the problem persisted with a weird flickering in Scene 0
Deleted Project "Library", "Temp" & "Project Settings" directories and let them be regenerated in conjunction with a few of these other attempts for good measure.  Also removed / regenerated user preferences
Ran a "Reimport All" Assets by unity, Unsuccessful.
For posterity, I tried "Turning it Off and On Again" (Rebooting my Machine)
Uninstalled and Reinstalled newest Unity WebPlayer, unsuccessful.


texts:
As far as I understand for DirectX11 it is recommended to have multiple single pass shaders, so the the method with multiple passes in one shader file is deprecated. Is my understanding correct and where can I find more information about that?

How would I go about creating a multi pass shader in DirectX11? The way I understand it, one would have to apply a shader and then copy the shader result to be used as input for the next shader pass.

Is this the right way to do it? Any information on this subject is very appreciated.


texts:
I have just launched a game on the Playstore with Unity IAP 1.19.0 . Everything worked fine during the internal tests though last week I got a crash report from Crashlytics that I have difficulty analyzing. Any help on finding the root cause would be really appreciated. Here is an extract from the trace:

Fatal Exception: java.lang.Error: FATAL EXCEPTION [main]
Unity version     : 5.5.4p3
OS Version: 7.1.1
Device: Nexus 6

Caused by java.lang.RuntimeException: Unable to start activity ComponentInfo{com.abc.abcd/com.unity.purchasing.googleplay.PurchaseActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.BaseBundle.getString(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:107)

Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.BaseBundle.getString(java.lang.String)' on a null object reference
at com.unity.purchasing.googleplay.PurchaseActivity.onCreate(PurchaseActivity.java:41)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:107)


texts: Libgdx Sprite is not drawn when generated inside another class

texts:
I´ve built a gameloop where I generate new items depending on the elapsed time and want to place them somewhere on the screen. I use some randomness for the color and coordinates. For better design I want the sprites of these items to be generated by classes that contain additional information on these items. But I figured out that when doing so my sprites won´t be drawn. Sprites that are generated explictly inside my loop are perfectly drawn.

This is my current gameloop

public void loopGame(float delta) {

    Gdx.gl.glClearColor(255, 255, 255, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    timer.addDelta(delta);

    Gdx.app.debug("Bubbles", "Time: " + String.valueOf(this.timer.getCurrentTime()));

    batch.begin();

    Sprite freeBubble = new Sprite(new Texture(Gdx.files.internal("data/img/bubble_black.png")));
    freeBubble.setPosition(200, 200);
    freeBubble.draw(batch);

    Bubble newBubble = this.bubbleFlask.createNewBubble(timer.getCurrentTime());
    if (newBubble != null) {
        bubbles.add(newBubble);
        Gdx.app.debug("Bubbles", "Created new bubble!");
        Gdx.app.debug("Bubbles", "Attributes: " + newBubble);
    }

    // draw all bubbles
    for (Bubble bubble : bubbles) {
        Gdx.app.debug("Bubbles", "Drawing bubble");
        Sprite bubbleSprite = bubble.buildSprite();
        bubbleSprite.draw(batch);
    }

    batch.end();

}

The freebubble is perfectly drawn. this.bubbleFlask generates bubbles the way it is supposed to but those bubbles are not drawn inside the for loop. Debugging messages show me that the loop works as it should.

So you might guess that bubble.buildSprite() is broken. Here is this method:

public Sprite buildSprite() {
    Sprite sprite = new Sprite();
    sprite.setTexture(new Texture(Gdx.files.internal("data/img/bubble_black.png")));
    sprite.setPosition(300f, 300f);
    return sprite;
}

For the sake of demonstration I placed the same texture file here.

What am I missing here?


texts: Why is my counter not incrementing when OnTriggerEnter is called?

texts:
I have a script that handles the destruction of game objects based on what they collide with.  I am trying to count the number of objects destroyed when they collide with specific objects.  However, this is not happening.  Instead, the counter is getting to "1" and no longer counting.  Can anyone explain why?

public class Destroy:MonoBehaviour{
    public GameObject asteroid_explosion;
    public GameObject ship_explosion;
    private int destroy_count = 0;

    void OnTriggerEnter(Collider other){
        if(other.tag == "Boundary"){
            return;
        }

        if(other.tag == "Bolt"){
            destroy_count = destroy_count + 1;
            Instantiate(asteroid_explosion, transform.position, transform.rotation);
            Debug.Log(destroy_count);
        }

        if(other.tag == "Player"){
            destroy_count = destroy_count + 1;
            Instantiate(ship_explosion, other.transform.position, other.transform.rotation);
        }
        Destroy(other.gameObject);
        Destroy(gameObject);
    }
}


texts:
I wanted to make a game with a "serverless" mobile multiplayer game.
The idea was to have devices connect to each other automatically when they are within range.
There would be no global game state but just the one created by the first one to start their game or be in one place. When others join the game state is forwarded to them and the themselves send it to devices that are connected to them.
This happens everytime there is a significant change.
The game itself would be kind of an rpg with a location based gameplay (mostly to have the players socialize)
The idea was to only have players who are close to each other play together.
Now: the actual question: How can I realize this idea? Things I found online were Android Wifi Direct or Bluetooth but both seem to have their problems for this project. Is there any way I can actually build my game?

Thanks in advance.


texts: How do I convert a horizontal, panoramic skymap texture into a "dome" version of itself?

texts:
How do I convert the following skymap image:

into a "dome" version like the one below?

I'm looking towards making use of Adobe Photoshop for the task at hand. However, I'm at a loss on what tools I'm going to use and how I will go about it.

So, how do I convert a horizontal, panoramic skymap texture into a "dome" version of itself?


texts: Entity component system - game progression

texts:
I'm quite new to game development (but not to programming) and I'm trying to figure out what would be the best way to handle inter-world communication. What I mean is this:

I've been reading about entity component systems (ECS) and how people suggest using different worlds/spaces (http://gamedevelopment.tutsplus.com/tutorials/spaces-useful-game-object-containers--gamedev-14091) for a subsection of a game. For example a HUD, inventory or combat/movement each get a seperate world/space (because they have different graphics and underlying logic.

However, I was wondering how the inventory, or the HUD knows about the health of a player when the health is handled by a different space/world, for example when in combat?

This also applies to game progression in general, for example dialog with NPC (a dialog would be a separate space since it's a popup screen) but how would you convey the choices made in (or the state of) the dialog to other spaces/worlds. Or basically any other type of event that influence the game progression in different spaces/worlds (health, mana, quests, dialog, combat, inventory, hud, etc)

How would one handle this kind of design? Does it need a (in implementation) singleton object that holds all this kind of information? That would be weird because then the components need to convey each change to this singleton object which feels like doing things twice (going against the main DRY of programming)...

I'm kind of at a loss here in terms of design, any pointers?

---EDIT---

So I've read a few other posts suggested by comments and got a general idea about possibilities, however each of them seems to have one major downside which makes them just not right. It's is very possible that I'm overseeing details that would solve these downsides so feel free to correct me. I'll try to give an overview as well as some answers to some questions.

I'm seeing three major options to 'share' data between spaces. Even though most posts are about sharing data between systems, I feel like the same can be applied to sharing data between systems.

1. Querying

Example: If the HUD world needs to know the current health of the player it can query another world and ask for the current health.

Downside: Worlds need to know about each other which is a major dependency issue and goes against decoupling.

2: Direct messaging (sync and async)

Example: If during combat the health of a player changes it can send messages (sync and async, whatever is needed) to other worlds that need to know about this change.

Downside: Still the decoupling issue: worlds need to know about eachother.

3: Indirect messaging (sync and async) <-- best option

Example: If during combat the health of a player changes it can send messages (sync and async, whatever is needed) to general message hub. Other worlds/systems that need to know about this change are subscribed to the particular message channel and read the messages.

Upside: Completely decoupled, easily manageable and extendable.

Downside/unclear: When does the message channel know that the messages need to be deleted? Or maybe the system that is subscribed marks (only for itself) the message as read and waits for new messages -> messagebox becomes enormous after a while. How do worlds/systems handle order? For example during a frame: if the HUD already polled the health message and after that the health changes, the next frame the HUD gets updated. For some applications this might not be the right way.

Q: A single game object can exists in multiple spaces

I'm using Artemis ECS framework which comes with build-in spaces (called worlds). Each entity (and with it, the data in the form of components) is created on a world and thus cannot be shared between worlds.


texts:
I use Urho3D which uses SDL2 as a window system. I want create another window as GUI and make it child for main window of Urho3D.

What I did is:

// insde virtual void Start() // Urho3D app
SDL_Window * sdlw = context->GetSubsystem<Graphics>()->GetWindow();
int width = context->GetSubsystem<Graphics>()->GetWidth();
int height = context->GetSubsystem<Graphics>()->GetHeight();
HWND mw = SDLWindows::GetWindowHWND(sdlw);
wpfC = WPFI::CreateWPFControl(0, 0, width, height);
HWND www = SetParent(wpfC, mw); // SetParent is windows function
if (www == NULL)
{
    std::cout << "------------------------------\n"
        << "www = NULL\n"
        << GetLastError() << "\n"
        << "------------------------------\n";
}

HWND SDLWindows::GetWindowHWND(SDL_Window * wnd)
{
    SDL_SysWMinfo sysInfo;
    SDL_VERSION(&sysInfo.version);
    SDL_GetWindowWMInfo(wnd, &sysInfo);
    return sysInfo.info.win.window;
}

I got Invalid window handle (1400) Error on SetParent().

I am not sure if I am doing it right, but I am sure that my wpfC is ok because I have another test project where it is working but instead SDL window I use win32 Window.

I think SDL_GetWindowWMInfo() give me a wrong handle.

Question is how to obtain HWND from SDL_Window correctly and be sure that it is right HWND?

If it is not possible do it that way, is there another way how to create child window from HWND inside main SDL2 window?


texts: SDL or SFML: which is the best option if I only want to use OpenGL for my graphics?

texts:
I've read a lot about creating graphics with OpenGL in SDL and SFML over the past few days, and I want to know which one I should pick. As mentioned in most of the things that I've read, both allow the programmer to use OpenGL.

However, I want to know which one would serve me best if I wanted to do graphics in OpenGL only. From what I've read, SFML does not work as well with OpenGL as SDL. Is this true?

To reiterate, I will only be using SDL or SFML for features like audio, input, and networking. All graphics will be done with OpenGL code that I write.

Also, I read a bit on LWJGL and LWJGL is essentially what I want, but I am much better at C and C++ than Java so I would like to use SDL or SFML. Which one is most similar to LWJGL?


texts: Animations with individual images in Phaser.js

texts:
So I have this game that I made a while back and I want to port it using Phaser.

The game is made using individual PNG files for all the animation frames, and there are over 100 of them.

From reading through the docs, it seems Phaser only supports spritesheets for animations.

I would like to do something like this :

player.sprite.animations.add('idle', ['images/s_snailIdle_0.png', 'images/s_snailIdle_1.png'], 60, true, false);
player.sprite.animations.play('idle');

Is there a way to add individual images to a sprite's animation?
If not, Is there a way to change the image of a sprite so that I can implement my own animation system?


texts: How can I write a D3D12 texture in cuda?

texts:
One point about such pipeline is that everything happens in GPU and bypass the CPU.

The texture is created as such:

ThrowIfFailed(m_device->CreateCommittedResource(&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_SHARED,
            &texDesc, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, nullptr, IID_PPV_ARGS(&TextureArray)));
// texture pixel format: DXGI_FORMAT_R32G32B32A32_FLOAT

How can I access in read+write to TextureArray (ComPtr<ID3D12Resource> TextureArray;) in cuda ?


texts: After creating DirectX11 Device, enumerating the DXGI Adapters seems to produce invalid results

texts:
EDIT: This is part of an upgrade from DirectX10 to DX11.

When I create a DirectX 11 device with D3D11CreateDevice(), it chooses a video adapter for me. I access this object like so:

// removed HRESULT checks for brevity- normally I print errors on failed hr

IDXGIDevice1*  pDXGIDevice = NULL;
HRESULT hr = mpDXDevice->QueryInterface( &pDXGIDevice );

IDXGIAdapter* pAdapter = NULL;
pDXGIDevice->GetAdapter( &pAdapter );

// save pAdapter

However, later, when I enumerate the adapters, this adapter is not on the list:

IDXGIDevice*  pDXGIDevice = NULL;
HRESULT hr = mpDXDevice->QueryInterface( &pDXGIDevice );

IDXGIAdapter* pAdapter;
hr = pDXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void **)&pAdapter);

// so far so good: pAdapter matches my current adapter I saved from above

IDXGIFactory* pFactory;
pAdapter->GetParent(__uuidof(IDXGIFactory), (void **)&pFactory);

UINT i = 0;
while( SUCCEEDED( hr ) && hr != DXGI_ERROR_NOT_FOUND )
{
    IDXGIAdapter* padapter;
    hr = pFactory->EnumAdapters1( i, &padapter );

    // none of these padapters matches the current adapter!!
    i++;
}

After this section, I have a list of the enumerated adapters. My current adapter is not in the list! Instead there is a DIFFERENT adapter with the same name as my current one.

Most importantly (this is the part I actually need) if I call D3D11CreateDevice() with this enumerated (different) adapter specified, I get E_INVALIDARG.

What am I doing wrong to generate these alternative, invalid adapters?


texts: Any clue to create natural shadow like this?

texts:
I only use skylight with hdri map for overcast lighting. The corner isn't dark enough compare to other's work. Any clue to achieve this natural falloff soft shadow?
What I want

What I get

My world settings


texts: Libgdx SpriteBatch won't position correctly on Screen

texts:
I have been trying to position my spritebatch correctly regardless of screen size but it simply wont scale..This is what I want to achieve on every screen size..I want my Sprite Object to be positioned at the center of the x-axis on every screen size and on the first half of the screen (above dotted line) and have it scale as well..I have also noticed that spritebatch doesn't respect my gameheight and gamewidth instead opting for screenwidth and screenheight. The dimensions for my sprite anim are 900 by 700 and I am hoping it can scale for lower resolutions

Code :

batch.draw(animation.getKeyFrame(elapsedTime, true), 20, app.midPointY + 350, app.screenWidth, 465);


texts: How to properly activate trigger objects?

texts:
I have made a flying cat that follows the player, but I want the cat to be a separate object. Cat is following the player and as soon as it sees a collectible it grabs it for the player and then returns following our player. I have it working, but I need the cat to be a different object, it only triggers properly when it's a child of the player object. I have made two scripts for the cat, one for detection, following, flying and the other for destruction of collectibles.

AI script

void OnTriggerStay2D(Collider2D col){
    if (col.CompareTag ("Collectable")) {
        //Destroy(col.gameObject, 1F);
        if(positionList.Count <= 0){
        positionList.Add(col.transform.position);
        timerDelay = 1F;
        mustReturn = false;
        }
    }
}

void OnTriggerEnter2D(Collider2D col){
    if (col.CompareTag ("Collectable")) {
        positionList.Add(col.transform.position);
        timerDelay = 1F;
        mustReturn = false;
    }

}
void Update () {

    if (mustReturn) {
    //  positionList.RemoveAt(0);
        transform.position = Vector3.MoveTowards (
            transform.position, player.transform.position, Time.deltaTime * speed);

    }

    if (timerDelay > 0) {
        timerDelay-= Time.deltaTime;
        idleDelay = 0;

        if(positionList.Count > 0) {
        foreach (Vector3 nextPos in positionList)
        {
            transform.position = Vector3.MoveTowards (
            transform.position, nextPos, Time.deltaTime * speed);

        }
    }

}

    if (timerDelay <= 0) {

        if(positionList.Count > 0) {
            positionList.Clear();
            timerDelay = 1F;
        }

        if(positionList.Count <= 0)
        mustReturn = true;
    }

    if (idleDelay >= 3F) {
        idleAnimation();
    }

    /*Debug.Log ("pos count is " + positionList.Count);

    if(timerDelay > 0)
        Debug.Log ("delay is " + timerDelay);*/

    idleDelay += Time.deltaTime;

}

void idleAnimation(){

}

void OnTriggerExit2D(Collider2D col){
    if (col.CompareTag ("Collectable")) {
        mustReturn = true;
    }
}

Destruction class

void OnTriggerStay2D(Collider2D col){
    if (col.CompareTag ("Collectable")) {
        Destroy (col.gameObject, 0.5F);
    }
}

void OnTriggerEnter2D(Collider2D col){
    if (col.CompareTag ("Collectable")) {

    }

}
void OnTriggerExit2D(Collider2D col){
    if (col.CompareTag ("Collectable")) {

    }
}

Question: Why won't the cat function on it's own???

Collectibles DO have that tag, and they DO have a Box Collider 2D along with a 'Trigger: true'

Cat:


texts: Unity - Calculating a rotation based on game time

texts:
I have a simple script to make an object spin:

Spin Speed is the speed to rotate the object on each axis (preferably in degrees per second). Local is whether the rotation should be done based on world axes or object axes. Starting Rotation is the initial rotation of the object.

Normally I would use Transform.Rotate to do the rotation, but in this case I have to make the rotation a function of time, so you can pass in any time value and it will return what the rotation should be at that time.

Here is an example (this doesn't work properly for either world or object axis rotation):

private Quaternion getRotation(float time)
{
    return Quaternion.Euler(InitialRotation + SpinSpeed * time);
}

I just need some help figuring out the math behind calculating rotations for both world and object axes. I think that matrices can be used but I honestly don't remember anything about how to use them.

Here's an example of using world axes with a SpinSpeed of 180 on the y axis and an initial rotation of 45 on the x axis:
https://i.gyazo.com/d7f41b6a88425b5d8b8237cd7ac40878.gif

An example of using local axes with the same parameters as above:
https://i.gyazo.com/d453b3dd239c9f77b86ce372c499d068.gif


texts: Hidden copies of the environment in an entity component system

texts:
For reasons outside the scope of this question, my game has several full copies of the game environment running asynchronously. At any one time, only one of these is rendered.

This is trivial to support in a traditional, object-oriented architecture. Instantiate a few copies of the environment, run each one in its own thread (I actually use a parallel task system for cases where there are more environments than CPU cores), and only call call draw() on the one you want rendered.

The time for large refactorings has come, and I'm considering converting to an entity component system such as Entt. What would be the best way to achieve this same functionality?

The best I've come up with is each environment being a self-contained ECS, managed by an object-oriented system (which would also handle things not replicated, such as UI). The render system would be disabled in all environments except the one being rendered.

I don't like that solution though. I don't want the render system for the game environments to be separate from that of the UI, etc. I also don't like the idea of mixing ECS and object-oriented architectures.

Is there a better solution?


texts: How to create a path-finding compatible road map from user input?

texts:
I'm currently working on an agent simulation (inspired by the recent SimCity release). Now, basically I understood how agents work but I do not understand how to put them into context. Agents travel along roads on a map and pursue their own goals.

As in SimCity, I want the player to be able to create his own roads. If I used grids, I would run into a problem caused by user input: Imperfect grids will be created where two roads would need to share one "box". This would be even worse with bevels.

(Grey = Street, Orange = Agent road, Dots = Immobile Agents)

Is there another, more clever way of building a road map that would support this kind of map and is compatible with path-finding?

Thanks a lot!

Paul


texts: What can I do to avoid one-off flags and checks throughout my code?

texts:
Consider a card game, such as Hearthstone.

There are hundreds of cards that do a wide variety of things, some of which are unique even to a single card! For instance, there is a card (called Nozdormu) that reduces player turns to only 15 seconds!

When you have such a wide variety of potential effects, how do you avoid magic numbers and one-off checks all over your code? How does one avoid a "Check_Nozdormu_In_Play" method in the PlayerTurnTime class? And how can one organize the code such that when you add even more effects, you don't need to refactor core systems to support stuff they've never had to support before?


texts: Cast a circle around an object and detect other objects in range (with visual)

texts:
I have my "player" object moving around an arena type area, with miscellaneous objects scattered about. What I want to do is move the player near any of these objects, and on keypress I want to display a circular radius with the player in the center that will detect nearby objects (eventually being filtered by tag).

I realize there are many ways to accomplish this, but being relatively new to Unity I am trying to find a way that is intuitive to me. Looking at the documentation, Physics2D.CircleCastAll seems like it would fit my needs, but I am unable to test at this time (at work).

Provided CircleCastAll is what I do use, is there a way in the scene to display the circle that is being cast so that the player can visually see the radius? I know it returns a RayCastHit2D, so I can get the objects from that, but the player should have something visual to let them know if they are slightly out of range or not.

Any suggesions/tips are welcome. Thanks in advance!


texts:
I have created a function that clicks images in real time and these images are copied to render texture that is created. I am looking for a way to blur/distort/half-fade-out the render textures. Is there a way to achieve this?

 Graphics.Blit(Texture2D, renderTexture);


texts: Collision Responses with many different types

texts:
I'd like to write an efficient Collision Response code, that does not use instanceof/type checks that often (if  possible)

my current implementation is something like this:

GameObject.collidesWith(GameObject other)
{
    if(other instanceof ConcreteType1)
    {
        //do response with Concrete Type 1
    }else if (other instanceof ConcreteType2)
        // do response with Concrete Type 2
    }
}

GameObject is the base class of everything.
Is there a possibility to avoid instanceof and type checks?


texts: Blender: Bones get enlarged in export/import process

texts:
I have a rig in blender that I want to export into a different blender project. For some reason, when I do that, some of the bones get enlarged. All the scales are applied. Why might this be happening?
I've no clue why this might be happening, as this problem seems exclusive to this project and one other project, where one bone out of the whole armature gets enlarges, but here is the information I can provide:
Some differences between the projects where this happens and the others is that the ones where this does happen have animations, and a pose library. However, this does not seem to cause the problem, as deleting the animations and poses doesn't change anything.
This problem happens when I export/import the project as an FBX.
I usually export the project to unity and in order to compensate for the unity/blender rotation, I follow this [guide][1. I rotate the armature -90 on the x axis, apply rotation. Then rotate the armature 90 on the x axis but only apply the rotation to the mesh. I export the project as a FBX, with unity unit scale, no leaf bones, and the 3rd and 4th box under animations checked off. This also does not seem to cause the problem, as not rotating the armature and such doe not change anything.


texts: In Unity, how do I create a drag and drop object?

texts:
I have a 2d scene. I want the player to be able to pick up an object, move it around the scene and drop it somewhere. I can't find any way to do this, and all of the resources for Unity are really daunting and I can't find anything relevant to what I'm doing.

I've tried adding the drag rigidbody script to both my camera and the sprite I want to drag, to no effect.

Where can I find relevant documentation for stuff like this? Basic things like how to implement a script or what objects I need to attach these scripts to - the stuff on the unity website is a little too advanced.


texts:
My game is a top down mobile game where the player clicks a tile to walk to it.
However, it isn't clear where tile boundaries are from just looking at a level, so you could click on the edge of a tile expecting the player to walk there- but they walk to the center.
For instance, you could click on the center of the island shown below expecting it to be a tile- but the center is actually a corner in-between 4 tiles- so clicking there could result in walking to any of the 4 surrounding tiles.

Should I let the player walk freely, even between tiles, or is there a better solution in terms of UX?


texts: Re-create 2D side-on wave effect from Worms game

texts:
I'm trying to recreate the waves/water effect from Worms ( see here http://youtu.be/S6lrRqst9Z4?t=31s ) From what I understand its not actually a sprite, its procedurally generated by something like a sin wave.

Has anyone created something like this before? or any idea how I would go about it?


texts: Select box-shape grid between two positions on tilemap

texts:
I want to be able to click and hold on a certain point and mark it as startPosition.
Then, while the mouse is held down and moved, mark that second position as endPosition.
When the mouse is finally released, I want to get all the positions between those two points.
Here is my code so far:
for (float x = startPosition.x; x <= endPosition.x; x++)
        {
            for (float y = startPosition.y; y <= endPosition.y; y++)
            {
                Vector3Int newPosition = Utilities.GridPosFromWorldPos(new Vector2(x, y));
                if (!selectedPositions.Contains(newPosition)) { selectedPositions.Add(newPosition); }
            }
        }

This works only when dragging up and/or to the right.
As soon as I try to go to left or bottom, the endPosition coordinates become smaller than the startPosition coordinates, which breaks the for loop.
How can I solve this?


texts: Specialisation in game roles: Getting better by learning vs leveling

texts:
Many games have some sort of role for the players, especially in multiplayer games. Medic, Sniper, Rifleman, AT Specialist in Battlefield, Healer, Tanks, DDs in MMOs, etc.

Now, in many games, there are incentives to specialize in a certain role, allowing access to better equipment for this role. Most of the time, you archive this equip by playing a certain amount of time, gather XP (by doing the roles job), or archive certain goals for that role (heal 1000 players, deal X amount of damage. Battlefield Bad Company 2 and Quake Wars are good examples for that.

Alternatively the player gets "better" in the role by pure stats. They get more health, they heal more etc.

In contrast to that some games have certain roles, that a player can fulfill just by picking certain equipment, that everyone is able to pick. So in theory, every player is as capable of fullfilling the same role. The difference is in the skill of the player and the depth of the role to fulfill.

The game i have  in mind is a coop crew game, where you manage and controll a ship, much like Pulsar: Lost Colony, but much more complicated. Engineering would mean to flux the vents and stabalizing the emitters, which means to have complicated "mini-games" to archive a certain goal: Activating the engine and keep it running. Similiar to Space Station 13 maybe.

So, either i could go the leveling way: The engineer gets traits and stats, what make those minigames easier for him (make something move slower, get a better result). The other thing could be the learning way: you have to learn how to do things, make it more "realistic" and with different (scalar) outcome.

I tend toward learning the about the mechanics. The idea is that you might have more than one person for a certain role, like a chief engineer and many other working in engineering, teaching them the in and outs, maybe even on equal terms. It also would make the game more hectic and thus more reliant on communication. A hard level base would mean, that someone is distinctivly better, if he is a higher level. The higher levels would need to do most of the work, hence their boni are just to good to waste.

On other hand, for roles with less of a learning curve, that wouldnt make that much sense, since mastering it is a lot easier. In that case, it would make sense to have one with skills in this role. But, if you have a pilot with skills for a faster ship, it would be wasted on a slower, but less manouverable ship, where a pilot with talents for better mobility would be far better. For a premade group of players, that would be alright, but if you got drop-in, drop-out, that would be hard to balance for.

What style of role specialisation (leveling vs learning) has what advantage and disadvantage? What would fit better to that syle of game im working on?


texts: After a postprocess effect, can I output a list of all non-zero pixel locations without having to save the entire image?

texts:
I am trying to simulate what's known as an 'event camera' in Unreal. Unlike conventional cameras that output full frames, event cameras return the locations of pixels where activity is detected - see example below.

I have a post-process material in UE, whose job is to essentially subtracts the current image from the previous one at every tick and 'light up' all the pixels that have changed. Thus, the job of this material to identify all "moving" pixels, and after doing this subtraction, I can identify all the pixel locations that had a change in intensity.

Under the assumption that the number of changed pixels is much lesser than the total number of pixels, I want to avoid the really expensive 'ReadPixels' sort of operations in order to simulate the output of an event camera. Is it possible to access the UV positions of non-zero pixels directly? What is a good, efficient way to access such data and read it out from a material?


texts: When writing code that interacts with multiple shaders, is it best practice to hard code the use of each effect? I wrote a couple of hard-coded loops and then noticed that I accidentally ended the pass of the wrong shader, and this has me concerned that instead, I should be writing some sort of Shader class that generically executes a shader. Is this the right way to go?


texts: Why it isn't possible to get a progress in SceneManager.LoadSceneAsync between 0.0 and 0.9?

texts:
I am trying to understand why does SceneManager.LoadSceneAsync progress always jumps from 0.0 to 0.9, no matter how big a scene can be.

To try trigger smoother progress of the scene being loaded, I've tried the following:

Generate a large scene from an EditorWindow, containing tens of thousands of objects referencing thousands of assets. Loading this scene didn't produce the intended behavior, rather, it ended up being exactly the same (jumps from 0.0 to 0.9) but with a huge lag at the end since there are many objects.

According this behavior, I am now considering that the supposed asynchronicity in SceneManager.LoadSceneAsync is just about the loading of the scene file itself, not processing its content for being usable by Unity.

Is this correct?

An example on how to load a large scene and report its progress would be appreciated :)


texts: How is a Challenge implemented for a game networking protocol?

texts:
Working on an authoritative online game using LiteNetLib. I've been reading about building a game network protocol and I'm feeling stuck with the "challenge" implementation.

The client requests a connection with the server.
The server then returns some sort of challenge (that only the client should be able to solve?).
The client returns the solution and the server allows the connection.

The first thing that I don't get is how to have a "pending" connection without accepting it to begin with. With LiteNetLib, this is how the server handles incoming connections:
listener.ConnectionRequestEvent += request =>
{
    if(server.ConnectedPeersCount < 10 /* max connections */)
        request.AcceptIfKey("SomeConnectionKey");
    else
        request.Reject();
};

From the looks of it, the server must decide whether to allow the client or not at this very instant. If I want to send or receive a challenge, I need to accept the connection first don't I? But that would defeat the point of the challenge implementation.
Is there a resource with an example of how this is done? The article doesn't really go into detail, and when I google things like "online game protocol challenge request packet" the results aren't quite related (almost as if the concept was coined by that article).


texts:
In a fast-paced multiplayer game I'm working on, there is an issue with the interpolation algorithm. This interpolation is for a moving object not controlled by the local computer.

The server sends packets with the object's position at a fixed rate. (red markers) The interpolation algorithm is attempting (and failing) to create a smooth path between the red markers.

The results of this interpolation are shown by green and black markers. Green is the local position at the exact time a packet is received, and black is the local position at every frame.

Green: Local position when a packet is received (edited for clarity)

Red: Position received from packet (goal)

Blue: Line from local position to goal when packet is received

Black: Local position every frame

On a network with a realistic amount of lag and packet loss, this is the result:

The local position (green&black lines) seems to oscillate around the goals (red lines) instead of moving between them smoothly.

This is how it looks on a perfect network with the object moving right to left. (0 ping, 0 packet loss, etc.)

The code works like this:

Every x ms, receive a packet with a Vector3 position
Set the goal to that position
Set the positionAtLastPacket to the current local position
Every frame, lerp from positionAtLastPacket to goal, attempting to reach the goal approximately when the next packet should arrive.
If the next packet takes longer than expected, interpolation continues past the goal and becomes extrapolation.

I believe what is happening is the extrapolation overshoots a bit to far. Over several packets, this issue compounds, causing the oscillation.

    // local transform position when the last packet arrived. Will lerp from here to the goal
    private Vector3 positionAtLastPacket;

    // location received from last packet
    private Vector3 goal;

    // time since the last packet arrived
    private float currentTime;

    // estimated time to reach goal (also the expected time of the next packet)
    private float timeToReachGoal;

    private void PacketReceived(Vector3 position, float timeBetweenPackets)
    {
        positionAtLastPacket = transform.position;

        goal = position;

        timeToReachGoal = timeBetweenPackets;
        currentTime = 0;

        Debug.DrawRay(transform.position, Vector3.up, Color.cyan, 5); // current local position
        Debug.DrawLine(transform.position, goal, Color.blue, 5); // path to goal
        Debug.DrawRay(goal, Vector3.up, Color.red, 5); // received goal position
    }

    private void FrameUpdate()
    {
        currentTime += Time.deltaTime;

        float delta = currentTime/timeToReachGoal;
        transform.position = FreeLerp(positionAtLastPacket, goal, currentTime / timeToReachGoal);

        // current local position
        Debug.DrawRay(transform.position, Vector3.up * 0.5f, Color.black, 5);
    }

    /// <summary>
    /// Lerp without being locked to 0-1
    /// </summary>
    Vector3 FreeLerp(Vector3 from, Vector3 to, float t)
    {
        return from + (to - from) * t;
    }

Any idea about what's going on?


texts:
Two of the main systems I've seen in entity system tutorials are:

An Entities class with one array / [hash]map for each component, with indices corresponding to entity IDs.
A list of Entity structs, which have the components as fields, and possibly a pointer to a "cold" struct for less used components.

What are the reasons I would use the former over the latter, considering that the latter seems much easier to implement? Is there some advantage to having each attribute laid out contiguously in memory?


texts: NULL REFERENCE EXCEPTION Object reference not set to an instance of an object

texts:
So I have 3 scripts:

first for my player movementscript
second for my speed powerup speedscript
third for my obstacle box script i

I'm trying to get the component of box script in speed script, to get the function 'added' (which is in box script) into speed script but it keeps giving me nullreferenceexception error

Here are those scripts:

public class box : MonoBehaviour
{

    [SerializeField]
    GameObject effect;

    public int damage = 1;
    [SerializeField]
    float Speed =10f;
    [SerializeField]
    GameObject audioexplosion;

    void Update()
    {

        transform.Translate(Vector2.left * Speed* Time.deltaTime);

    }

    void  OnTriggerEnter2D(Collider2D col)
    {
        if(col.CompareTag("Player"))
        {
            Instantiate(audioexplosion, transform.position, Quaternion.identity);
            Instantiate(effect, transform.position, Quaternion.identity);

            movment tmp = col.GetComponent<movment>();

                tmp.health -= damage;
            Destroy(gameObject);
        }
    }
    public void added(float spd)
    {
        Speed += spd;
    }

}

And here is my speed script.

public class speedscript : MonoBehaviour
{
    [SerializeField]
    GameObject effect;
    [SerializeField]
    GameObject speedaudio;
    //[SerializeField]
   public float speed;
    public float add_v = 5;
    private float timeindue;
    //[SerializeField]
 //  public box io;

    void Start()
    {

     //  io= GetComponent<box>();
       // Debug.Log(io);
    }

    void Update()
    {
        transform.Translate(Vector2.left * speed * Time.deltaTime);
    }

    void OnTriggerEnter2D(Collider2D sp)
    {
        if (sp.CompareTag("Player"))
        {
            Instantiate(speedaudio, transform.position, Quaternion.identity);
            Instantiate(effect, transform.position, Quaternion.identity);
            box io = GetComponent<box>();
                Debug.Log(io);
                io.added(add_v);

                Destroy(gameObject);
        }
    }
}


texts: How to implement in-app-Billing in libgdx?

texts: I'm trying to implement in-app-Billing in libgdx game. Does someone have a working example? There is some explanation on developer.android but it's not helpful for libgdx.


texts: How do I calculate the bounding box for an ortho matrix for Cascaded shadow mapping?

texts:
I've been trying to get a cascaded shadow mapping system implemented on my engine, though it appears to be that the bounding boxes for the cascades aren't correct.
The part I'm interested in can be found here, under the function name "CalcOrthoProjs".
I've been trying to understand the matrix multiplications with this answer, and the ogldev variable and function names are kind of confusing me.
This is how I modified ogldev's function to work with my variables:
void Scene::calcOrthoProjections(Camera &camera, glm::mat4 LightView, std::vector<glm::mat4> &orthoContainer, std::vector<GLfloat> &cascadeEnd) {
GLfloat FOV, nearPlane, farPlane, ratio;
camera.getPerspectiveInfo(FOV, nearPlane, farPlane);
ratio = static_cast<GLfloat>(RE::config.height) / static_cast<GLfloat>(RE::config.width);

GLfloat tanHalfHFov = glm::tan(glm::radians(FOV / 2.0f));
GLfloat tanHalfVFov = glm::tan(glm::radians((FOV*ratio) / 2.0));

for (GLuint i = 0; i < NR_CASCADES; i++) {
    GLfloat xn = cascadeEnd[i]     * tanHalfHFov;
    GLfloat xf = cascadeEnd[i + 1] * tanHalfHFov;
    GLfloat yn = cascadeEnd[i]     * tanHalfVFov;
    GLfloat yf = cascadeEnd[i + 1] * tanHalfVFov;

    //The frustum Corners on View(Camera) space
    glm::vec4 frustumCorners[8]{
        //Near Face
        glm::vec4( xn,  yn, cascadeEnd[i], 1.0),
        glm::vec4(-xn,  yn, cascadeEnd[i], 1.0),
        glm::vec4( xn, -yn, cascadeEnd[i], 1.0),
        glm::vec4(-xn, -yn, cascadeEnd[i], 1.0),
        //Far face
        glm::vec4( xf,  yf, cascadeEnd[i + 1], 1.0),
        glm::vec4(-xf,  yf, cascadeEnd[i + 1], 1.0),
        glm::vec4( xf, -yf, cascadeEnd[i + 1], 1.0),
        glm::vec4(-xf, -yf, cascadeEnd[i + 1], 1.0),

    };

    //The frustum Corners in LightSpace
    glm::vec4 frustumCornersL[8];

    GLfloat minX, maxX, minY, maxY, minZ, maxZ;
    minX = minY = minZ = std::numeric_limits<GLfloat>::max();
    maxX = maxY = maxZ = std::numeric_limits<GLfloat>::min();

    glm::mat4 cam = (camera.getProjection() * camera.getView());
    glm::mat4 camInverse = glm::inverse(cam);

    for (GLuint j = 0; j < 8; j++) {
        //View(Camera) space to world space
        glm::vec4 vW = camInverse * frustumCorners[j];
        //world space to light space
        frustumCornersL[j] = LightView * vW;

        minX = min(minX, frustumCornersL[j].x);
        maxX = max(maxX, frustumCornersL[j].x);
        minY = min(minY, frustumCornersL[j].y);
        maxY = max(maxY, frustumCornersL[j].y);
        minZ = min(minZ, frustumCornersL[j].z);
        maxZ = max(maxZ, frustumCornersL[j].z);
    }
    orthoContainer[i] = glm::ortho(minX, maxX, minY, maxY, minZ, maxZ) * LightView;
 }
}

LightView represents a matrix created with:
glm::LookAt(-glm::normalize(light.direction), glm::vec3(0.0), glm::vec3(0.0, 1.0, 0.0))

camera.getProjection() returns the perspective matrix of the main camera
camera.getView() returns a LookAt at the objective the camera is looking at
The orthoContainer values are then fed into the depth rendering unaltered afterwards (by anything other than the model matrix of each model)
I wrote some comments on how I think the math is done, trying to understand what's wrong.
The result is a frustum too wide, resulting on low res shadows(even for the closest shadow map):

and this is the depth map of the closest shadow map:

any insight as to why this isn't working, or any other best practice advice, is welcome.


texts: Getting a texture from a renderbuffer in OpenGL?

texts:
I've got a renderbuffer (DepthStencil) in an FBO and I need to get a texture from it. I can't have both a DepthComponent texture and a DepthStencil renderbuffer in the FBO, it seems, so I need some way to convert the renderbuffer to a DepthComponent texture after I'm done with it for use later down the pipeline.

I've tried plenty of techniques to grab the depth component from the renderbuffer for weeks but I always come out with junk. All I want at the end is the same texture I'd get from an FBO if I wasn't using a renderbuffer. Can anyone post some comprehensive instructions or code that covers this seemingly simple operation?

EDIT:

Linky to an extract version of the code
http://dl.dropbox.com/u/9279501/fbo.cs

Screeny of the Depth of Field effect + FBO - without depth(!)
http://i.stack.imgur.com/Hj9Oe.jpg

Screeny without Depth of Field effect + FBO - depth working fine
http://i.stack.imgur.com/boOm1.jpg


texts:
As you see in this screenshot I must hover the mouse on that that spot to click on button in overall you must hover the mouse upper than button to click on it, tried to change the Sprite but even with default Sprite I have this problem so I don't think there is problem with Sprites.

Let me explain more about this panel:
In this scene I have two canvas's one for Pause button only and another one for this panel that is disabled. When you click on Pause this panel will appear ( second canvas will be activated. Why is that? I tried to change some things in the canvas like change UI scale mode to scale with screen size but no luck.
I will be grateful for help I don't really know where problem is.

Update : I just now found very odd behavior when hit play if mouse be in game view that problem wont occur, after mouse leave the button issue will appear again.


texts: I'm interested in working as an artist in the game industry.  Many job postings contain the phrase "pixel art".  What exactly is pixel art?


texts: I'm coding a game's GUI in SDL2 and c++, I'm using SDL_RenderCopy to load the buttons on to the screen, but don't know how to get buttons in specific spots eg. bottom left corner, slightly below center. How do I achieve this?


texts: so the other day I was looking for jobs in the gaming industry (software engineer/game programmer/gameplay programmer, etc) just to get a look at what are some of the requirements. Most of these jobs require 5+ years of experience with C++, and to be an "expert" in this language. My question is, what does exactly an expert in C++ need to know, apart from pointers, STL, memory allocation, inheritance, polymorphism? Do you need to know the programming language from A to Z? Every bit of the language? Or what are some of the most important topics that you need to know in order to qualify as a "C++ expert"?


texts:
Okay so I am quite new, I've got the player to move using up, down, right, and left. But what I am trying to do is make the character move with a left click.

var Player = function(id){
    var self = {
        x:250,
        y:250,
        id:id,
        number:"" + Math.floor(10 * Math.random()),
        pressingRight:false,
        pressingLeft:false,
        pressingUp:false,
        pressingDown:false,
        maxSpd:10,
    }
    self.updatePosition = function(){
        if(self.pressingRight)
            self.x += self.maxSpd;
        if(self.pressingLeft)
            self.x -= self.maxSpd;
        if(self.pressingUp)
            self.y -= self.maxSpd;
        if(self.pressingDown)
            self.y += self.maxSpd;
    }
    return self;
}

That's what I have for the up, down, left, right movement. I've seen a few documents stating the click but just can't seem to implement it into the file.


texts: How can I hook up player input to an action in RPGMaker?

texts:
How do I set a player input to perform an animation such as swinging a sword.

I tried doing it by creating a parallel process in which hitting z calls the following common event.

Change Party Member: Add [mage sheild], Initialize
Change Party Member: Remove [Mage]

Effectively making the animation a party member that can be switched to. This doesn't really work at all. I tried looking at Sapphire ABS to see how they do it, but I can't find a definition for $Game_player in the code. So I'm sorta incredibly lost.


texts:
I'm actually trying to do something fairly simple.

I cannot get multiple key presses to work in XNA. I've tried the following pieces of code.

else if (keyboardState.IsKeyDown(Keys.Down) && (keyboardState.IsKeyDown(Keys.Left)))
{
      //Move Character South-West
}

and I tried.

else if (keyboardState.IsKeyDown(Keys.Down))
            {
                if (keyboardState.IsKeyDown(Keys.Left))
                {
                      //Move Character South-West
                }
            }

Neither worked for me. Single presses work just fine. Any thoughts?


texts: Boundaries in game development: How do “professionals” do it?

texts:
How do professionals do boundaries in a 2D game? The way I do is say I don't want the sprite to move into a certain area:

//Example
if ((playerPosX >= 825) && (playerPosX  <= 910)&& (playerPosY >= 170) && (playerPosY <= 255)) {
    //do nothing
}else{
    //move
}

But some games out there have a lot of boundaries so I'm wondering, is there an easier way. I don't think there is any way someone would use the above method throughout a whole game, just to block of movement.

EDIT:
My question is mainly regarding a game where you can walk around, similar to Pokemon or final fantasy


texts:
I'm developing a simple "Geometry Wars" like game: 2D world and multiple enemy spaceships. The enemies should be able to pursue the player and avoid collisions between them at the same time. I've implemented a vector field algorithm based on this one. When two ships are too near between them, a force that slightly modifies the direction of the ship is created.

This works like a charm, the enemies pursue the player and no collision exits, but this happens sometimes:

This is because in one frame they "collide" and the path is modified, but, in the next frame they are not colliding and the path is not altered. This two states in loop cause that shaking.

Do you have any idea to solve this?

PS: if I didn't make myself clear, please ask me, english is not my first language


texts: Simplest most effective way to rank and measure player skill in a multi-player environment?

texts:
I know of the Truskill algorithm, it's quite complex but effective.

My question is there other algorithms/methods to determine a players skill for accurate measuring for multi-player competitive play?


texts:
So I have an fbx file with animations and materials on it. Simple stuff.

But when I change something on the fbx, like adjusting some animation, then re-export as fbx, Unity does not re-import the fbx when I do RMB -> Re-Import. It shows the loading bar but doesn't actually effect the current mesh by re-importing.

Is this normal?

Is there a way to re-import the fbx while keeping the modification I made on the mesh. Like, I changed the Scale Factor and some other things, so I want to keep these while re-importing.


texts: Moving object parallel to another on path on 2d space

texts: How to Move object parallel to another on curved path on 2d space


texts: Water shader in Unity3D not working on some Linux distributions/some Mac OS?

texts:
I've got reports from some Linux users that the game's water isn't rendered on his machine.
3 example operating systems:

Ubuntu 20.04 (with kernel 5.4.0-54-generic x86_64

Linux 4.15 Linux Mint 19.2 64bit

Mac OS X 10.13.6

I use this shader: https://roystan.net/articles/toon-water.html
I've made a small change so I can use it in orthographic projection as well:
            float existingDepthLinear = 0;

            if (unity_OrthoParams.w > 0)
            {
                // orthographic camera
            #if defined(UNITY_REVERSED_Z)
                existingDepthLinear = 1.0f - existingDepth01;
            #endif
                existingDepthLinear = (existingDepthLinear * _ProjectionParams.z) + _ProjectionParams.y;
            }
            else
            {
                // perspective camera
                existingDepthLinear = LinearEyeDepth(existingDepth01);
            }

            // Difference, in Unity units, between the water's surface and the object behind it.
            float depthDifference = existingDepthLinear - i.screenPosition.z;

I've got a feeling that
            #if defined(UNITY_REVERSED_Z)
                existingDepthLinear = 1.0f - existingDepth01;
            #endif

is what causing the issue.
When I remove it, on my PC, which was working well until now, the whole surface will be just foam. So plain white. Just like on their computers.
So maybe UNITY_REVERSED_Z is not defined?
What could cause this issue? Feel free to ask for more info, maybe I can provide.


texts:
I'm making a game for Android using Libgdx with Android Studio in Java. In my game, I have a class called ObjectFactory which has a method createGameObject(int objectType) which receives an integer from ObjectIds (a static class that hold a final static numbers for every object type: PLAYER = 0, BULLET = 1, ENEMY = 2 and etc...).

This method has a switch condition and 'till now I have reached 69 types of objects. The method gets the id, looks for it using the switch, creating that object and returns it. At the beginning it was comfortable using this way, but now it's really annoying looking for stuff over there because the switch statement is huge. This is an example of a case:

        case Rules.GameObjectIds.EXPLOSION:
            Explosion explosion = Pools.obtain(Explosion.class);
            explosion.init(getTextureAtlas(explosion, AssetsPaths.Gfx.Sheets.Misc.Explosion.DATA_FILE), AssetsPaths.Gfx.Sheets.ImagesNames.BIG_EXP, x, y, AssetsPaths.Configs.ParticleEffects.EXPLOSION);
            explosion.setDistanceInteraction(Rules.Misc.Explosion.BLAST_RADIUS);
            gameObject = explosion;
            listName = Rules.System.GameObjectTypes.EXPLOSIONS;
            createEffect(AssetsPaths.Configs.ParticleEffects.BLAST_RING, gameObject);
            createLight(explosion);
            break;

I'm thinking about a way to simplify the Object Factory, any suggestions?
Thanks in advance


texts: Logic and view separation but the view is generated by the logic

texts:
We are working on a simple turn-based card game. We would like to implement it using a design which let us create additional "monsters" and "events" later on (so the code should be flexible).

Also, we would like to separate the actual logic (who does what) from the presentation (view/rendering) so we could write a different renderer whenever we want (Unity, WPF, etc.)

This game is already playable on paper (we have a table, figures, cards, etc.) but we would like to speed up some things (for example the battle). And this would be a learning project. This is the reason why we would like to implement it in a nice way (instead of just "hacking" things together).

The main concept of the MVC pattern is to have the model, controller and view separated. In a fully-separated design the view can display the model by asking the controller to give some data. The view can also ask the controller to modify the model based on its input. However the controller has no knowledge about the view.

Our problem is that we would like to "generate the view" based on the "controller" (action). This might sound a little wierd but let me give you some examples:

In this game we have some special "event cards" and these are doing different things when the player meets with them. For example the "Wise" gives the player x gold based on a roll OR it gives the player his treasure if he has any. Since we are not storing the actual map in this program (we are playing on a physical table) the GM (Game Master) must choose the operation based on the current state of the game. This means that when the GM selects the "Wise" there should be two buttons, like "Give treasure" and "Give gold". This is when the controller/model/action defines the view.

Something like this:

GM selects the player
The player makes some action in real-life
When the player enters a zone where an "event card" can be found, the GM selects the right "event card" on his tablet (for example)
Then the selected event card defines the possible actions which defines the view (since the GM has to press some buttons)

It is not important that if we are generating the view (using a layout and filling it with text and buttons) or if we are creating the views by hand. The main problem is that we don't know how to "glue" them together. When the GM selects an event card, which view should we generate? Which button should execute which action? Sometimes a specific action requires another view to be shown. This seems like a hard coupling between the logic and the view.

Here is a mini code-snippet (note this is not the actual code, it's just an example).

interface IEventCard
{
    void Selected();
}

class Wise : IEventCard
{
    void Selected()
    {
        // add "Give treasure" action
        // add "Give gold" action
    }
}

class GameManager
{
    IList<IEventCard> cards;

    void Initialize()
    {
        // create cards
        cards = new List<IEventCard>();
        cards.Add(new Wise());
        // ...
    }

    // called from the UI
    void Select(int id)
    {
        IEventCard card = cards[id];
        card.Selected();

        // it should open a view
        // the view should be populated with:
        // - the name and description of the event card
        // - buttons that execute the corresponding action
        // some of these actions should open another views
        // for example the "give treasure" action should open the "inventory screen" which lets the GM select the item
        // or the "give gold" action should open a "roll the dice" window first to determine how much gold the player should get
        // etc.
    }
}

Sorry if it's hard to understand my description, I've tried to explain things as short as possible. We would appreciate if you could give us some tips, preferable some code snippets.


texts: How can I prevent a GameObject within a ScrollView from moving?

texts:
I have a ScrollView.  It has children, most of which I want to scroll, but some of which I want to remain still.  Think of something along the lines of a spreadsheet where the title rows/columns don't move.

I have somewhat succeeded, as the GameObjects I want to stay in their place do, but they are fighting the ScrollView to move.  It forces them to jitter every time I scroll.  Here is my current code:

private Vector3 originalPosition = Vector3.zero;

private IEnumerator Start()
{
    yield return new WaitWhile(() => transform.position == Vector3.zero);
    originalPosition = transform.position;
}

private void OnGUI()
{
    if (originalPosition == Vector3.zero)
    {
        return;
    }
    transform.position = originalPosition;
}

What is causing it to jitter?  And how can I fix it?

(The reason I am waiting to start updating is because my GameObject originally thinks its position is (0, 0, 0)...not sure why.  Maybe its related?)


texts: Unity - Top Down Perspective Camera to Orthographic size

texts:
I have a perspective camera with an fov of 60.
It looks at an object from top view with a rotation(90, 0, 0) and position (0, 50, 0)

The user has the option to change the camera to orthographic view to get a 2D view without any depth from top

Now how can i calculate the orthographic size so the view looks same as that in the perspective view(just not having the depth)?


texts:
Breathing (the movement of chest and face features): I'd like to ask if it is hard to model and whether it is computationaly expensive. I recently noticed the great effect it has in Madagascar 3 movie, but (please, correct me if I am wrong) don't remember seeing it in any games (except maybe steam cloud in cold/winter setting) and very few animated movies does that to noticable degree (e.g. when it is necessary by the plot or situation).

I'd greatly appreciate answers from both movie graphics and game graphics perspective.


texts: How can I draw a quad in wireframe with modern OpenGL, without rendering the interior bisecting edge?

texts:
I want to draw a quad (not two triangles). I actually know that triangles are faster, as I answered this question.

But let's say I am building a 3D modeling tool. It makes sense to draw a quad for the user (like Maya and 3D Max do) and not two triangles especially if he is actually working with quads. Is there any other option than using geometry shaders to accomplish this?

I understand that I can draw two triangles and make them co-planer. Unfortunately this will still make the two diagonal points connected, I don't want this. I want a pure quad. I don't want the line connecting the two points, Exactly like what you see in a modeling tool. I am actually rewriting a modeling tool that I wrote few years ago, and can't get the same behavior I got with the older OpenGL.

Here is an image of the tool I am re-writing using modern OpenGL. I used QUADS, so the question is about an alternative that gives this same behaviour especially I am using two pass rendering to render the model and it's outline. That's why I don't want the line separating the two triangles to appear.


texts: How can I manage large numbers of objects in a physics engine?

texts:
MY friend and I are programming a game and I decided to give the physics engine a try. I was able to get a class working where it would calculate out the total force on a model and apply the correct acceleration, velocity, and position during each time step.

My question is how do I implement this over many objects when the game starts to get big. Is there just one class managing all the physics calculations for each object or do you attach the physics engine class to each object in the game so that they update and manage their own physics?

I've looked through some code and I usually see people putting the velocity, acceleration, and position calculations right on the object itself. But somehow I think I'm getting the wrong interpretation of this and I think on a large scale, this would be very inefficient.

We don't want to use a pre-built physics engine because we want to learn about how this all works.


texts: SDL2: Why is my player's position not updating?

texts:
I've just started getting into game development, SDL in particular, so please go easy on me. I'm struggling to understand why my player's position isn't chaning when I press the left arrow button.

main.cpp

#include <iostream>
#include "SDL2/SDL.h"
#include "SDL2/SDL_image.h"

typedef struct
{
  float x, y;
  SDL_Texture *sprite;
} Player;

int processEvents(SDL_Window *window, Player *player) {
    SDL_Event event;
    int done = 0;
    while(SDL_PollEvent(&event)) {
        switch(event.type) {
            case SDL_WINDOWEVENT_CLOSE: {
                if(window) {
                    SDL_DestroyWindow(window);
                    window = NULL;
                    done = 1;
                }
            }
            break;
            case SDL_QUIT: {
                done = 1;
            }
            break;
        }
    }

    const Uint8 *keyState = SDL_GetKeyboardState(NULL);
    if( keyState[SDL_SCANCODE_LEFT] ) {
      player->x = 120;
    }
    return done;
}

void render(SDL_Renderer *renderer, Player *player) {
    SDL_RenderClear(renderer);

    SDL_Rect playerRect;
    playerRect.x = 0;
    playerRect.y = 0;
    playerRect.w = 32;
    playerRect.h = 32;
    SDL_RenderCopy(renderer, player->sprite, NULL, &playerRect);
    SDL_RenderPresent(renderer);
}

void update(Player *player) {
     player->x += 10;
}

int main( int argc, char *args[] ) {
    SDL_Window* window;
    SDL_Renderer* renderer;
    SDL_Event event;

    Player player;
    player.x = 50;
    player.y = 0;

    SDL_Init(SDL_INIT_EVERYTHING);
    window = SDL_CreateWindow("Dungeon", 100 , 100, 640, 480, SDL_WINDOW_SHOWN);
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    player.sprite = IMG_LoadTexture(renderer, "assets/player.png");

    int done = 0;
    while( !done ) {
        done = processEvents(window, &player);
        update(&player);
        render(renderer, &player);
    }
    SDL_DestroyWindow(window);
    SDL_DestroyRenderer(renderer);
    SDL_Quit;
    return 0;
}

Any help would be much appreciated.

Thanks :)


texts:
I am making RPG in OpenGl and I need to make some portals.
How should I render it if I want to see through the portal on the other side?


texts: How to hide Game Progress Files saved in Application.persistentDataPath in Unity Android

texts:
I am developing a game that saves its state in a text file. I am writing that file in Application.persistentDataPath but my issue is that the game progress file is available to user in Data/PACKAGE NAME/files/*.

How can I hide the game progress file so that user can't access the files ?


texts: How can I architect my game tools to allow for easy extension?

texts:
In the code for the toolkit for my game, I have a concept I've been calling "contexts."

Each context refers to, essentially, different tools (SelectionContext, DrawTerrainContext, et cetera) and contains contain "actions" which are added/removed from the undo history.

Some pseudo-code:

public abstract class Context
{
    public abstract void Initialize();
    public abstract void Destroy();
    public virtual void Update();
}

public interface IAction
{
    void Execute();
    void Undo();
}

public class SelectionContext : Context
{
    public override void Initialiize() { ... }
    public override void Destroy() { /... }
    public override void Update() {
        if(mouseDown && noSelection)
            startSelection();
        else if(mouseDown && !noSelection)
            expandSelection();
        else if(!mouseDown && !noSelection)
            finishSelection();
    }

    private class SelectionAction : IAction
    {
        private List<object> _oldSelection;
        private List<object> _newSelection;

        public SelectionAction() { ... }
        public void Execute() { ... }
        public void Undo() { ... }
    }
}

The above context may define things like a RectangleSelectionAction, EllipticalSelectionAction, et cetera.

Stacking them like this allows me to do things like select a section of terrain then go to a different context to change textures (or what have you), then return to the selection.

While this is an improvement over putting almost everything in one file it still seems a little strange to me having to define small private classes in each context for each of their major actions.

Is there a standard (or better) way of abstracting out different tools from the main toolkit program to allow for easier development of future tools?


texts: Unity (C#): How can I create dialogue to be used in my game? (also critique my system?)

texts:
I've created my own system for handling dialogue. There's a class for each 'node' or part of dialogue. It contains the following variables: identifier (identifiers are unique for each NPC, but not globally, ie "1", "2"), a text variable, a list of strings (which are the option button values), another list of strings (which contains option identifiers), and a string which is used for passing custom functions through. A collection of these Dialogue classes are made, and then stored in a dictionary, with the key of each being the identifier.

public string identifier;
public string text;
public List<string> options;
public List<string> optionIdentifiers;
public string onCloseFunction;

public Dialogue(string identifier, string text, List<string> options, List<string> optionIdentifiers, string onCloseFunction = "") {
    this.identifier = identifier;
    this.text = text;
    this.options = options;
    this.optionIdentifiers = optionIdentifiers;
    this.onCloseFunction = onCloseFunction;
}

At the start, the dialogue with identifier 1 will be chosen, and the text displayed, with each of the buttons.

If the first option is chosen, that is index 0 in the options list. The index selected is used to get the correct identifier from the identifier list, which will return "2_1". This is then used to find the next dialogue.

The system fortunately works, however I'm wondering if I've overcomplicated this, and if there's a simpler way to do this.

Building further on this, it isn't easy to sort out the conversations to appear in. I have made the class 'Dialogue' serializable, so the properties are displayed in the unity window. I've made a public array of dialogue, which then is turned into a dictionary with the corresponding key identifiers.

public Dialogue[] dialogueList;
public DialogueLibrary dialogueLibrary;

void Awake() {
    Dictionary<string, Dialogue> dict = new Dictionary<string, Dialogue> ();
    for(int i = 0; i < dialogueList.Length; i++)                // Add all dialogue from inspector into dictionary
        dict.Add(dialogueList[i].identifier, dialogueList[i]);
    dialogueLibrary = new DialogueLibrary (dict);
}

This allows me to add dialogue as such:

The biggest problem I have with this, is the fact that it's just... not very nice to deal with. For example, if there were 30 pieces of dialogue, and I wanted to add another between 2 and 3, I would have to either increase every identifier afterwards, or use something like 2a for an identifier. Furthermore, it would be a lot better if I could read the dialogue list from an XML file.

What I'm stuck with is how I can create this XML file. I need some software that can simply create the conversations and export them in XML. Honestly I'm not sure how to go about this. Is there any software which exists already which could do something like this, or should I create my own in Visual Studio? I'm not sure how I'd go about creating something like this in visual studio. Ideally the software would be similar to mind maps, where the node of text is the dialogue text, and the connecting arrows have text on, and are equivalent to the options. Identifiers should ideally handle themselves.

Can anyone give me any pointers in what direction I should take, and if the direction is creating my own program, could anyone suggest any resources which would help me?

I understand this is a long message and I'm asking a lot, but any help, comments or even constructive criticism on my system would be greatly appreciated. Thanks in advance.


texts: How to work with smaller intermediate textures in OpenGL and GLSL?

texts:
I'm working on a project rendering water simulated through smoothed-particle hydrodynamics (SPH) with a non-photorealistic look to use in games.

In the actual stage of the project everything about this rendering is done through OpenGL and GLSL in C++, with many shader steps that stores intermediate textures in FBOs, which are later used in a final shader that brings everything together.

Everything is working fine, except for the framerate, which lies below between 25 and 30 FPS in the better case, rendering everything, including the intermediate textures, in 1024x768 pixels. So, since some of these intermediate steps involve image smoothing algorithms that are time consuming, I thought of reducing the dimensions of the textures generated in intermediate steps to make them faster, trying to find a sweet spot between the level of reduction/performance (divided by 2, 4, 8...) and the rendering final visual.

My question lies precisely here: How can I work with smaller textures in intermediate steps and use them on a final shader step to render to a image in a bigger dimension?


texts: Android differences (Dalvik+Java vs Old School C++)

texts:
Developing in Android is going to be different for me, having spent the last 10 years coding games in C++. What's the main differences / pitfalls / bottlenecks to developing for the Android? My big worry is moving to Java, what am I going to miss most?

To be clearer: what would I miss if I coded the whole thing in Java compared to the way I normally code C++ for consoles?


texts:
I am referencing singleton script's object from another script and I wonder what is difference between this two, or if even work the second one properly?

GameManager.Instance.selectedBuildSite = GetComponent<BuildSite>();

VS

GameManager.Instance.selectedBuildSite = this;

The code is written inside BuildSite class which inherits monobehaviour


texts: i just chose unity as my game engine an i don't like the level editor, and i really enjoy gtkradiant, its really easy and fun to use. I was wondering if someone knows a way i can use my gtkradiant levels in unity, since i know gtkradiant is meant for id tech 3, but i heard there is some way you can import your radiant levels to unity, does anyone know how? also, if you guys dont know how, can you please tell me how to get id tech 3? i would enjoy using that engine knowing how great the graphics can be if you mod it the right way.


texts:
I'm building Runner Game.
 Ground Class.

public class Ground extends Actor {

private Texture texture;
private ArrayList<Vector2> groundLocations;
private float speed;
private float cameraLeft, cameraRight;
private int textureWidth;

public Ground() {
    this.cameraRight = Const.GAME_WIDTH + Const.GAME_MARGIN;
    this.cameraLeft = 0 - Const.GAME_MARGIN;
    texture = new Texture(Gdx.files.internal("ui/ground.png"));
    groundLocations = new ArrayList<Vector2>();
    init();
}

public void setSpeed(float speed) {
    this.speed = speed;
}

private void init() {

    textureWidth = texture.getWidth();
    float currentPosition = cameraLeft;
    while (currentPosition < cameraRight) {

        Vector2 newLocation = new Vector2(currentPosition, 0);
        groundLocations.add(newLocation);
        currentPosition += textureWidth;
    }

}

public int getFloorHeight() {
    return texture.getHeight();
}

@Override
public void act(float delta) {
    super.act(delta);
    int size = groundLocations.size();

    for (int i = 0; i < size; i++) {
        Vector2 location = groundLocations.get(i);
        location.x -= delta * speed;
        if (location.x < cameraLeft) {

            location.x = findMax().x + textureWidth;
        }
    }

}

private Vector2 findMax() {
    return Collections.max(groundLocations, new Vector2Comparator());
}

@Override
public void draw(Batch batch, float parentAlpha) {
    super.draw(batch, parentAlpha);
    for (Vector2 location : groundLocations) {
        batch.draw(texture, location.x, location.y);
    }
}

public void dispose() {
    if (texture != null)
        texture.dispose();
}

}

Ground Texture is 128x128
GAME_WIDTH = 1024f
GAME_MARGIN = 250f
speed = changes.

While the ground is moving according to Speed and FPS. (Speed * delta)
Problem is : There are always Gaps between ground Textures. after certain Movement
function findMax finds the texture with the biggest X
any help would be Appreciated.

Solution:

  for (int i = 0; i < size; i++) {
        Vector2 location = groundLocations.get(i);
        if (location.x < cameraLeft) {
            location.x = findMax().x + textureWidth;
        }
        location.x -= delta * speed;
    }


texts: 3DS Max MassFX -- Animation to XNA without bones/skins?

texts:
I made a model in which a number of cobble stones fall into a hole using the rigid bodies in 3DS Max 2012 MassFX. They are just editable polys, no skin, no bone. I want this to play (Take 001, 0-100 frames) when the game loads the mesh. I haven't found a way to get to the animation though.

Does anyone have suggestions? All the tutorials for animated skinned models don't seem to work with a model set up like this? Do I really need to give each of 145 rocks a bone? If so, does anyone have a suggestion how to streamline that, or if there is an alternate solution to achieving this effect? The animation only needs to play once when the game starts, and that's it.

Thanks.


texts:
I am trying to define texture2d objects as shared. The reason of why I am trying to do is, I made an xna user control and my project loads unlimited (as much as the user wants) my XNA User Control. And all of the textures are same. I don't want to load textures for everyone of them (think how much ram size it will use if I do it)

The real problem is:

cmMaps = New ContentManager(Services, "Maps")

As you see, ContentManager news ServiceProvider for initialization. When I look at the codes where Services variant modified, I see this lines:

GraphicsDeviceService = GraphicsDeviceService.AddRef(Handle, ClientSize.Width, ClientSize.Height)
m_services.AddService(Of IGraphicsDeviceService)(GraphicsDeviceService)

Why I can't define global Texture2D objects. Why is it specific for the window or control that the XNA tries to draw on?

Is it possible to define em as shared variant and able to use it in every XNA UserControl?

Note: I took UserControl source codes from this page:
http://xbox.create.msdn.com/en-US/education/catalog/sample/winforms_series_1


texts:
I've been writing some server code recently and I ran into a bottleneck.
If a server is capable of sending data at 60hz, with 1 client it would send data to that client at 60z, with 2 clients this would drop to 30z, then with 3 clients to 20hz,etc... This is because the server can only send data to one client at a time, Is my logic correct here? For example, if I had 50 clients and I wanted each client to receive 60 updates per second the server would have to tick at (60hz x 50 clients)  3000hz!?

Is there a more efficient way this is done?


texts:
I have a game object on screen represented by a cube (but say it was a quad or something else all the same).

How do I raycast to check intersections? Keeping in mind I may not be raycasting fora  physical object, just a gameobject of any sort.

Another question I have is, how can you raycast in Unity3D just to check against an intersection against anything in general (say the first gameobject to be hit)?


texts:
I'm using LibGDX and Tiled. I need to render a Texture for my repeated background, then myTiled map and finally the sprites.

My problem is that if I put mapRenderer.render() between batch.begin() and batch.end(), the background texture is not being rendered.
If I render the map before or afterthe batch, some objects are hided.

So the logic of what I want to do is:

public void render(float delta) {
  // update

  // clear screen

  batch.begin();

  // draw repeated background texture

  // draw map
  mapRenderer.setView(camera);
  mapRenderer.render();

  // draw sprites

  batch.end();
}

Any idea what I might be missing and how to fix it?

Edit

Followup question, to make sure that what I'm asking is valid.
I was under the impression that calling batch.begin() and batch.end() multiple times was inefficient. But from what I've been searching it seems that it's not. I was confusing it with creating more than one SpriteBatch.
So I guess it's fine to do more then one begin/end call in each frame?
Sorry if my question is trivial, but I'm new to LibGDX.


texts: unity editor support 3.5 .net or lower, plugin targeting 4 .net is not supported by unity editor?

texts:
I am trying to import some libraries in my unity project but keep getting the above error. Kindly help. Also, if anyone has some some image processing within unity,please point some useful libraries.

When I changed the framework to .net 4 and added the assembly reference to my project, I could compile my unity script but still there were errors like unloading broken assembly, this assembly can cause crashes in runtime. and the library I am trying to add is ConvNetSharp.


texts:
In a top down shooting game, what alternatives are there for input if I want the direction of movement to be independent from the direction I'm shooting at? I'd like to avoid shooting with the mouse as it's much too precise, but alternatives that make it harder to aim could also work.

Alternatives I've already considered are:

Arrows for movement and WASD for shooting. The Binding of Isaac does this and it has two problems. It only allows for shooting in four directions, where I'd prefer at least eight; and most keyboards start ignoring some key presses if you press more than 2 keys at one, making it impossible to move in a diagonal while shooting.
Arrows or WASD for movement, shooting direction becomes fixed  in the direction you are facing when you start shooting. I don't remember where I saw this. This allows for shooting on any direction, but you have to stay still for a moment to change shooting direction, and it just doesn't feel very dynamic.


texts:
How can I create a geometry shader that can handle multiple primitives? For example when creating a geometry shader for triangles, I define a layout like so:

layout(triangles) in;
layout(triangle_strip, max_vertices=3) out;

But if I use this shader then lines or points won't show up. So adding:

layout(triangles) in;
layout(triangle_strip, max_vertices=3) out;
layout(lines) in;
layout(line_strip, max_vertices=2) out;

The shader will compile and run, but will only render lines (or whatever the last primitive defined is).

So how do I define a single geometry shader that will handle multiple types of primitives? Or is that not possible and I need to create multiple shader programs and change shader programs before drawing each type?


texts: pointers to member functions in an event dispatcher

texts:
For the past few days I've been trying to come up with a robust event handling system for the game (using a component based entity system, C++, OpenGL) I've been toying with.

class EventDispatcher {
  typedef void (*CallbackFunction)(Event* event);

  typedef std::unordered_map<TypeInfo, std::list<CallbackFunction>, hash_TypeInfo > TypeCallbacksMap;

  EventQueue* global_queue_;

  TypeCallbacksMap callbacks_;

  ...
}

global_queue_ is a pointer to a wrapper EventQueue of std::queue<Event*> where Event is a pure virtual class. For every type of event I want to handle, I create a new derived class of Event, e.g. SetPositionEvent.

TypeInfo is a wrapper on type_info.

When I initialize my data, I bind functions to events in an unordered_map using TypeInfo(typeid(Event)) as the key that corresponds to a std::list of function pointers. When an event is dispatched, I iterate over the list calling the functions on that event. Those functions then static_cast the event pointer to the actual event type, so the event dispatcher needs to know very little.

The actual functions that are being bound are functions for my component managers. For instance, SetPositionEvent would be handled by

void PositionManager::HandleSetPositionEvent(Event* event) {
   SetPositionEvent* s_p_event = static_cast<SetPositionEvent*>(event);
   ...
}

The problem I'm running into is that to store a pointer to this function, it has to be static (or so everything leads me to believe.) In a perfect world, I want to store pointers member functions of a component manager that is defined in a script or whatever. It looks like I can store the instance of the component manager as well, but the typedef for this function is no longer simple and I can't find an example of how to do it.

Is there a way to store a pointer to a member function of a class (along with a class instance, or, I guess a pointer to a class instance)?

Is there an easier way to address this problem?


texts:
In the game that I am currently making the play character is supposed to hover off the ground. I had used the code from the Hover Car tutorial on the unity website however this causes a lot of fluctuation in height even when staying still on a flat surface. This is a problem because the game is supposed to be in the first person. Is there a way to make the player character more stable?

public float hoverForce = 65f;
public float hoverHeight = 3.5f;
public Rigidbody playerRB;
// Start is called before the first frame update
void Start()
{
    playerRB = GetComponent<Rigidbody>();
}

// Update is called once per frame
void FixedUpdate()
{
    Ray ray = new Ray(transform.position, -transform.up);
    RaycastHit hit;

    if (Physics.Raycast(ray, out hit, hoverHeight))
    {
        float proportionalHeight = (hoverHeight - hit.distance) / hoverHeight;
        Vector3 appliedHoverForce = Vector3.up * proportionalHeight * hoverForce;
        playerRB.AddForce(appliedHoverForce, ForceMode.Acceleration);
    }
}


texts: How can I get the user altitude from an iPhone using Unity 3D?

texts:
I can see in the Unity 3D documentation that its possible to get the altitude of the user from their iPhone, but I cannot figure out how to actually do it.

I try this code:

using UnityEngine;
using System.Collections;

public class Altitude : MonoBehaviour {

    void Start () {
        Input.location.Start();
    }

    void Update () {
        Debug.Log (LocationInfo.altitude);
    }
}

and I get this error:

  Assets/Altitude.cs(11,41): error CS0120: An object reference is
  required to access non-static member
  `UnityEngine.LocationInfo.altitude'


texts: Why would some PNG files extracted from games display incorrectly?

texts:
I've noticed extracting PNGs from some game files that the image becomes distorted part-way through. For example, here are a couple of PNGs extracted from the Textures file in Skyrim:

Is this some unusual variation on a PNG format? What modifications would I need to make to view such PNGs properly?


texts:
I've have read this interesting question, where is explained how to simulate positional sound with the left and right channel; but still I wonder: is it possible to simulate positional sound (with headphones) when the source is "in front" of you, "behind", "above", or "below"?

Again, all I can do is to adjust left/right volume.

EDIT: I can also alter the playback rate (pitch) of the sound, ranging from double to half the original pitch.


texts: Deferred Rendering With Diffuse,Specular, and Normal maps

texts:
I have been reading up on deferred rendering and I am trying to implement a renderer using the Sponza atrium model, which can be found here, as my sandbox.Note I am also using OpenGL 3.3 and GLSL. I am loading the model from a Wavefront OBJ file using Assimp. I extract all geometry information including tangents and bitangents. For all the aiMaterials,I extract the following information which essentially comes from the sponza.mtl file.

Ambient/Diffuse/Specular/Emissive Reflectivity Coefficients(Ka,Kd,Ks,Ke)

Shininess

Diffuse Map

Specular Map

Normal Map
I understand that I must render vertex attributes such as position ,normals,texture coordinates to textures as well as depth for the second render pass. A lot of resources mention putting colour information into a g-buffer in the initial render pass but do you not require the diffuse,specular and normal maps and therefore lights to determine the fragment colour? I know that doesnt make since sense because lighting should be done in the second render pass.

In terms of normal mapping, do you essentially just pass the tangent,bitangents, and normals into g-buffers and then construct the tangent matrix and apply it to the sampled normal from the normal map.
Ultimately, I would like to know how to incorporate this material information into my deferred renderer.


texts: How to make inputing large inputs more engaging

texts:
I asked this question on another exchange "Encrypted content in games" and it made me wonder about game design.

The basics of that question is that you are using user-input, either directly or indirectly through the current game state, to generate a decryption key which unlocks/decrypts some secret content. This input would be the solution to some puzzle or come from a series of clues.

The problem is that the input space has to have high entropy to prevent it from being brute-forced, even by a computer. Having a series of levers would mean you need to have 90-120 or so of them. If I want a shorter input like let's 7, then you need 7500 different symbols to match those 90 levers which is way to many for people to distinguish between.

So I would like to hear ideas about how you could make an engaging/fun input method with high entropy. Ideally one that's visible to the user, meaning that the user is aware of it and not happening in the background.

Here is one example I thought about:

Imagine a secret altar outside of any quest lines. In front of it are 10 slots. Any of the 500+ game objects can be placed in the slots. Based on the game objects used and their permutation, a unique decryption key is generated using the object's game-IDs. Then the clues to what objects to use and in what order could be cleverly hidden through the game or somewhere else.

It still suffers from users possible being unable to effectively distinguishing the 500 different objects in the game. Also if your game is small and doesn't have that many objects it doesn't work.