texts: Architecture for game character movements with user input and a finite state machine

texts:
I have a JavaScript canvas game setup using Phaser framework. When I first made my character able to run, jump, and crouch, I used lots of if/else conditions and ended up with an ugly, buggy mess. I have read some articles about finite state machines and that seems to be the solution I need.

I am using javascript-state-machine and can't work out what kind of logic belongs where. My old logic looked something like this:

function update() { // ticks every frame
  if (cursors.right.isDown && !jumping && !crouching) {
    runRight(); // set character velocity and animation
  } else if( // more absurd complexity
}

What should be my first thought when trying to add a movement to the character? Do I think about the input first or define a state on the state machine first?

What exactly is a state? You can be moving right and jumping, but also moving to the right and not jumping. How are those movements described in terms of states?

What checks the user input for keys that are pressed or released and how does that interact with the changing of states?

A very helpful answer would include a psuedo code example of running and jumping that uses javascript-state-machine. I've read this interesting article that addresses character movement with an FSM, but I'm unable to apply those principles in JavaScript, with Phaser, and with this FSM library.

Here's some code from my most recent refactoring attempt in case it helps. I doubt it's even on the right track.

hero.sm = StateMachine.create({
  initial: 'standing',
  events: [
    {name: 'move', from: ['standing', 'jumping'], to: 'running'},
    {name: 'jump', from: ['standing', 'running'], to: 'jumping'},
    {name: 'stop', from: ['running', 'jumping'], to: 'standing'},
  ],
  callbacks: {
    // onEVENT
    onmove: (event, to, from, direction) => {

    },
    // onSTATE
    onrunning: () => {

    },
    // onSTATEleave
    onrunningleave: () => {

    }
  }
})

hero.update = () => {
  if (cursors.right.isDown || cursors.left.isDown) {
    hero.sm.move(cursors.right.isDown ? 'right' : 'left');
  } else {
    hero.sm.stop();
  }
}


texts: Provide A Scrolling "Camera" View Over A 2D Game Map

texts:
I'm in the process of attempting to create a 2D MMO type game with Kryonet and some basic sprites, mostly for my own learning. I have the back end set up great  (By my standards) and I'm moving on to actually getting some things drawn onto the map.

I cannot for the life of me figure out a solid way to have a "Camera" follow a player around a large area. The view pane for the game is 640 x 480 pixels, and each tile is 32x32 pixels (Thats 20 tiles wide and 15 high for the viewpane)

I have tried a couple things to do this, but they did not seem to work out so well. I had a JScrollPane with 9 "Viewpane"-sized canvases in it, and tried to have the JScrollPane move in accordance with the player. The issue came when I reached the end of the JScrollPane. I tried to "Flip" canvases, sending the canvas currrently drawing the player to the middle of the 9 and load the corresponding maps onto the other ones. It was slow and worked poorly.

I'm looking for any advice or previous experience with this; any ideas?

Thank you!

Edit and Clarification:
I did not mean to mention Kryonet, I was merely providing peripheral information in case there was something that would help which I could not foresee.

Instead of having an array of 9 canvases, why not just have one large canvas loading a large map every once in a while? I'm willing to have "load times" where as with the canvas array I would have none (in theory) to give the user a smooth experience.

I could just change the size and location of the map with a modified setBounds() call on the canvas in a layered pane (layered because I have hidden swing items, like inventories  and stuff)

I'll try it out and post here how it goes for people asking the same question.


texts: How to control in the vertex shader where pixel ends up in the renderTarget?

texts:
What if I have an arbitrary renderTarget, that is smaller than the screen (say it is 1x1 pixel) and I want to make sure in the VertexShaderFunction that all my pixels end up exactly in that 1 pixel region? No matter what I do, they all seem to get culled at some point, though GraphicDevise.Clear() works OK.

Where is the top left corner of the renderTarget Vertex-shader-vise? I tried output.Position = (0,0,0,0)/(0,0,0,1)/(1,1,1,1)/(-0.5,0.5,0,1) NOTHING works!

Fullscreen quad is not an option 'cause I actually need to process geometry in the shaders to get the results I need.


texts: Need advice for 3D BSP based graphics engine

texts:
I have coded myself a OpenGL BSP viewer for an old game format. It is very similar to the Quake 3 file format. Because my interest is developing graphics engines, I want to be developing while looking at using current technology. So I turn to you, the experts on the subject for direction of what to focus on. I would like this to be as fast as possible and considering the old file formats are very simple and have few polygons, I think it should be doable. Here are my questions:

Lighting
a. Does it make sense for me to learn vertex lighting or should I just implement per pixel lighting instead?
b .I know OpenGL has an 8 light limit. Should I realistically only use one of those for ambient light and the rest computer through shaders? If not, what should I do?
Sorting/Culling
a. What is the fastest most common used algorithm for sorting surfaces to render. Complexity is not really an issue. I want to learn what is currently being used and ways to really only render the things I can see. I have seen a number of algorithms described like the painter's algorithm and am wondering what makes the most sense for BSP based geometry.
b. If I have textures with alpha masks, I was told that sorting has some sort of involvement with this process. How do I allow them to render correctly in 3d space?
Graphics Pipeline
a. Should I be sending my geometry data via VBOs? Is this the standard used today?
b. If I have a number of "regions", possibly 200-300, should I find a better way to send them to the GPU without sending 200-300 chunks. Should I combine them into one and keep a reference associated with each.

Any other tips for BSP based rendering and things of that nature?

Also, if I said something that was incorrect, please correct me. I'm that person who would rather be corrected and slightly embarrassed than ignorant and unaware.

Thank you for your time. I really do appreciate it.


texts:
I am concerned about performance with my current setup; as I want to expand on it i need to figure out if I might need to change it.

Current Setup:
The Game/Prototype is similar to Dwarf Fortress or Rimworld. The world i have is tile based and procedural. It is made up of chunks(16x16). All chunks are connected not via coordinates but via pointers (chunk on the east, chunk in the north, chunk in the south and so on). Each chunk segment (or block/ tile) holds an entity(which can be the player, the human or a plant).
Lets say one Entity (for a example a human) walks towards the edge of the chunk and wants to know what is the tile next to him. Then i will have to look at min 8 tiles next to him. Due to the chunks only being accessible through neighbors, I have to always check wether the position relative to the entity is in a new chunk and how many chunks i have to iterate through to get to the position asked for. It is quiet the hassle and i can imagine it becomes a big performance problem once i want to do pathfinding.

Now some Questions:
How do games like Factorio handle this type of data gathering. In an Array i could easily figure out where to look. How do i retrieve individual Tile Information from a tilebased procedural World fast? Should i use coordinates or relative Positions(like i do now)?


texts: How to linearly transform vertices for large coordinate systems

texts:
Alright, so I'm working on a space game and well, I want it to have a lot of space! So I need a large coordinate system and for my rendering pipeline to not suffer from "vertex jittering" due to floating point rounding errors introduced in the world to view space matrix transformation.

So far I'm having some luck with a technique discusses in GPU Pro that was used for Just Cause 2. However, it's not quite there. It looks like the "world" (including the player's ship) is orbiting around my camera instead of the camera adjusting it's orientation and position to stay behind the player's ship when it rotates. It doesn't do this with the traditional World x View x Projection transformation.

Anywho, the technique basically merges the world and view space's translation matrices by translating directly to the object's offset from the camera.

The transformation is

objectScale x objectRotation x objectOffsetFromViewPosition x viewRotation x Projection

Where the offset is a translation matrix built from the object's world position - view position.

I've always built my view matrix simply using the XNA library's XMMatrixLookAtLH() function so I'm thinking I might be missing another vital aspect of the view matrix transformation. My view rotation matrix at the moment is only built from a quaternion representing the camera's orientation.

What am I missing or what is the correct way to build this transformation?


texts: Get SFML to report the version of OpenGL that is being used

texts: How can I get SFML to report the version of OpenGL that is being used by the render window?


texts: Is there a way in the UE4 to make a decal such as a blood decal and give it a physical object? I want to do it so that I can add a sound affect when the player walks on the physical object, a box trigger wont work as when the player stands on it the sound will keep playing and repeating even if the player isn't moving.


texts: What is the difference between expand(), grow() and fill() in libGDX?

texts:
I am currently working with scene2d tables. But I am tired of using hit and trial to make the layout I wanted. Can anyone explain the meanings of expand, fill and grow? I need the behaviour like wrap_content and match_parent as in android.

Some code I tried is:

    Table contentTable = scoreDialog.getContentTable();
    contentTable.debugAll();

    Table topTable = new Table();
    topTable.debugAll();
    topTable.top();

    topTable.add(timeImage).colspan(2).pad(5);
    topTable.add(timeProgressBar).colspan(5).pad(5);
    topTable.add(bonusLabel).colspan(3).pad(5);
    topTable.row();
    topTable.add(alignImage).colspan(2).pad(5);
    topTable.add(alignProgressBar).colspan(5).pad(5);
    topTable.add(penaltyLabel).colspan(3).pad(5);

    contentTable.row();
    contentTable.add(topTable).colspan(10).pad(5).expandX().align(Align.center);
    contentTable.row();

    contentTable.add(scoreLabelDialog).colspan(10).pad(5).expandX().align(Align.center);
    contentTable.row();

    starsTable = new Table();
    starsTable.setHeight(50);
    contentTable.add(starsTable).pad(5).colspan(10).expandX().align(Align.center);


texts: How does one disable the right-click context menu in Flash?

texts:
I happened to play around with habbo.com social game portal.

It clearly uses Adobe Flash as platform (if you look into the source code of the HTML page). But when you do right mouse click you don't get the Flash right-click menu popping up!

Does anybody have an idea how this is done?


texts: Get all the gameobjects for a SceneManager scene in Unity

texts:
I'm using the new SceneManager to load multiple scenes in the same structure adopting the Additive method. I find it extremely useful but I wonder if there is a way to get all the GameObjects for a specific scene. When multiple scenes are loaded I see the GameObjects clearly separated by scene in the hierarchy but I cannot find a way to access the specific hierarchy of a single scene via script. Is that possible?
The findGameObject method I think returns the GameObjects for all the scenes..


texts: Would creating a player scriptable game using Unreal Engine or Unity violate their license agreement?

texts:
I want to create a game in Unity or UE4 which allows the user to write scripts in Python and run them mainly to control the AI. I will have to find a way to enable runtime script execution first. After searching the internet i was able to find some ways that may work.
What i cant find an answer for is how to limit the parts of engine and game code the user has access to so that the player doesnt feel like he's playing it in God mode.
And the main question is that even if i am able to restrict access to the API will it violate the terms of agreement for these commercial engines because the player will get access to the underlying engine and will be manipulating objects within it. I don't intend to make a moddable game just a game that requires you to write some code but that would be an extreme case to think about.


texts:
I would like to render an OpenGL scene with an arbitrary number of point lights (at least 1024) with shadows enabled.

My current method of rendering shadowmaps, however, cannot do this.

Let me explain

There are only 32 textures you can pass to a fragment at a time.

I am using 31 of those 32 textures for shadowmaps at the moment.

pseudocode for my main code...

setShader("DepthBufferPointLight", -1); //the int is actually numlights, used for deciding whether or not to recompile a finalpass shader. Irrelevant in this stage and set to -1 for debugging purposes.
FBO fBO* = CreateFBOs[6 * numLights]
for (int j = 0; j < 6; j++)
for (int i = 0; i < 6; i++)
{
 setRenderTarget(fBO[i]);
 setupCameraforLight(j,i); //Move the camera to the right position
 renderSceneDepth(); //Textures aren't even rendered for this
}
setRenderTargetDefault();
setShader("FinalPass", numLights); //The shader dynamically recompiles for final pass calls if the number of lights has changed, because it will need to change how many uniform struct lights there are.
setLightTextureUnits(fBO, 6, numLights); //glActiveTexture calls and glBindTexture calls
renderSceneFinalPass(); //Textures and uniforms are all set up for this, also does the lights

and then in the shader pipeline I do my calculations using the shadowmaps.
My pseudocode is rough but you get the picture.

(SIDE NOTE: the dynamic recompiling is actually really simple and only changes one line of the shader, and I'm going to deprecate and remove the function once I figure out how uniform variable arrays work...)

my code breaks after numlights*6 is greater than 31.

Is there a better way to do this?

my ultimate goal is to render an arbitrarily high number of point lights using shadow mapping


texts: Are there any issues with not drawing to all render targets when using MRT?

texts:
Lets say I set 2 render targets:

device.SetRenderTargets(color, depth);

And then half my draw code only outputs color and not depth. This works fine on the PC and produces the expected results however I feel like this might be an issue on the Xbox.

Are there any issues I should be aware of when using MRT while only outputing to one render target?


texts:
I've tried several methods to switch between two views in my program. I've tried creating a new thread then have the view run for 5 seconds before creating intent to start my main activity. This is the code snippet from the said view class:

mHelpThread =  new Thread(){
        @Override
        public void run(){

            try {
                synchronized(this){
                    // Wait given period of time or exit on touch
                    wait(5000);

                }
            }
            catch(InterruptedException ex){
            }

            finish();

            // Run next activity
            Intent intent = new Intent(Intent.ACTION_MAIN, null);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            //stop();
        }
    };

    mHelpThread.start();

I can access the said view without error but it doesn't disappear after 5 seconds nor did it switched to main view when I even utilized an onTouchEvent() to detect touch on the screen of which it should have automatically closed.
I've also tried adding a button on the said view to manually switch to main view:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.help);
    final HelpView helpView = this;
    final Button btnback = (Button) findViewById(R.id.back);
    btnback.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v) {
            Intent intent = new Intent(helpView, MainActivity.class);
            startActivity(intent);
        }
    });

}

These codes worked, though, for creating a launcher for my program. So I thought that it would work the same if I added an option for help/rules(for the game) that would switch to another view. I've only since started using eclipse for android so pardon my lack of knowledge. Here is also the snippet from my manifest:

<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="MainActivity"
        android:label="@string/title_activity_main">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.DEFAULT"/>
        </intent-filter>
        <intent-filter></intent-filter>
    </activity>
    <activity android:name="SplashScreen"
              android:theme="@style/Theme.Transparent">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity android:name="HelpView"
              android:theme="@style/Theme.Transparent">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.DEFAULT"/>
        </intent-filter>
        <intent-filter></intent-filter>
    </activity>
</application>


texts: How to play GameObject (ParticleSystem) and stop?

texts:
Have a game where you've to shoot somethings and when you hit the GameObject I've should play. I've tried with Instantiate but I can keep shooting even if the gameobject is destroyed. What should I do in order to fix it?

 public GameObject particlesystem;

 void Start () {
    particlesystem= GameObject.Find("Effect");
 }

 void Hit(){
 Destroy(gameobject)
 Instantiate(particlesystem, transform.position, transform.rotation);
 }

This is how I handle it now, but as I wrote earlier I can keep activating the particle system.


texts: Dependency setup between libGDX projects in Eclipse IDE

texts: For my game I'd like to create another project that extends the functionality of libGDX and since it will be an independent project it could be easily reusable. How can I achieve this in Eclipse IDE? Do I have to use any building tools like Ant or Maven? I'd prefer not using them but I also don't want that the libgdx.jar file to get in the final jar twice. Do I have to create a full libGDX project (with gdx-setup-ui) for the extension project or is it enough to create a simpe Java Project and add the libGDX library?


texts: ScriptableObject referencing a gameobject in scene

texts:
What I'm using for the scriptableobjects that requires a reference of a gameobject in scene is for scheduling events like for moving. Meaning a scriptableobjects should have a gameobject or waypoint for an npc to go to.

Is there a workaround to scriptableobject to have reference of a gameobject in scene? Or are there any better ways to do this?


texts: What part of my engine should load images and fonts?

texts:
Right now, I have an AssetLoader interface, which has one implementation per platform. There can only be one instance of it, because it has some state (e.g. the path to the APK on Android).

It has two methods (the game doesn't have sound):

Pixmap loadImage(String path)
Pixmap loadText(String text, String fontFamily, int fontSize)

While that works well enough in practice, I feel this is bad design. In particular, I have two issues with it:

I have to duplicate image and font loading. It's not exactly the same code, because there are different methods used for loading from the file system and loading from a ZIP file, but I could certainly just load a font or an image into memory and return that.
loadText does a bit much at the moment: It loads a font from the disk, renders each glyph of the text onto a pixmap and returns that. More unnecessary code duplication.

What do you think, is this as bad as I think it is? How would you address it?

I don't insist on having a single AssetLoader with one implementation per platform, so please don't hold your suggestion back because it would get rid of that. In fact, I'm not perfectly happy with the beast, but can't think of a nicer approach.


texts: Loading non-skeletal animation to opengl via assimp

texts:
I'm a newbie in assimp and openGL. I'm trying to import .fbx or .dae formatted file to openGL via assimp.
Importing skeletal animation was kind of easy. Lots of introductions and sample projects helped me to run several files properly.
But, in case of none skeletal animation(does it named 'vertex animation'?), which has no bone, I can't find any of source, instructions, including assimp tutorials.
Or, I'm not sure it is even possible, maybe assimp doesn't support this kind of animation.
Is there any recommendable project for non skeletal animation? Any single comment, will be helpful.
Thanks.


texts:
My simple canvas game seems to work fine on Chrome and FF on Mac/Linux. I haven't had chance to test it on smart phones or Windows environments yet. It doesn't use double buffering but I have seen some JS Canvas examples using it.

When is the use of the double buffering recommended?
Does it make difference only for specific browsers?
Is there a significant performance hit?

Thanks!


texts: Limiting a player's movement to the screen's dimensions

texts:
I have a player, that I can control using WASD. And I don't want him to leave the screen.

So I've tried the following:

if (player1.getX()+5 < 974 && player1.getX()-5 > 0) {
    if(Keyboard.isKeyDown(Input.KEY_D)) {
        player1.addForce(5, "d");
    }
    if(Keyboard.isKeyDown(Input.KEY_A)) {
        player1.addForce(5, "a");
    }
    if(Keyboard.isKeyDown(Input.KEY_W)) {
        player1.addForce(5, "w");
    }
    if(Keyboard.isKeyDown(Input.KEY_S)) {
        player1.addForce(5, "s");
    }
} else if(player1.getX() >= 974) {
    player1.addForce(5, "a");
} else if(player1.getX() <= 0) {
    player1.addForce(5, "d");
}

It actually works, but the player gets stuck at the edge of screen, and can't move anymore. Any ideas why? Or rather, how do I make a proper collision detection?

NB: 1024 is the width of screen. And my player is 50 pixels wide, thus the 974. I am only working with X at the momemnt, to try getting it to work.


texts: I'm making a 2D sidescroller (although it's technically being made in 3D), and I need to freeze a player's position temporarily. With a RigidBody, this would be simple, but I can't think of how to do it with a First Person Controller besides saving a player's position and setting it back to that position every frame, which is very inefficient.


texts:
I created a particle effect using a material created from Particles/Simple Lit shader with an image of white circle tinted red through Start Color setting. On the left I have Alpha Blending Mode and on the right Premultiply Blending Mode.

Why do I get black lines on the left?


texts: Weird black lines when rendering in my Java Game Engine

texts:
I have an issue regarding weird horizontal and vertical lines that occur in my game engine. The lines is in the background color. It occurs when I draw a lot of tiles in this way:
for (int y = iy; y < camera.getY() + renderer.getpHeight(); y+= image2.getHeight()) {
    for (int x = ix; x < camera.getX() + renderer.getpWidth(); x+=image2.getWidth()) {
        renderer.drawImage(x, y , image2);
    }
}

The lines appear when I move the "camera" around.
The way I am rendering the tiles is not a good way to do it, which I have understood due to the drop in FPS. I am currently thinking on a way to make it more optimized. I don't think that the bad optimization is the reason for the black lines however. Here is a GIF of the phenomenon:


texts: Android Jump&Run - Random map generation

texts:
I'm pretty new to game development but I work on an android app.
It's a 2D Jump and Run game.

I do it in Eclipse and the map is readed out of a txt file right now.
But I want to do a Jump and run game, where the player must jump over holes in the ground.
Theses holes should be created randomly. So I want an infinite map, which is created randomly.
Can somebody give me tips how to begin with this? How can I do a randomly generated map?
I don't want the full code or something else, just a little tip how to start because I don't know how I can do this randomly generating.

Thanks in advance! Hope u know, what I mean!


texts:
I'm currently trying to make a small ball-like game in C++. I have two disc-like objects with varying radii. Let's say Disc 1 is on coordinates (100,0) and Disc 2 is on coordinates (400,0). Now Disc 1 has a velocity vector of (300,0) and Disc 2 has a velocity vector of (-300,0). In my program, the Discs just swap places and no collision happens.

Now how do I program in the collisions? Do I have to program my own manual raycasting or something?


texts: Will a Game written using HTML5 work on smartphones?

texts: I would like to write a game that could be played on smart phones and was wondering if HTML5 might be a way to write games to work on a wide selection of smart phones.


texts: How would one get the pixel value of a texture under the cursor?

texts:
I have a requirement to detect which pixel of a texture is under the cursor in the 3D world. I assume that Ray casting is involved however, after that I'm not sure how one would accomplish this.

Can anyone please point me to an example? Preferably one that does not require a PhD to understand... lol


texts: How can I access to all component of a certain type in Unity?

texts:
I want access to (for example) all AudioSources in Unity and stop all sounds.

using UnityEngine;
using System.Collections;

public class StopAllSound: MonoBehaviour {

    void Start() {
        AudioSource[] allMyAudioSources = GetComponents<AudioSource>();
        allMyAudioSources.Stop();
    }
}

This does not work, because of the followin error:

Assets/SlowMotion.cs(8,35): error CS1061: Type `UnityEngine.AudioSource[]' does not contain a definition for `Stop' and no extension method `Stop' of type `UnityEngine.AudioSource[]' could be found (are you missing a using directive or an assembly reference?)

I try it by FindObjectsOfType:

using UnityEngine;
using System.Collections;

public class SlowMotion : MonoBehaviour {

    void Start() {
        AudioSource[] allAudioSources = UnityEngine.Object.FindObjectsOfType<AudioSource>();
        allAudioSources.Stop();
    }
}

but I get the same error.


texts: How do I move a unit one grid-square-width per button press in Unity3D?

texts:
I'm learning Unity. I'm making a 2D top down Frogger-esque game. I was wondering how you would go about making the player move x pixels per button press.

I have this code to move him, currently with a float for x and y inputs, so he moves slowly:

    Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

    if (movement_vector != Vector2.zero)
    {
        anim.SetBool("isWalking", true);
        anim.SetFloat("input_x", movement_vector.x);
        anim.SetFloat("input_y", movement_vector.y);
    }
    else
    {
        anim.SetBool("isWalking", false);
    }

    rbody.MovePosition(rbody.position + movement_vector * Time.deltaTime);


texts: Equation to make small number big and big number small (gravity)

texts:
I have a sprite that I want to speed up as it gets closer to another object. I really want this to flow well and don't want a series of if statements. All I can think of is to take the distance and have some equation pump out a number that slowly rises as the distance decreases.

But for the life of me I can't think of a way to do this, though I'm sure it's possible. My mathematics knowledge is just too lacking to think of the tools I need for this.

Here's a pseudocode breakdown:

50->(function)->1.2
20->(function)->1.8

Than I'd could do something like:

speed = speed*1.8

I've thought about it and I think this would be similar to gravitation, I've tried some googleing, is there anyone that can point me in the right direction


texts: Checking whether a specific key was pressed in enchantJS

texts:
I am using enchantJS and would like to use the letters and numbers as well as numpad on a keyboard to do different things (eg: hotkeys).

From this page http://users.csc.calpoly.edu/~foaad/enchant/guide/playerInput.html

  By default, enchant.js provides input listeners for six buttons: UP, DOWN, LEFT, RIGHT, A, and B. By default, the directions are bound to the arrow keys. Any of the six buttons may also be bound to any key with an ASCII value. We’ll address that later.

So enchant provides the ability to bind keys to different input such as up, down, left, right...but how can I simply check whether the D or X key was pressed, and if so, perform certain actions based on that event?


texts: overlapping 3d particles not blending nicely when at the same z

texts:
I'm working on a 3d particle emitter.  It's going pretty good but I'm still having a problem with triangle sorting.

As you can see in the photos, there are some particles that are not blending properly presumably because of sorting.  I do sort my quads before I draw them back to front.  And they are all being drawn in a single glDrawElements(GL_TRIANGLES... call.

Blending is on & depth buffer is on.  Depth buffer has to be on because of the other 3d objects in the scene that are sometimes in front and sometimes behind the particles.

When they're moving in a z space they're sorting better and you don't see it as much:

I'm using a sort with the following compare:

int compare (const void *a, const void *b) {
   Particle *ia = (Particle*)a;
   Particle *ib = (Particle*)b;

   float t = ib->distanceToCamera - ia->distanceToCamera;
   if (t<0) {
       return -1;
   }
   return (t>0);

}

But I think there are times when some particles have the same z and then they're not blending nicely.

One thought was to somehow force them to not be the same z.  But with them moving on their own I'm not sure about that.

QUESTION - if overlapping triangles are close in z space but not equal, and still drawn back to front within the draw command, could they still overlap like this?

ANSWER - I set a break point and printed out all my structures to find that there are a ton of quads in the same z.  In groups.

Using the advice from the checked answer I was able to fix it. By making sure to render the solids first and the particles last I don't need to worry about writing to the depth buffer while rendering the particles. In my game they're all like gases, smoke and air. So they all need to blend with each other and on to things deeper in the scene than them.  When I start to render the particles I set:

glDepthFunc(GL_LEQUAL);
glDepthMask(GL_FALSE);

And when I'm done rendering them I return it to:

glDepthFunc(GL_LESS);
glDepthMask(GL_TRUE);

And look at the result:

What I believe was happening was that as particle triangles were drawn if they were on the same plane they were writing to the depth buffer and then the next one on that z if larger would get masked. By turning off depth mask it doesn't write to the mask as it's drawing the particles so they're not masking each other any more.  Since I draw them last they don't need to mask other things.

UPDATE: Another benefit I just figured out. Now I don't have to sort the particles at all. The sort was only to make them draw properly with the depth test on. And that's no longer needed. So I have that savings as well.


texts: What is the design rationale for having armor and magic penetration mechanics?

texts:
It seems to me that the penetration stat found in many games adds needless complexity and often is not easily understood.

It is obvious to a player that if they are taking a lot of damage, then they need to get armor.

An opposing player then has to decide whether or not to get an item to do more damage or an item to do armor penetration.

The answer is often not obvious.  The player could look up definitions and statistics on the web and not get a clear answer.  They can scour forums and find several different explanations both for and against one or the other.

To me this seems needlessly complex. If more damage can't scale with more armor, then shouldn't damage be buffed or armor be nerfed? Am I missing something obvious?


texts: Does Unity have existing support for Timelines?

texts:
I am planning the development of a game in Unity3D, and trying to come to terms with what the engine has already provided, and what I must code myself.

The game itself is going to be a rhythm game, which means synching audio and graphical events so that they always play when they're supposed to. What I'm looking to avoid is a potential scenario of lag where either the audio or the graphics starts to progress faster than the other.

When we discussed this type of coordinating system in my game design class back at university, my professor called this type of design a "Timeline" class. The idea being that you can instantiate one or more of these to progress at different rates, schedule things to happen in the future, and synch up periodic events. However, calling this a "Timeline" class seems to have been limited to my professor himself, as googling for whether a certain API features "Timeline" functionality has been a fruitless endeavor.

Is there some more common name for this kind of functionality? Does Unity have any pre-existing methods to coordinate the scheduling of events like this, or is this the kind of thing that needs to be built onto the engine? And if it does, I'd appreciate being pointed towards some tutorials!


texts:
I want to be able to change the game speed, to speed up or slow down all animations and gameplay. Ideally, this could also be set to a negative number to make everything go backwards.

I tried this:

I made everything dependent on a time variable, updated every frame from the OS time:

void calledEveryFrame()
{
    time = System.accurateTime();
}

Then I tried just scaling that time.

lastTime = time;
long now = System.accurateTime();
double diff = now - lastTime;
time = (lastTime + diff * speed);

That obviously doesn't work, because you can't just multiply the speed times the difference because it is not called exactly regularly.

How do I do this correctly?


texts:
I'm currently using Imgui for the GUI part of my OpenGL/C++ engine with the GLFW binding. The problem is though that this binding has encapsulated the input callbacks in a global .cpp file which makes it impossible to access for other classes. Now I could always use the regular routine to handle input without the callbacks like:

if(glfwGetKey(m_window, GLFW_KEY_A) == GLFW_PRESS)
   ...

but yet this won't give me the one-to-one mapping like the key callback provides as the conditional code is processed more than once. I have tried using static booleans without success to see if I could overcome the problem by setting the boolean to true when the key is pressed in the callback and then handling the outcome elsewhere. I also know that you can override callbacks with different ones but that would not make any sence in this case.

Does anyone know how to solve this problem?


texts: Unity - DontDestroyOnLoad - FindObjectsOfType(GetType()).Length is always returning 1

texts:
I'm trying to have an object with the DontDestroyOnLoad property. I want an object with NetworkIdentity to persist across scenes, so I can have a holder script for RPCs.

This answer suggests the following code:

public void Awake()
{
    DontDestroyOnLoad(this);

    if (FindObjectsOfType(GetType()).Length > 1)
    {
        Destroy(gameObject);
    }
}

Despite this, I still end up with duplicate objects. FindObjectsOfType(GetType()).Length is always returning 1, and I don't know why, or how to fix it. It makes no difference whether this object is a prefab instance or a simple object in the hierarchy.

I have also tried to clone this object in my NetworkManager script, which is automatically persistent, but GameObject.Find("ObjectNameHere(Clone)") is always returning false. However, the above solution seems simpler so I'd prefer to figure out  FindObjectsOfType(GetType()).Length.


texts: Asset is up to date but does not have a correct hash assigned in GuidPersistentManager

texts:
I have a ScriptedImporter that generates a few extra assets, this works fine except when I re-import it after version upgrade, I get the following message:

Asset with guid 'bbe94cef9d5f3464ab6ba6913e6747a2' and path '...' is up to date, but does not have a correct target hash assigned to it in the GuidPersistentManager
UnityEngine.UnitySynchronizationContext:ExecuteTasks()

Inside that ScriptedImporter I've tried File.Delete, AssetDatabase.Refresh, AssetDatabase.ImportAsset but neither helped out, only when I delete it manually it does work.

Furthermore, that error message is quite useless as basically Unity handles it but still notifies you.

Note that the asset generated is next to the format being imported, this is because if for instance you create a texture and add it to the AssetImportContext then it becomes readonly in the Inspector and cannot be tweaked further. So basically I generate a PNG file in same folder which then has the usual TextureImporter that can be edited as will.

Question:

How to avoid incorrect GUID errors when re-importing an asset generated by a ScriptedImporter?

Alternatively, how to solve this incorrect GUID clash when overwriting an asset?


texts: Procedural terrain generation is very slow

texts:
I've been trying to create procedural generated 2d terrain (similar to a game like Terraria) using Simplex noise. I was able to get the noise function working, and I set up a grid of 16 by 16 tiles that uses the noise to generate the height of the terrain. The problem is that the grid generation is rather slow. I often need to wait 5 - 10 seconds for a somewhat small grid to generate.

My code looks like this:

var level; // height of the terrain
generate_simplex_octaves2D(__largestfeature, __persistance, seed); // generate octaves using __largestfeature

for (var gy = 0 ; gy < global.__gridheight ; gy++)
{
    for (var gx = 0 ; gx < global.__gridwidth ; gx++)
    {
        level = (global.__gridheight div 2) + (100*get_noise2D(gx/100, gy/100, __octaves, __frequencys, __amplitudes)); // get noise value at point (gx/100, gy/100)
        if (gy > level) // if below level
        {
            global.__testgrid[# gx,gy] = TILE_FULL; // set grid position to a full tile
        } else global.__testgrid[# gx,gy] = VOID; // set grid position to an empty tile

        if (global.__testgrid[# gx,gy] == TILE_FULL) tilemap_set(global.testmap, 1, gx, gy);
    }
}

This creates terrain that looks fine, it's just too slow. I want to be able to generate terrain in real-time to create an infinite landscape. After doing some research, I found that I could maybe use a compute shader to have the GPU help speed up the generation, but I am not sure how to implement a compute shader in my case. Would I calculate the noise in a shader, or generate a noise map using one? Or do something else to generate the terrain faster?


texts:
I've been implementing John Chapman's method for SSAO (an excellent tutorial by the way), and I've completed it all minus the final part: blurring it. I believe this is what the entire process should be like:

First pass: render normals and depth to textures. (plus diffuse/specular albedo and such)
Second pass: render scene without ambient occlusion to texture, render ambient occlusion to another texture.
Third pass: blur the AO texture, multiply with scene texture for end result.

Then, if I wanted to implement bloom and depth of field, would I need yet another pass (or two)? Do modern games really go through a ton of rendering passes to add effects, or is there something obvious I'm missing? Some way to drop the number of passes needed?


texts: How do I keep my orbiting camera upright?

texts:
I am working on code that rotates the camera around a point on the in-game map when dragging the mouse. I understand how to lock it so it stays above the map surface.

However, if I keep rotating the view up, the camera will go "up and over" and be upside-down. How can I fix the camera orientation to make sure my camera stays upright?

A representative bit of code:

x += Input.GetAxis("Mouse X") * xSpeed;
y -= Input.GetAxis("Mouse Y") * ySpeed;

// when mouse moves left and right, rotate around local y axis
transform.RotateAround(target.position,transform.up, x);

// when mouse moves up and down, rotate around the local x axis
transform.RotateAround(target.position,transform.right, y);


texts: Crowd funded DLC. Is this a viable option for covering the development costs of DLC?

texts:
I have had this idea floating around in my head for a while now but I am not sure if it will work.

I was looking at the idea of DLC and thought what about if we made some DLC crowdfunded in order to incentivise the players to provide money to cover for the development of it.

Basically the modal I am pondering is this:
DLC is announced and a trailer is shown.
Next the announcement states that a crowdfunding campaign for the development of it has start and people are free to donate money as a backer. Backers get special rewards such as early access, their name included in the credits, etc.
Once the campaign is fully funded development starts immediately and a release date is announced.
Once the DLC is finished and ready for release, it is available for free because all costs have been covered.

The other version is to start development on the DLC right away and run the campaign at the same time.
If enough people back the project, in addition to the backer rewards, the DLC is released for free.

I am not so sure that this a good idea or not so this is why I am asking.


texts:
The script reference "manual" is not much of a help. When I look up createTileLayer(tileCountX/tileCountY/tileSizeX/tileSizeY) it doesn't say more than it creates a new TileLayer.

But, in what unit do I specify tileSizeX/Y?
Do I have to clean-up (delete) the created TileLayer when my game exits?

(There was no tag for Torque2D and I'm a little bit short on rep. points to create a new tag)


texts: how to implement pvp(text based rpg in php/mySQL)

texts:
I'm creating a text based rpg in php/mySQL and I've come up to a dead end in regards implementing the pvp aspect of the game. First off is this even possible in php/mysql? If so, how would I go about implementing it? I was thinking something like having an arena or room where you can go to battle. Then have a list of everyone else in the room who is looking for a fight. You can then make a request to fight someone from the list. Once the request has been accepted, then you can begin the fight. In terms of this mechanic, it seems to me something similar to what I am after is described in the following question: https://stackoverflow.com/questions/8934681/database-design-for-turn-based-game

P.S. The combat system is turn based. So first you attack, then the enemy attacks, and so on until you have a winner.


texts:
I have a vertical shooter, the game scrolls TMXTiledMap, and when it runs out I want it to load next map and scroll them seamlessly without interruption. How do I achieve that?

Here is my scrolling method, if I load another map it stops, I need to add scrolling to another map, is there a way around that?

- (void) update: (ccTime) delta

{
    CGPoint tempPos = myMap.position;
    tempPos.y -= 2;
    myMap.position = tempPos;
}

How do I load next map so they are scrolling seamlessly and connected to each other?


texts: How do you get a license from Marvel comics for game?

texts: I want to use Marvel comics character in my game but I don't know how to get Marvel comics character licence for game


texts: Cloning a Game - Dev diary while using original assets

texts:
I'm currently cloning a game and still using the sound and graphic assets of the original.

I know that I may not distribute those assets but what about publishing a video of my progress as part of a dev diary, is that allowed?

Thanks.


texts: Best approach to develop a mobile version of existing browser mmo game?

texts:
our team has developed a MMO browser game (HTML5, Javascript & PHP). The game is similar to Empire GG, Clash of Kings, Game of War etc.

We want to develop a mobile version and the question is which would be the most efficient way/ process we can take advantage of?


texts: Age Rating: female nipples poking through clothing?

texts: Pretty simple and straightforward question, what rating would a game get for something like this?


texts: MonoGame Shader - 2MGFX cant compile in SM4

texts:
am trying to compile three .fx custom shader files from a monogame sample project, i am tryting to get running for windows phone.

The GaussianBlur.fx file is:

// Pixel shader applies a one dimensional gaussian blur filter.
// This is used twice by the bloom postprocess, first to
// blur horizontally, and then again to blur vertically.

sampler TextureSampler : register(s0);

#define SAMPLE_COUNT 15

float2 SampleOffsets[SAMPLE_COUNT];
float SampleWeights[SAMPLE_COUNT];

float4 PixelShaderFunction(float2 texCoord : TEXCOORD0) : COLOR0
{
    float4 c = 0;

    // Combine a number of weighted image filter taps.
    for (int i = 0; i < SAMPLE_COUNT; i++)
    {
        c += tex2D(TextureSampler, texCoord + SampleOffsets[i]) * SampleWeights[i];
    }

    return c;
}

technique GaussianBlur
{
    pass Pass1
    {
        PixelShader = compile ps_4_0_level_9_1 PixelShaderFunction();
    }
}

I am trying to compile it using MG2FX.exe - I cloned the latest monogame develop repo and built the 2MGFX project x64|release

The command I run is - 2MGFX.exe GaussianBlur.fx GuassianBlur.mgfx

******* I can only get it to compile if use ps_2_0 - ps_4_0_level_9_1 fais to compile, saying error X3523: DX9-style intrinsics are disabled when not in dx9 compatibility mode. and ps_4_0 fails with Invalid profile ''. Pixel shader 'PixelShaderFunction' must be SM 3.0 or lower!

I have no idea how to set it to work with ps_4_0 - am I building 2MGFX incorrectly? all i did was open the project and press build.

Next, I am tryng to take the files and load them by calling

gaussianBlurEffect = Game.Content.Load<Effect>("Shaders/GaussianBlur.mgfx");

I am setting the mgfx file as content

But when I try to load it, I get an exception stating:

System.Exception: The MGFX effect is the wrong profile for this platform!

I am assuming that I need to get it loaded in ps_4_0 first, so my question is how can I get 2MGFX to recognize this? Then once I have built the mgfx file using 2MGFX, can I just load it like a normal .xnb file.


texts: What are "frame A" and "frame B" in btGeneric6DofConstraint's constructor for?

texts:
I have a very simple (and maybe too primitive to post here but I’ll try anyway :P) question about Bullet constraints. What are arguments const btTransform &frameInA, const btTransform &frameInB, bool useLinearReferenceFrameA of Bullet’s btGeneric6DofConstraint? Documentation doesn’t say anything about them.

I think (but am not entirely sure) that the first two are Pivot Point Transformations relative to mass-center of two rigid bodies (in their own coordinate systems). And thus they should always point to the same point in world-space. Is that true?

Also, what is Linear Reference Frame?


texts: Should Draw method calculate the element's screen location?

texts:
Should Update take care of calculating the drawing position of element or should it be done exlusively in Draw method?

If I calculate the drawing position of element in Update and then store it as element property then I can reuse it in Draw method. I can only run the update if the element (or camera) moved so it seems it would be good for performance. Is this good approach? Or should I never store the draw position of an element and always calculate it in Draw method?

EDIT:

It seems my question wasn't clear enough. I'm not talking about elements Draw method but the Draw method of manager/renderer that draws them on the screen. The elements themselves do not have Draw method.


texts:
Usual tetris game has 2D arrays for arena/piece and collision check with matrix comparison. To add smooth movement and auto alignment of pieces:

x and y are pixels on the screen

xMatrix [the cell that piece in it related to the x value]
yMatrix [the cell that piece in it related to the y value]
xCheck [(x +- amount) cell equivalent for collision check]
yCheck [(y +- amount) cell equivalent for collision check]
xOffset [x mod cell size]
yOffset [y mod cell size]

With These Updates New Game Loop:

if not collide(down)
    piece.y += amount
else
    merge

if left
    if not collide(left)
        piece.x -= amount
    else
        align

else if right
    if not collide(right)
        piece.x += amount
    else
        align

if key_release
    calculate_offset

if offset
    piece.x +- amount

is playable. But causes glitches on corner movements and out-of-bound errors for repetitive key presses sometimes. What can be the improvements on this code or what changes needed to be done?


texts: Set-up Android SDK path to make Android remote work in Unity

texts:
I am using the Unity 2019.1.12. If I go to Edit > Preferences... > External Tools it says that the Android SDK Tools Installed with Unity (recommended).

Now I downloaded the Unity Remote 5 to my Android device and try to debug a game in Editor.

But when I run the game I see the output in the Unity console which tells:

  Set-up Android SDK path to make Android remote work

So, should I unchek the check near the Android SDK Tools Installed with Unity (recommended), download the Android SDK myself and provide the path to it?

Are there any other ways to fix it? Because the Unity simplified the process of the installation of the SDK and it seems very sad that I can not use the Unity Hub for this purpose.

Thank you.

So, I went to the Unity\2019.1.12f1\modules.json file, found the path to the Unity SDK in the file. And provided the path manually. That solved the issue. But I do not like the solution, since it is supposed by the Unity Hub that the path to the SDK will be provided automatically.


texts:
I'm writing a Factorio mod, and I'm trying to figure out why it doesn't work. Can I do some kind of error / debug logging somewhere? Both manual (printing variables) and simple error reporting (accessing a property that doesn't exist) would be great. I know about the player.print method, but I can only get it to print string literals, not objects:

script.on_event(defines.events.on_player_created, function(event)
    pcall(function()
        local player = game.get_player(event.player_index)
        player.print("Hi player") -- works
        player.print(player) -- does not work. Any error message would be nice
    end)
end)

I've also tried the log file in the application folder, and the various debug modes (F5/F6 in game), but so far haven't found anything useful.


texts: Unity Vertex shader recalculate renderer bounds

texts: I've made a simple billboard gpu instancing vertex shader that manipulates the verticies of an object based on the projection matrix. The problem is that the renderer bounds does not update to encapsulate the object. If the objects render bounds goes out of view the objects dissapears because of frustrum culling, is there a way to recalculate the render bounds after manipulating the verticies or manually manipulate the bounds to be the maximum size that the object that be.


texts: Serializing object members within unordered_map and storing into binary file (C++)

texts:
I'm making a multiplayer game, the Server stores it's game world state as various std::unordered_map in a class
called ServerWorldState.

The server is composed by a single class called Game, which contains ServerWorldState.

Currently I'm trying to make Save() and Load() functions, which for now will be in the Game class. These functions
are supposed to save certain data from the maps within ServerWorldState into a binary archive, for this purpose, I'm
using Cereal library for serialization and the standard file IO streams.

Cereal requires a serialize method to be present in a class, in order for members to be specified for serialization:

ServerWorldState.h

class ServerWorldState : public World
{
private:
    std::unordered_map<int, ServerProp> props;
public:
    template<class Archive>
    void serialize(Archive& archive);

};

ServerWorldState.cpp

template<class Archive>
void ServerWorldState::serialize(Archive& archive)
{
    archive(props); //Serialize things by passing them to the archive
}

The ServerProp class actually has another serialize method within itself. I'm unsure if this is correct for specifying with further depth what object members should get serialized.

Save function from Game (load works very similar and has same problem, but since I haven't finished it's design I'm only showing save):

Game.h

class Game
{
private:
    std::shared_ptr<ServerWorldState> currentWorld;
public:
    bool Save();
};

Game.cpp

bool Game::Save()
{
    std::ofstream outfile("level.dat", std::ios::binary | std::ios::out);
    if (!outfile) {
        std::cout << "SERVER_WORLD_STATE::SAVE: Could not open world.dat file for saving!" << std::endl;
        return false;
    }

    {
        cereal::PortableBinaryOutputArchive oarchive(outfile); //Create an output archive

        oarchive(currentWorld); //Write data to the archive

    } //Archive goes out of scope, ensuring all contents are flushed

    outfile.close();

    return true;
}

In essence I want to serialize/deserialize and binary save/load the std::unordered_map in ServerWorldState, but I get this link error:

  Error LNK2019 unresolved external symbol "public: void __cdecl ServerWorldState::serialize(class cereal::PortableBinaryOutputArchive &)" (??$serialize@VPortableBinaryOutputArchive@cereal@@@ServerWorldState@@QEAAXAEAVPortableBinaryOutputArchive@cereal@@@Z) referenced in function "public: static void __cdecl cereal::access::member_serialize(class cereal::PortableBinaryOutputArchive &,class ServerWorldState &)" (??$member_serialize@VPortableBinaryOutputArchive@cereal@@VServerWorldState@@@access@cereal@@SAXAEAVPortableBinaryOutputArchive@1@AEAVServerWorldState@@@Z) - Game.obj line 1

I would asume this would show if the serialize method wasn't defined, but it is.
I also thought I might be missing some inclusion, but I seem to have all in order.


texts: Disabling object OnCollisionEnter and Enabling it On Collision exit

texts:
I have two objects that when they collide disable another gameobject. The problem is that I only want to have the other game object disabled while the two objects are touching and that I want to have it enabled again as soon as the two objects are no longer touching. My script is below:

using UnityEngine;
using System.Collections;

public class DestroyObject : MonoBehaviour {

public GameObject ObjectToDestroy;
public GameObject TheObject;
public GameObject Player;

void OnCollisionEnter(Collision col)    {
    if (col.gameObject == TheObject) {
        ObjectToDestroy.SetActive (false);
    }
}
}


texts: I built a character is ZBrush, added some subtools and extracts and realized I have to move the angle 'cause he is "falling". Is it possible to move him and all subtools around him at once (like groups in photoshop) or change the angle of the "Floor"?


texts:
I am developing my first iOS game on Unity. I spent a lot of time creating beautiful artwork for the game (characters and scenery). I gave testflight access to my friends and advisors, and they loved the game art, and asked me if I have ever thought about selling t-shirts or something.

I did some research, and found three services offering a SDK or plugin that lets me sell merchandise inside the game:

themonetizr.com
merch.amazon.com

First I thought about using Amazon, but then I saw that the monetizer actually lets players buy right inside the game (which is nice, as I would hate users to be directed to their browser) and they a lot more products, like phone cases.

Have you guys used any of these services before? How hard are they to integrate?

Thanks!


texts:
I am trying to implement shadow maps in my game following this tutorial. For some reason, the light is not being occluded.

In the above screenshot, the big white sprite in the foreground is a rendering of what the occlusion map looks like. In the background, you can see the result does not produce any shadows. It's hard to see, but in the top left it shows the shadow map.

Enlarged version of the shadow map:

The occlusion map and the shadow map seem to be generating correctly, so it must be an issue with how I'm taking it into account when rendering the light. Here is the fragment shader for the light:

#version 330

uniform sampler2D uDiffuseTexture;
uniform sampler2D uNormalsTexture;
uniform sampler2D uShadowMap;

uniform vec4 uLightColor;
uniform float uConstAtten;
uniform float uLinearAtten;
uniform float uQuadradicAtten;
uniform float uColorIntensity;

uniform vec4 uAmbientColor;

in vec2 TexCoords;
in vec2 GeomSize;

out vec4 FragColor;

float sample(vec2 coord, float r) {
    return step(r, texture2D(uShadowMap, coord).r);
}

float occluded() {
   float PI = 3.14;

   vec2 normalized = TexCoords.st * 2.0 - 1.0;
   float theta = atan(normalized.y, normalized.x);
   float r = length(normalized);
   float coord = (theta + PI) / (2.0 * PI);

   vec2 tc = vec2(coord, 0.0);
   float center = sample(tc, r);

   float sum = 0.0;

   float blur = (1.0 / GeomSize.x) * smoothstep(0.0, 1.0, r);

   sum += sample(vec2(tc.x - 4.0*blur, tc.y), r) * 0.05;
   sum += sample(vec2(tc.x - 3.0*blur, tc.y), r) * 0.09;
   sum += sample(vec2(tc.x - 2.0*blur, tc.y), r) * 0.12;
   sum += sample(vec2(tc.x - 1.0*blur, tc.y), r) * 0.15;

   sum += center * 0.16;

   sum += sample(vec2(tc.x + 1.0*blur, tc.y), r) * 0.15;
   sum += sample(vec2(tc.x + 2.0*blur, tc.y), r) * 0.12;
   sum += sample(vec2(tc.x + 3.0*blur, tc.y), r) * 0.09;
   sum += sample(vec2(tc.x + 4.0*blur, tc.y), r) * 0.05;

   return sum + smoothstep(1.0, 0.0, r);
}

float calcAttenuation(float distance) {
    float linearAtten = uLinearAtten * distance;
    float quadAtten = uQuadradicAtten * distance * distance;

    float attenuation = 1.0 / (uConstAtten + linearAtten + quadAtten);

    return attenuation;
}

vec3 calcFragPosition(void) {
    return vec3(TexCoords*GeomSize, 0.0);
}

vec3 calcLightPosition(void) {
    return vec3(GeomSize/2.0, 1.0);
}

float calcDistance(vec3 fragPos, vec3 lightPos) {
    return length(fragPos - lightPos);
}

vec3 calcLightDirection(vec3 fragPos, vec3 lightPos) {
    return normalize(lightPos - fragPos);
}

vec4 calcFinalLight(vec2 worldUV, vec3 lightDir, float attenuation) {
    float diffuseFactor = dot(normalize(texture2D(uNormalsTexture, worldUV).rgb), lightDir);

    vec4 diffuse = vec4(0.0);
    vec4 lightColor = uLightColor * uColorIntensity;

    if(diffuseFactor > 0.0) {
        diffuse = vec4(texture2D(uDiffuseTexture, worldUV.xy).rgb, 1.0);
        diffuse *= diffuseFactor;
        lightColor *= diffuseFactor;
    } else {
        discard;
    }

    return (uAmbientColor + diffuse + lightColor) * attenuation;
}

void main(void) {
    vec3 fragPosition = calcFragPosition();
    vec3 lightPosition = calcLightPosition();

    float distance = calcDistance(fragPosition, lightPosition);
    float attenuation = calcAttenuation(distance);

    vec2 worldPos = gl_FragCoord.xy / vec2(1024, 768);
    vec3 lightDir = calcLightDirection(fragPosition, lightPosition);

    lightDir = (lightDir*0.5)+0.5;

    float atten = calcAttenuation(distance);
    FragColor = calcFinalLight(worldPos, lightDir, atten) * vec4(vec3(1.0),
    occluded());
}


texts: How to stop 3D model from reflecting light like plastic

texts:
I was browsing SketchFab and found a 3D model I decided to try in Unity.

This is how the model looks in SketchFab's viewer:

When I put it in Unity, I used a Directional Light object:

As you can see, it looks like plastic. I have been playing with the light's intensity, but the model seems to always reflect light as if it were some sort of plastic (unlike SketchFab's viewer).

How can I make it look like the above image?

The model is https://sketchfab.com/models/1ee9b44352c840bda4202895948c30bb


texts: Too much delay while sending object over UDP to server

texts:
I'm getting 4 sec delay when sending objects over UDP. Working on small game and trying to implement multiplayer. For now just trying to synchronize movements of 2 balls on the screen. StartingPoint.java is my server(first player), that receiving serialized objects (coordinates). SecondPlayer.java is client that sending serialized objects to server.
   When I'm moving my first object it appears 4 seconds later on different screen.

StartingPoint.java

@Override
public void run() {

    byte[] receiveData = new byte[256];
    byte[] sendData = new byte[256];
   // DatagramSocket socketS;
     try {
        socket = new DatagramSocket(5000);
        System.out.println("Socket created on "+ port + " port");
    } catch (SocketException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    while(true){

        b1.update(this);
        b3.update();

        System.out.println("Starting server...");

        //// Receiving and deserializing object

            try {
                //socket.setSoTimeout(1000);
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                socket.receive(packet);

                 byte[] data = packet.getData();
                    ByteArrayInputStream in = new ByteArrayInputStream(data);
                    ObjectInputStream is = new ObjectInputStream(in);
                  //  socket.setSoTimeout(300);
                        b1 = (Ball) is.readObject();

            } catch (IOException | ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        repaint();

        try {       Thread.sleep(17);
        } catch (InterruptedException e) {
                e.printStackTrace();
        }

SecondPlayer.java

@Override
public void run() {

    while(true){

        b.update();
        networkSend();

        repaint();

        try {
            Thread.sleep(17);
        } catch (InterruptedException e) {
                e.printStackTrace();
        }

    }

public void networkSend(){

    // Serialize to a byte array
    try {
                ByteArrayOutputStream bStream = new ByteArrayOutputStream();
                ObjectOutputStream oo;
                oo = new ObjectOutputStream(bStream);
                oo.writeObject(b);
                oo.flush();
                oo.close();

                byte[] bufCar = bStream.toByteArray();

                //socket = new DatagramSocket();
                //socket.setSoTimeout(1000);
                InetAddress address = InetAddress.getByName("localhost");
                DatagramPacket packet = new DatagramPacket(bufCar, bufCar.length, address, port);
                socket.send(packet);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


texts:
I have an Artificial Networks which needs to recognize 130 different types of moves encoded in terms of 1s and 0s. Therefore the number of outputs I used is 8 so that all my patterns could be distinguished. However, by using 8 outputs, the different types of patterns possible is 256, leaving me with 126 different types of patterns useless.

Do these extra 126 different patterns ruin my ANN's ability? Is there a better way not to have these unused holes?


texts: I don't understand why one of my vbo is overwritten by another

texts:
to create a vbo I use this function:

    public void loadVBO(){
        vboID = GL15.glGenBuffers();
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboID);
        GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buf, GL15.GL_STATIC_DRAW);
        // Put the position coordinates in attribute list 0

        GL20.glVertexAttribPointer(0, 4, GL11.GL_FLOAT,
        false,4*4+4*4+4*4+2*4 , 0);
        // Put the color components in attribute list 1
        GL20.glVertexAttribPointer(1, 4, GL11.GL_FLOAT,
        false,4*4+4*4+4*4+2*4 , 4*4);
        GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT,
        false,4*4+4*4+4*4+2*4 , 4*4+4*4);
        // Put the texture coordinates in attribute list 2
        GL20.glVertexAttribPointer(3, 4, GL11.GL_FLOAT,
        false,4*4+4*4+4*4+2*4 , 4*4+4*4+4*4);

        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
    }

to display a vbo I use this function:

    public void displayVBO(){
            GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vboID);
            GL20.glEnableVertexAttribArray(0);
            GL20.glEnableVertexAttribArray(1);
            GL20.glEnableVertexAttribArray(2);
            GL20.glEnableVertexAttribArray(3);
            GL11.glDrawArrays(GL_TRIANGLES, 0, buf.capacity());
            GL20.glDisableVertexAttribArray(0);
            GL20.glDisableVertexAttribArray(1);
            GL20.glDisableVertexAttribArray(2);
            GL20.glDisableVertexAttribArray(3);
            GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
    }

So when I call map.loadVBO() and then ocean.loadVBO(), I think the second call overwrite the first vbo I don't know how ...

When I call map.display() and ocean.display(), I have the ocean draw 2 times ....

Thanks.


texts:
I have a collection of different enemies that I save as Prefabs with default AI settings. I drag them into the game world and apply changes to the AI as necessary.

Every now and then for some reason I happen to click on Apply Prefab at the top right of the screen. That obviously messes up my Prefab and depending on the settings that I changed also messes up ALL the other bots in the game world.

Yes, I shouldn't be pressing that button, but is there any way to set the Prefab to read-only not to accidentally override settings?


texts: How can I make message passing between threads in a multithreaded engine less cumbersome?

texts:
The C++ engine I'm working on currently is split up into several large threads- Generation (for creating my procedural content), Gameplay (for AI, scripts, simulation), Physics, and Rendering.
The threads communicate with one another through small message objects, which pass from thread to thread. Before stepping, a thread processes all of its incoming messages- updates to transforms, adding and removing objects, etc. Sometimes one thread (Generation) will create something (Art) and pass it to another thread (Rendering) for permanent ownership.
Early in the process and I've noticed a couple things:

The messaging system is cumbersome. Creating a new message type means subclassing the base Message class, creating a new enum for its type, and writing logic for how the threads should interpret the new type of message. It's a speed-bump for development and is prone to typo-style errors. (Sidenote- working on this has me appreciating how great dynamic languages can be!)
Is there a better way to do this? Should I use something like boost::bind to make this automatic? I'm worried that if I do that I lose the ability to say, sort the messages based on type, or something. Not sure if that kind of management will even become necessary.

The first point is important because these threads do so much communicating. Creating and passing messages is a big part of making things happen. I'd like to streamline that system, but also be open to other paradigms that might be just as helpful. Are there different multithreaded designs I should think about to help make this easier?
For example, there are some resources which are infrequently written, but frequently read from multiple threads. Should I be open to the idea of having shared data, protected by mutexes, that all threads can access?

This is my first time designing something with multithreading in mind from the ground up. At this early stage I actually think it's going really well (considering) but I'm worried about scaling, and my own efficiency at implementing new stuff.


texts:
I'm pretty new to direct x and c++, I have a problem with loading .obj files.
This is a cube

I think the problem is with creating vertices and indecies.
list<vertex> FinalVertices;

list<unsigned long> Indecies;
for (int i = 0; i < Faces.size(); i++)
{
    for (int j = 0; j < Faces.size(); j++)
    {
        if (Faces[i] == Faces[j])
        {
            cout << 'b' << endl;
            if (i == j)
            {
                FinalVertices.push_back(Faces[i]);
                Indecies.push_back(j);
            }
            goto a;
        }
    }
a:
    cout << ' ';
}


texts: UDP + digital signature vs TCP vs other solutions to guarantee message authenticity

texts:
TCP guarantees message authenticity rather reliably using packet sequence number.
Other option would be going with UDP and using digital signatures to make the message authentic.
What could be my other options (basically are there any I missed)?
Maybe there is some sort of framework which I could use which would allow me to plug into a game engine without writing all authentication logic(each time using tcp i would need that clients login into my system, with udp i would rely on client public signatures inside my db).

TY


texts: Ways to get around the limiting default terrain shaders in Unity

texts:
I am trying to use the Toon Rim Light shader for Unity however there are a few problems when trying to use any custom shaders for a terrain in Unity. The most well known is of course, that all textures immediately become a blurry mess and ruins the look. The other issue is that all shading on the terrain ceases to be, and causes it to not cast shadows for both nature objects as well as characters.

I have researched methods for circumventing this problem, however all sources for troubleshooting have been inadequate in providing enough details or steps in correcting the issue and I am left to turn here for a possible better breakdown of the processes and coding involved in achieving the effect that I desire.

Thank you in advance, I appreciate any help.


texts: Unity3D: collider performances on mobile iOS devices

texts:
I'm experimenting with Unity3D and colliders. Unfortunately I still don't have Unity Pro version and I can't use the profiler.

Consider the following situation:

mobile devices (ios, iphone 3GS).
an infinite runner game (consider something like agent dash or temple run). The player run along its path collecting bonuses and possibly hurting obstacles.
the number of objects along player's path is very high.

The first simple approach is to use a rigidbody with a collider attached to the player (let's say it could be even a shere collider) and use a collider for each object in the scene (coins, obstacles, bonuses,...) .

AFAIK, using hundreds of colliders could have a serious impact on performances,specially on mobile devices, am I right?

So here's some questions:

In the situation described above, is that feasible use collider to
detect objects collectable by a player running along a path?
Could be a better idea to store the location of the collectables
objects inside some kind of data structure and completely avoid to
use Unity collision detection?
What's a reasonable average number of RigidBody/Sphere Collider that can be used in a single scene on a mobile device?

Does anyone has implemented something similar? Could you suggest me the right way to go?


texts: Best way to connect and save data in an online Android game

texts:
I'm new here, I'm in need of a help as it would be the most ideal way to proceed with my project.

The project is very simple, a basic online rpg for android in specific (in the future can be migrated to other OS), done in unity3d and c #, at the moment I'm using the Photon Network to connect, but I do not know how to save the data Character, intended to connect to mysql and save the data.

Is this method good?

And which would be the most appropriate to save the data?

  Sorry Google Translated!


texts: Godot - Collision for character teleportation

texts:
I'm currently working on a little game to discover Godot game engine.
It's a Top-Down game and I want my character to be able to teleport through walls.
I thought to dupplicate my character's collision box and to set its position to the teleportation's position but I didn't find a way to check if there is a collision to this new position.
Any advise?


texts:
I'm attempting to import an FBX model from Blender into Unity, but the materials' textures aren't coming with it. I've made sure to name all my materials the same as the associated texture files and I've tried having the texture files in all sorts of locations, such as in the same folder as the .fbx or in a "Textures" folder.
I've tried importing the textures separately, the body texture goes onto the material correctly but with no transparency and the eye texture doesn't show up at all.
I've seen that some people's solution was the "Extract Textures..." button under Materials, but it's grayed out for me.


texts: How to check metadata stored in FBX files?

texts:
Is there a way to check and edit metadata information stored in FBX files? I'm using 3ds Max's fbx exporter. Can this be done with it or is there any other tool for that?

For example: adding name, contact info, tags or anything that provides ownership of the file.


texts:
I am trying to instantiate my fire particle system during runtime like this:

GameObject fire, firePrefab;

void Start()
{
    ...
    firePrefab = Resources.Load("FirePrefab") as GameObject;
}

void FixedUpdate()
{
   if (Input.GetKeyDown(KeyCode.V))
   {
       fire = Instantiate(firePrefab, transform.GetChild(3).position, transform.GetChild(3).rotation);
       Destroy(fire, 5.0f);
   }
}

My FirePrefab is just a regular particle system, and the model the above script is attached to looks like this:

  Model

    Default

    Camera

    DroneFire

However, my fire prefab isn't instantiated anywhere when I run the game.


texts:
Currently I am running my menu (with buttons "new game" and "choose level") as an xml view of an activity, that then starts my gameactivity with custom view run on a gameloop. But Im starting to see some restrictions with this.

Would it be a terrible idea to let the menu be part of the gameloop and just add another state for it, like gameState = MENU ? and then render and update touch accordingly.

Does anyone have any experience with this and if so how did you choose to solve it?


texts: Edit spawn location according to vector direction

texts:
I'm trying to make a turret in Bukkit (Java). This will shoot an arrow to the players that are in the shooting radius. But now I've a little problem, the arrow gets stuck inside the block where its spawned. Now I'm trying to spawn the arrow at the side of that block so it wont get stuck anymore, but I don't know how to calculate the best side of the block to set the new spawn location. Like North, East, South or West of the block.

So is there someone who can help me with this? Thnx!

Code that I use for now:

Vector v = pl.getLocation().add(0, 2, 0).toVector().subtract(loc.toVector());
Arrow arrow = (Arrow) Bukkit.getWorld(loc.getWorld().getName()).spawnArrow(loc, v, (float) 4, t.getAccuracy());

So the variable loc needs to be recalculated so it will be outside the block to the right direction from the vector 'v'.


texts: How to reproduce examples from ShaderToy on my computer?

texts: I am a beginner with computer graphics. I have some experience with drawing polygons, shaded surfaces, the use of geometry shaders, etc. I am trying to create a volumetric cloud/volume render shader like this, with techniques such as 'raymarching'. The problem is that I have understood that graphics are rendered throughout a pipeline (generate vertex information with cpu, store them in buffer objects, process them with the vertex shader and then render the image with the fragment shaders), so for me it is not clear at what stage of the pipeline the volumetric rendering is done, since the cloud is not made of polygons or vertex in general. My first step would be reproducing the same rendering from shadertoy, to understand the technique better, add parameters, lighting, etc. What kind of shader is it? how should I write a program to use it? I use OpenGL in Linux. Thank you in advance!


texts: Chunking/caching large levels in a singleplayer game

texts:
Does it make sense to try to offload a large nonlinear level into file-based chunks, and load those on demand? We've implemented level chunking to improve rendering performance, but still all level objects are persistent in RAM.

If yes, then how do we keep the illusion of a living/changing world? Since the level is not linear, but rather like a world in itself, we cannot just pretend that whatever one's gone through is gone forever.

Is it a better idea to make the levels complex enough, but also optimized enough to be always persistent in memory, but implement micro/macro jump points which allow one to jump to a totally distant point (i.e. a whole new level), thus forgetting about the world consistency, and the illusion of a changing world. Also, this would allow us to follow a slightly linear story in a seemingly non-linear world. It would be possible to just apply a new state to the existing state of a "distant" level, if we are to bring the player back to it.


texts: How can i change the hit distance of RaycastHit?

texts:
I'm using this script to send a raycast from the center of the camera to objects.
It's working fine but only if i'm getting close enough to objects. But for example if it's npc person i want to be able to detect him as "Interactable" from a more distance. How can i change/set the hit distance ?

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

public class CameraRaycast : MonoBehaviour
{
    public Camera cam;

    void Update()
    {
        Ray ray = cam.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
            if (hit.transform.tag == "Interactable")
            {
                print("I'm looking at " + hit.transform.name);
            }
            else
                print("I'm looking at nothing!");
    }
}


texts: How do I need to tag different (but a little similar) entities with Entity-Component-System pattern

texts:
I have some count of weapons - pistol, shotgun, rifle. And I have one system which deals with all weapons, and another system which deals only with pistol. So I need to create both components "weapons" and "pistol", and I add them both to the entity - "Pistol". So now we have next components - "Weapons", "Pistol", "Rifle", "Shotgun", becase probably I will need to have separate system for different weapons in future.
Then in the same reasons I create next Components - "Character", "Player", "Enemy", "Friend" (maybe more types of Enemies and Friends), "Ammo", "AmmoForPistol", "AmmoForRifle" ...
And there are too much different components only for tagging different entities regarding to the types.
How can I avoid this amount of Components?


texts: How to create a dynamic Map in Unity (Augmented Reality)

texts:
I created a dynamic map with a LineRenderer. The LineRenderer gets a new position assigned, for each movement my 'character' does. It works good, but I expect it to get a really bad performance at some point. Could you recommend a better solution to create a dynamic map with the free version of Unity.
My code looks like this at the moment :

        if (lastPosition != target.transform.position) {
            path.SetVertexCount(positionCounter + 1); //Path is the LineRenderer
            lastPosition = target.transform.position;
            path.SetPosition(positionCounter++,new Vector3(lastPosition.x,0,lastPosition.z));
        }

The LineRenderer lies on a layer, which can only be seen by my orthographic mini map camera.
Btw. I need it in a dynamic way, because it's an augmented reality app, which has no terrain which I could display on the map or stuff like this. I have to create the stuff which should be displayed.


texts: How to flatten the collider for a tilemap?

texts:
I am relatively new to game development, and am working on a simple 2D platformer. I have created a tilemap and painted some tiles for the character to walk on.. but he is getting stuck. Yes, I know this is a common question and I did find some answers (including this one: Player gets stuck on edges between TilemapCollider2D tiles), but none seem relevant for me. The thing is my tiles are not flat.. they have pointy edges due to grass.. see the image below:

As you can see, the edge is not flat. I have overcome the problem of getting stuck by changing the "Edge Radius" to what you see in the above screenshot and that works, but the character now looks like he is floating slightly above the ground. Is there any way I can just tell Unity to ignore the jagged grass and make the collider flat and move the edge of it down a bit? That way it would fix the issue and also have the added bonus of looking like some of the grass is behind him and some in front..


texts: Split vector vs matrix notation for transformation

texts:
Some rendering engines like Ogre prefer to use a individual vector based
notation for transformations like the following

Split vector notation:
Net Transformation is represented by
Scale vector = sx, sy, sz

Transformation vector = tx, ty, tz

Rotation Quaternion Vector = w,x,y,z

Matrix notation:
There are other engines which simply use a net combined transformation matrix.

What are the advantages of the first notation over the second?

Also for animation interpolation does it work in the first notation that we interpolate across
the individual components and use the interpolated parts to get the net transformation?
Is this another advantage?


texts: onClickListeners not working correctly (conflicting)

texts:
In my pause dialog, the exit is working correctly, but the resume isn't, if I press resume 3 times, the third time it's going to exit.

ImageButton btnPlayOn = UIFactory.createButton(txtrPlayOn);
btnPlayOn.setSize(40, 40);
btnPlayOn.setPosition(75, 75, Align.center);
dialogP.addActor(btnPlayOn);

ImageButton btnEndGame = UIFactory.createButton(txtrEndGame);
btnEndGame.setSize(40, 40);
btnEndGame.setPosition(75, 55, Align.center);
dialogP.addActor(btnEndGame);

btnPlayOn.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                System.out.println("resuumeeeeeeee");

            }
        });

        btnEndGame.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                System.out.println("exiiiiiiiiit");

            }
        });

I think I know why, it's because both buttons have the same x so the listener is getting confused. Anyhow I don't know how to fix it.


texts: I am running Python 3.5 and I want to install PyGame, the website only supports up to version 3.2. I have tried a few forums on this and other websites but they are all for Python 3.4. Does anyone know were I can find the install file for Python 3.5 and how to install it?


texts:
I have an OpenGL(3.3)+GLEW application.
I want to draw a black vertical rectangle at the left side of the window for writing some information on it, like fps (I use GLEW function for drawing text).

I have a common pipeline, like this:

 m_transformation = PersProjTrans * CameraRotateTrans *
           CameraTranslationTrans * TranslationTrans *
           RotateTrans * ScaleTrans;

I know how it works, but I can't figure out how to draw a projection of the rectangle on the window, like 2d.

I would be glad to any advise.


texts: Godot: How do I get the id mask for a physics layer by name?

texts:
I would like to figure out whether a collider is in a physics layer by the name (string) I set in project settings:

func _physics_process(delta):
    var collision = move_and_collide(direction * delta * speed)
    if collision and (collision.collider.collision_layer & get_collision_layer("Walls")) != 0:
        direction = direction.bounce(Vector2.LEFT)
    # more behaviors based on other layer tests

Walls is the name of the physics layer and I am trying to find get_collision_layer.

I am using Godot 3.2.1.  self is a KinematicBody2D & colliders are StaticBody2D's & also KinematicBody2D's.

I have figured out the collision id (as an int) but still think it would be cleaner to use layer names, preferably using a built-in function.


texts: How do I draw a sprite on top of a video in Andengine?

texts:
I'm playing a video in Andengine on

@Override
protected void onSetContentView() {}

However, when I place a sprite on the screen at some point in time, it is placed behind that video view. I want it to appear in front of it.

My attempt:

Entity foregroundLayer= new Entity();
foregroundLayer.attachChild(drag1);
scene.attachChild(foregroundLayer);

Setting setZIndex also didn't work

Here's a screenshot:

The world icon is half outside and half behind. It should be on top.


texts: Learning to code first game, few questions on basic game development and 3D

texts:
I've been programming for a while, and I'm concurrently learning how to make a basic game and slimdx, and wanted to talk to someone to hopefully get a few pointers. I've read that Tetris is the "Hello, world" of game programming, which made sense to me, so I decided to give it a shot.

I've been able to code up a basic version in a few hours, which I'm quite happy with, but I had a few questions about 3D programming. Right now I'm using Direct3D to do display the blocks without any textures (just colored squares). I have a data structure (2d array of bytes, where each byte denotes the presence of a block and its color) which is the "game board," and on every render() call I create a new vertex buffer of the existing squares in the game board, and draw those primitives.

This feels very inefficient, and I wondering what would be the idiomatic way of doing this in a 3D world, with matrix/rotations/translation operations. I know 3D is overkill for such a project, but I want to learn any 3d concepts that I can while I'm doing it. I understand that what you'd usually want to do is keep the same vertices/vertex buffers but manipulate them with matrices to achieve rotations/translations, etc. To do so, I assume what would happen is I'd have one vertex buffer for the "active" piece, since that'll be constantly rotated and moved, and have one vertex buffer for the frozen pieces on the bottom of the board, which is pretty much stationary, but will need to be changed/recreated when the active piece becomes frozen.

Right now I'm just clearing and redrawing on every render call, which seems like the easiest way to do things, although I wonder if there's a more efficient way to deal with changes.

Obviously there are a lot of questions I'm asking here, but if you can even just point me a step or two ahead in terms of how I should be thinking, it'd be great. Thanks


texts: Hello everyone I learned how to emit from socket.io website guides but I was wondering how does the chat example receive its input? For example in my cocos2dx app how do I pass a text field over to the socket.io chat?


texts:
Alright, I think it's a simple question, but I got difficulties to find some answers around.

I already read that XNA wouldn't be in Visual Studio 2012.  I recently learned to use XNA, but since I would like to work on games, I'd like to know if there's a way to develop games using C# on Visual Studio 2012, or if I should learn everything again using C++ and Direct3D?

C# is a language I like a lot, so if there's no way to do it in C# but something quite easy to use Java for game development, I'd also be interested.

Thanks a lot!


texts: Quit the application when clicking cancel button of Alert View in C#

texts:
Can someone guide me as to how can I make an application quit when you press the cancel button of an Alert View in C# code?

Thanks

I forgot to add that I am trying to quit application on clicking ok button on alert view which I am developing on Unity platform.


texts: Estimate angle to launch missile, maths question

texts:
I've been working on this for an hour or two now and my maths really isn't my strong suit which is definitely not a good thing for a game programmer but that shouldn't stop me enjoying a hobby surely?

After a few failed attempts I was hoping someone else out there could help so here's the situation.

I'm trying to implement a bit of faked intelligence when the A.I fires it's missiles at a target in a 2D game world. By predicting the likely position the target will be in given it's current velocity and the time it will take the missile to reach it's target. I created an image to demonstrate my thinking: http://i.imgur.com/SFmU3.png which also contains the logic I use for accelerating the missile after launch.

The ship that fires the missile can fire within a total of 40 degree angle, 20 either side of itself, but this could likely become variable.

My current attempt was to break the space between the two lines into segments which match the targets width. Then calculate the time it would take the missile to get to that location using the formula. So for each iteration of this we total up the values and that tells us the distance travelled, ad it would then just need compared to distance to the segment.

startVelocity * ((startVelocity * acceleration)^(currentframe-1)

So for example. If we start at a velocity of 1f/frame with an acceleration of 0.1f the formula, at frame 4, would be

1 * (1.1^3) = 1.331

But I quickly realized I was getting lost when trying to put this into practice.

Does this seem like a correct starting point or am I going completely the wrong way about it?

Any pointers would help me greatly. Maths really isn't my strong suit so I get easily lost in these matters and don't even really know a good phrase to search for with this.

So I guess in summary my question is more about the correct way to approach this problem and any additional code samples on top of that would be great but I'm not averse to working out the complete code from helpful pointers.


texts: How can I make a two-eye-view effect using two cameras?

texts:
I have two cameras. The second was made by duplicating the first.
Then I changed both cameras' viewport rects:

First Camera X = 0 Y = 0.25 W = 0.5 H = 0.5
Second Camera X = 0.5 Y = 0.25 W = 0.5 H = 0.5

Then I created two Post Process profiles for each camera, CC and CC1 in the Inspector.

The result:

But it seems to me a bit odd. Since the view through both eyes looks the same.

Shouldn't the right eye be rotated or something, so it's completing the view from the right side? That is, I don't want both cameras (eyes) see the same (right-hand) view.


texts: Game Maker: Is there a faster way to check for collision than this?

texts:
There are many objects named obj_Cell and obj_Core in the room, each Core has a number (0 to 10) of Cells that belong to it. Each Cell record its corresponding Core with the variable ID_MyCore, which is the id of its Core.

Collisions/overlapping between Cells belonging to different Cores are to be detected. The purpose of this is to know which Cells are overlapping with a "foreign" Cell.

The following code is used, it is run in the step event of every Cell

with(obj_Cell)
{
    if place_meeting(x,y,other)=true
    {
        if other.ID_MyCore!=ID_MyCore
        {
            //do action
        }
    }
}

The annotated version of the above:

with(obj_Cell)  //get every cell in the room to do the following:
{
    if place_meeting(x,y,other)=true  //if you are touching the cell that is runing the script...
    {
        if other.ID_MyCore!=ID_MyCore  //...and your core is not the other cell's core
        {
            //do the thing that should be done when two foreign cells touch
        }
    }
}

My question is, is there a way of doing the same but faster? As it is, the number of times these scripts need to be run is the square value of total number of cells in the room, I intend to have hundreds of cells simultaneously.


texts: Mesh/Path reduction to simulate traveled path to target

texts:
I generate that kind of mesh during runtime to display the path to follow to a target (think at something like the path your GPS shows you when you are travelling):

I need to reduce the displayed path going from one end to the other to simulate the travel the player did. What can I do to achieve such effect?

I can think about vertex modifications at runtime directly from a Monobehaviour class, or a shader(?). Are there any other (smarter?) moves to do here? Is Vertex modification the wiser choice for that kind of case?

Thanks.


texts:
So I just learned the basics of Java and was ready to try to create a protoype game in the style of Civ. So a tile&turn based game.

I created an enum for the different tiles:

public enum TerrainTile{

 WATER(1), GRASSLAND(1), HILL(2), FORREST(2), BLANK(99);

private final int id;
private final int moveCost;
private boolean hidden = true;

private TerrainTile(int moveCost) {
    this.id = this.ordinal();
    this.moveCost = moveCost;
}

I made a JFrame:

public class MainFrame extends JFrame {

private MapPanel pnlMap;

public MainFrame(Terrain map) {

    setTitle("MyGame");
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    getContentPane().setPreferredSize(new Dimension(500, 500));

    pnlMap = new MapPanel(map);
    pnlMap.setPreferredSize(new Dimension(500, 500));
    add(pnlMap);

    pack();
    setLocationRelativeTo(null);

}

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {

            BufferedImage mapImg = null;
            try {
                mapImg = ImageIO.read(MainFrame.class.getClassLoader().getResourceAsStream("frames/resources/map2.png"));
            } catch (IOException e) {
                e.printStackTrace();
            }

            Terrain map = new Terrain(mapImg);
            System.out.println("Terrain created:");
            map.printTerrain();

            JFrame frame = new MainFrame(map);
            frame.setVisible(true);

        }

And a JPanel for the map:

public class MapPanel extends JPanel {

private final Terrain map;

public MapPanel(Terrain map) {
    this.map = map;
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

}

when I wasn't sure where to save the textures for the tiles.
Should I just read out the array of the map and do a switch statement to define inside the MapPanel class which texture to draw or should the textures better be implemented inside the enum?


texts: Unity prevent force apply on re-enable Physics2D.IgnoreCollision

texts:
I'm making 2d platformer game. My player and enemies  are rb with body type Dynamic. I choose dynamic for enemies because enemy need physics ( jumping, colliding with ground, etc)
I'm using  Physics2D.IgnoreCollision  for disabling and again enabling collision between Player and Enemies. When player lost life shield is applied on player.Here is code :
Disabling collision
private void OnCollisionEnter2D(Collision2D collision)
       {

    Player player = collision.gameObject.GetComponent<Player>();

    if (collision.gameObject.tag == "Player")
    {
        Physics2D.IgnoreCollision(collision.collider, gameObject.GetComponent<Collider2D>(), true);
        StartCoroutine(EnableCollision(player.timeShildActiveFixed, collision.collider, gameObject.GetComponent<Collider2D>()));

        if (player.playerState != Player.PlayerState.SHIELD)
        {
            playerLostLife();
            player.ActiveShield();
        }
    }

}

Enabling collision again:
    private IEnumerator EnableCollision(float delay, Collider2D collider1, Collider2D collider2)
{
    yield return new WaitForSeconds(delay);
    Physics2D.IgnoreCollision(collider1, collider2, false);
}

This work well but I my problem is that some force is applied on enemy before ignoring collision and enemy is changing its position ( on enemy because mass is set to 0.01 , but on Player mass is 1). This force is more visible when player not moving and shield is disabling and collison between player and enemy occur again and player get shiled again.
I can't work with different layer with disabled physics for Player and Enemy because I need collision between them.
Can someone help me with this? How can I fix this ?
Thanks


texts: Unity2D - How to destroy my Instantiate particle system

texts:
I'm having trouble trying to destroy my Instantiated particle system, I can only destroy my gameobject

using UnityEngine;
using System.Collections;

public class meteor_destruction : MonoBehaviour {

public GameObject meteor_d_effect;
public GameObject meteor_explo_effect;
public GameObject meteor_explo2_effect;

public int pointsIncrement = 1;

void OnCollisionEnter2D (Collision2D col)
{

    var effect_explo = Instantiate(meteor_explo_effect, col.gameObject.transform.position, col.transform.rotation);
    var effect_explo2 = Instantiate(meteor_explo2_effect, col.gameObject.transform.position, col.transform.rotation);
    var effect_d = Instantiate(meteor_d_effect, col.gameObject.transform.position, col.transform.rotation);
    Destroy (gameObject);
    Destroy (effect_explo,3);
    Destroy (effect_explo2,3);
    Destroy (effect_d,3);

}

It's generated after the meteor collide, but those 3 particle effects keeps adding inside my Hierarchy panel.