texts: How to make a single action run for two objects in GAME MAKER?

texts:
Think of a traffic light that only turns green or red.

If it is green, the next car passing through the detection point (pink square) will be directed to the green path and will cause the traffic light to turn red.

This way the next car that passes, will be directed to the red path, also making the green light, and so on.

Let's assume that two cars are in the same place and at the same speed and thus collide with the pink square at the same time. How can we make both directions to the same path be green or red and so that the light of the traffic light changes only once?

Considering "obj_BolaAzul" as "obj_blueCar", "obj_BolaRoxa" as "obj_purpleCar" and "obj_Cannon" as "obj_trafficLight".

The codes are basically:

obj_traficLight collision with obj_blueCar

if greenLight==true{
  obj_blueCar.move_towards_point(x+1,y,manSpeed); //go to right
  testGreen=true;
}

if redLight==true{
  obj_blueCar.move_towards_point(x-1,y,manSpeed); //go to left
  testRed=true;
}

if testGreen==true{
  greenLight=false;
  redLight=true
}

if testRed==false{
  redLight=false;
  greenLight=true
}

There are more things besides in code, but it has no relation to the problem.

I'm sorry again for the translation errors, I'm still not speaking English.


texts:
I have a WebGL deferred rendering pipeline, where I'm rendering shadow map with VSM technique. The goal is that the scene, or model, is hovering in space, and in addition to casting shadow on itself, it has to cast a shadow on invisible plane below it.

Now my current setup involves a finite plane geometry, but it's rather complicated.

I realized that since I only need the plane's depth, I could model the plane directly in the shadow map fragment shader with signed distance function. The idea seems to work, but I'm having trouble transforming the plane using my view & projection matrices (the renderer doesn't need any model matrix).

float sdPlane(vec3 p, vec4 n) {
    // n must be normalized
    return dot(p,n.xyz) + n.w;
}

void main(){
    vec2 uv = gl_FragCoord.xy/viewport;

    vec4 eye_data = vec4(
        texture2D(eye_normal, uv).rgb,
        unpack16f(texture2D(eye_depth, uv).rg));
    vec4 eye_data_floor = vec4(
        texture2D(eye_normal_floor, uv).rgb,
        unpack16f(texture2D(eye_depth_floor, uv).rg));

    if (eye_data.w == 0.0) {
      // some big enough constant because the depth clearing value can only
      // be in 0-1 range
      eye_data.w = 1000.0;
    }

    vec3 normal = eye_data.xyz;
    float depth = eye_data.w;

    // clipping planes scaling
    float cps = 1.0 / (far - near);

    float floor_depth = sdPlane(
        (inv_eye_proj * vec4(clip, cps, 1.0)).xyz,
        eye_view * vec4(0.0, 1.0, 0.0, 0.0)
    );
    floor_depth = floor_depth / cps;

    depth = min(depth, floor_depth);

    if (depth == floor_depth) {
        normal = vec3(0.0, 1.0, 0.0);
    }

    depth = near + (depth * (far - near));

    vec4 ro = inv_eye_proj * vec4(clip, 1.0, 1.0);
    vec3 rd = normalize(ro.xyz);
    vec3 eye_p = depth * rd;
    vec3 p = (inv_eye_view * vec4(eye_p, 1.0)).xyz;

    float occlusion = OcclusionVSM(p, normal);
    float lambert = clamp((light_rot * normal).z, 0.0, 1.0);
    float intensity = (occlusion*0.8+0.2) * lambert;

    gl_FragColor = vec4(vec3(intensity), occlusion);
}


texts: How to use GetViewProjMatrix().TransformVector(LineDirection) in UE4?

texts:
I try to project a 3D vector (a direction, not a position) in screen space, but it does not return satisfying results:

 FVector LineDirectionOnScreen =
   EdMode->ViewMatrices.GetViewProjMatrix().TransformVector(LineDirection);
 FVector2D LineDirectionOnScreen2D(
   LineDirectionOnScreen.X * 0.5f * (float)EdMode->ViewRect.Width(),
   LineDirectionOnScreen.Y * 0.5f * (float)EdMode->ViewRect.Height());

When LineDirection is (0,0,1) it always returns a something like (0,Y) (Y can be anything), no matter how the camera is rotated.

What is wrong with my code?


texts:
I'm using thinking of using an entity system in my game. So far I've been using Artemis with success. However, I have a question about texture switching.  I read that switching textures too often is bad. So I load all the textures when the game loads like so:

import org.newdawn.slick.opengl.TextureLoader;
...
public HashMap<String, Texture> Textures;
...

Then for each texture I do this:

Texture tex = TextureLoader.getTexture("PNG", this.getClass().getResourceAsStream(texturePath));
Textures.put(textureName, tex);

Then when drawing entities I do this:

drawEntity() {
    glBindTexture(GL_TEXTURE_2D, Textures.get(entityTexture).getTextureID());
    ...
}

Say I have 50 entities, using 10 different 3D models, each with their own texture. When the drawEntity system runs, it doesn't group by which entities use which texture. So I could be switching textures before drawing each entity! Is there a more efficient way to switch textures between entities? Or is glBindTexture() a good option?


texts: Why does my FPS drop gradually over time?

texts:
I'm working on this game: yt alpha preview

I came into a huge game-breaking problem - after 10-15 min of gameplay the FPS drops from 60 to 30 and is very unstable. I'm using tons of physics and particles, I'm deleting and nulling everything I can after it's supposed to be removed, I remove objects from vectors etc. The memory usage is stable at around 150mb so a leak is unlikely (or invisible?)- after a round ends and I delete everything, play a new round and performance is still terrible. I spent two days trying to figure this out and I just can't fix it. Maybe I'm missing something? I know it's hard to help with no code but I would just have to post my whole source.


texts: Creating a good looking interface for a Java CCG?

texts: I would like to create a Java collectible card game. I have the logic down pat, but I am having some trouble with the interface. I would like to make it look nice. Rather than using the standard java SWING components, I would like to create something like this. What is necessary to create something like that?


texts: How can I change object material color using time and lerp?

texts:
I'm using the following code to change the color over time.

The coloring part is working but it's changing the color too fast. Even if I change the duration value to 5 or 10 it's changing the colors less then a second and it should be 5 seconds. I tried in the Inspector to change the duration to 10 but it didn't effect, still too fast.

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

public class ChangeScale : MonoBehaviour
{
    public GameObject objectToScale;
    public float duration = 1f;
    public Vector3 minSize;
    public Vector3 maxSize;

    private bool scaleUp = false;
    private Coroutine scaleCoroutine;

    public Color startColor;
    public Color endColor;
    public float colorDuration = 5; // duration in seconds

    private float t = 0; // lerp control variable

    private void Start()
    {
        startColor = GetComponent<Renderer>().material.color;
        endColor = Color.green;
        objectToScale.transform.localScale = minSize;
    }

    // Use this for initialization
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
            //Flip the scale direction when F key is pressed
            scaleUp = !scaleUp;

            //Stop old coroutine
            if (scaleCoroutine != null)
                StopCoroutine(scaleCoroutine);

            //Scale  up
            if (scaleUp)
            {
                //Start new coroutine and scale up within 5 seconds and return the coroutine reference
                scaleCoroutine = StartCoroutine(scaleOverTime(objectToScale, maxSize, duration));
            }

            //Scale Down
            else
            {
                //Start new coroutine and scale up within 5 seconds and return the coroutine reference
                scaleCoroutine = StartCoroutine(scaleOverTime(objectToScale, minSize, duration));
            }
        }

        if (Input.GetKeyDown(KeyCode.C))
        {
            t = 0;
        }
        GetComponent<Renderer>().material.color = Color.Lerp(startColor, endColor, t);
        if (t < 1)
        { // while t below the end limit...
          // increment it at the desired rate every update:
            t += Time.deltaTime / duration;
        }
    }

    IEnumerator scaleOverTime(GameObject targetObj, Vector3 toScale, float duration)
    {
        float counter = 0;

        //Get the current scale of the object to be scaled
        Vector3 startScaleSize = targetObj.transform.localScale;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            targetObj.transform.localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration);
            yield return null;
        }
    }
}

When I press on C it's changing the colors but too fast.

What I want to do is when i press on C to change slowly and smooth the color of the object.


texts: Efficient way to implement a lot of singletons

texts:
I just came upon programming patterns and learned about singleton. I'm in the process of creating my first game and it contains several managers:

I wanted to implement singleton on each of the managers,but the only way I can think is copy pasting the singleton pattern on each awake method script attached to each manager.
Is there a more efficient way to do it rather than pasting the pattern on each awake method?


texts: Mouse Input Unexplained Behavior Unity3D

texts: Input.GetMouseButtonDown(0.....6); - in documentation it says that you can pass, 0, 1, 2 as parameter. Input.GetMouseButtonDown. It doesn't accept negative numbers like -1 or numbers 7+. What does 3 4 5 6 do? What input are they calculating? Or can I use these numbers as default for None state? I couldn't find any information about this.


texts: How to achieve dotted trail behind moving object with use of Trail Renderer?

texts:
How can I achieve effect shown on picture below with use of Trail Renderer in 2D game? Is it even possible? I need dotted (dashed) trail behind my object and i can't figure it out.

don't know why stack can't load my images LINK HERE

Why trail renderer? Because I feel this is the right way to do this. Earlier, (Unity ver 5.3) I achieved this using: Mesh Particle Emitter + Particle Animator (Fade) + Particle Renderer, but sometimes it behaves strangely in multiplayer. Particles not always came out from object, sometimes they were offset. Anyway, Unity in ver. 5.5 released new component (TrailRenderer), which I would like to use (if it is possible to accomplish effect I need).

I am looking for efficient ways, so answers like "you can instantiate"dot" every X sec. at position of your moving object" ... Please no.

What I have tried.

I added to my gameobject a child (gameobject) with Trail Renderer. Then I put material into Materials array field.

Material shader currently is set to Mobile/Particles/Additive (I am targeting Mobile devices). Material Texture is:

don't know why stack can't load my images LINK HERE

I've tried different settings to accomplish my needs but with no success.

Trail Renderer -> Texture Mode -> Tile (my gameobject is followed by one dot and line)

Texture Import- > Wrap mode -> Repeat (my gameobject pulls dots without gaps behind instead leaving dots in place it was)

Also i tried different shaders, different Trail Renderer parameters with no success. Most of time, my gameobject is followed by stretched dot, line or dots without gaps which are pulled instead of left in place where object was.


texts: Box2D OpenGL debug renderer convert box2d coordinates to world space

texts:
I made an OpenGL 3.x renderer for Box2D's debug draw (b2Draw base class). Unfortunately I've tried for a while now to convert the box2D units, which are meters to my internal units which are pixels. I make 1 meter == 50 px, I set the sizes and positions just fine. It's only the debug renderer that is giving me trouble, because I don't know how to set the ortho and view matrix properly.

Basically I've got a camera which I center on the player's position each tick, the player's position being in pixels..so it could be say 2500x, 3200y. So the camera's view mat4 would be centered on that and the ortho is just set to the size of the screen.

So somehow I need to be able to turn this so that the position and the sizes are properly set. I'm using GLM for my matrix handling.

For example, I will see the physics debug data on screen if i set the ortho to be PIXELS_PER_METER (which is 50) for both x and y. But obviously this wouldn't map to worldspace, so my actual sprites won't have the physics bodies rendered where they are.

I've tried several things, including glm::scale, glm::translate with all kinds of different values and now I'm just out of ideas. Anything else I try results in no physics data to be drawn..


texts: Normal doesn't appeared on shadow/dark area in Mobile Shader

texts:
Let's look at this picture:

You can see the red rectangles, those are shaded by normalmap.

Here, is the same model with different light angle, there's no normal shading in dark area.

It only happens in Mobile Shader(simplified blinnphong actually). I'm targeting on Android devices, and using Mobile Shader with Normalmap. How do I fix this?


texts:
For my RTS game's ability system, I need an efficient ability system where each ability is its own class that implements certain functions from an inherited abstract base class, Ability. Every ability is identified by a byte ID (which gets sent over the network and interpreted by other players). I want to be able to call an ability's overrided Execute() Method with its ID. Currently, I've been thinking of storing all the abilities in dictionaries with their IDs as their keys but I'm having trouble storing these derived classes, abilities, in the dictionary.

I've also heard of reflection but I'm a bit hesitant because I've heard it's a quite expensive operation. Would it be recommended to use up to 60 reflection processes in one frame or will this cause performance issues?

Note: I'm using C# and Unity3D.


texts: Trigger an event only if two colliders fully cover each other

texts: Let's say I have two different objects that can go through each other. Both have a circle collider (2d) that has the exact same size and there is a good chance that the two colliders will completely overlap each other. How can I trigger an event when that happens?


texts:
I am working though the Space Shoot tutorial and I have just applied tilt to the player object. One of the things that I have noticed is that the tilt is not applied instantly but instead the player object can be seen to rotate to the new rotation position. Why does the rotation appear to applied over time (1/2 second maybe) instead of instantly?

My expectation would be that when I set an attribute the value is changed instantly, not over time. I understand that instantly snapping to a position might not be very desirable, but I can't find anything in the unity documentation that explains the behavior I am observing. My desire is to understand this behavior so that I can account for it and take advantage of it, so please provide a link to any supporting documentaion.

Sample code that exhibits this behavior.

using UnityEngine;
using System.Collections;

public class PlayerControler : MonoBehaviour {
    void FixedUpdate(){
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        rigidbody.velocity = new Vector3 (moveHorizontal, 0.0f, moveVertical);

        rigidbody.rotation = Quaternion.Euler (0, 0, rigidbody.velocity.x);
    }
}


texts: Is there a collection of images (GUI - interface) program or web page available for programmers / developers games?

texts:
I would like to add a GUI in my basic XNA games.
Before starting work on "Photoshop" or "Illustrator". I wanted to ask you the following question:
Do you know of a website or other resource program offering a graphics collection ? Oriented (GUI - interface) free preference available to developers ?


texts: Implementing time step in main game loop

texts:
So ive read both http://gameprogrammingpatterns.com/game-loop.html and http://gafferongames.com/game-physics/fix-your-timestep/ and I kind of understand how I'm supposed to do it, but some parts are still blurry and I would like some guidance.

By the way, I have programmed my game from scratch and i do not want to change to some framework or anything that has an built in main loop, i want to do this by myself.

Anyway, this is what I have accomplished code-wise, I will re-produce my solution it in psudocode below.

func createPlayer()
{
oData = Empty Object()
oData.id
oData.name
oData.etc.....
Player = LoadSprite("filename", oData)
// Properties
Player.oSprite.x
Player.oSprite.y

Player.oSprite.scale
Player.oSprite.width
Player.oSprite.height
//Methods (Self-explanatory)
Player.oSprite.width()
Player.oSprite.height()
Player.oSprite.centerX()
Player.oSprite.centerY()

return Player
}

// Startup
oPlayer = createPlayer()
oWorld = 1D array of objects which has identical properties and methods from createPlayer()

// Main game loop
while(game){

 //User inputs
 _game_userInputs(byref oPlayer)

 // "Physics" jumps and world collission is done here.
 _game_Physics(byref oWorld, byref oPlayer)

 // rendering, draws the world frame with all inputs and physics done beforehand
 _game_render(byref boWorld,byref oPlayer)

}

This is how I "understand" what flow the loop should have

t = 0.0
dt = 0.0
currentTime = 0.0
accumulator = 0.0

while(game)
{

  newTime = _Timer_QueryPerformanceCounter() // Im feeling like this need something more than just the QueryPeformenceCounter?
  frameTime = newTime - currentTime

  if (frameTime > 0.25) {
        frameTime = 0.25
  }
  currentTime = newTime

game_input()

//This is causing my game to get stuck here, i belive it has something to do with my type of timer
 while accumulator > dt
 {
  game_physics(t, dt) //how is the deltatime helping me in my physics?
  t += dt
  accumulator -= dt
 }

 alpha = accumulator / dt
  game_render(alpha) // I dont know what im supopsed to do with this.
}

TLDR, what do i do with the t, dt in my physics? before i render?


texts:
I need some help with math in a 2d environment. I have a joystick that controls the acceleration vetor for the player figure.

Its suppose to look like the ground is slippery which makes the figure turn slowly and accelerate and decelerate slowly.

Now, I can do this without any problem if I remove the maximum speed, but Im having problem when using a speed cap.

This is my calculation:

func move() {
    if acceleration == CGPointZero && currentSpeed != 0 {
        direction *= 0.95
    }
    else {
        if self.currentSpeed > maxSpeed {
            // This is almost working, just a little buggy, please help here with quality mathamatics :)

            let angle = CGPointZero.angleToPoint(direction) // In Radians
            direction = CGPoint(cos(angle), sin(angle)) * maxSpeed
        }
        else {
            direction += acceleration
        }
    }

    self.center += direction
}

move() is getting called by a timer running at 32 fps. acceleration is a Vector pointing to the direction the user wants his figure to go. currentSpeed is calculated using Pythagorean theorem. direction is acceleration * speed. maxSpeed is a number. self.center is the centerpoint of the figure.


texts:
The title is fairly self-explanatory. I have a 2D racing game that utilizes per-pixel collision detection (the track is essentially two bitmaps, one for the graphics, one for collision data). The problem I'm running into is that I can't figure out how to implement the collision response. I can figure this out for situations where I have a box colliding with another box, but the fact that my objects can essentially be any shape has me stumped.

The one approach that I've had some success with is to just sample a couple of pixels near the pixels that collide, build vectors out of those and then take the cross product of that, but it fails in many scenarios. Plus, it just seems like overengineering. In fact, I'm about 103% sure that I'm just overthinking the whole problem.

Has anyone tackled this problem?


texts: Is Mogre (essentially Ogre, but C#) dead? If so what would be a viable alternative to it?

texts:
I've been looking around for a 3D engine where I can use C# to replace Unity lately, but haven't really come up with much. Ogre looked promising, but it wasn't C# however Mogre is. Sadly looks like it hasn't been updated since Feb. 2014.

With the said are there any viable alternatives to it, or Unity? Or better yet is there a nightly I missed somewhere for Mogre?


texts: How can I implement a side scrolling seamless fog shader?

texts:
I've run into a problem trying to code a 2d game. The way I've set up the game is that you run through underground dungeons and fight enemies, for ambiance I've added a smoke/fog shader to superimpose over the dungeon backdrop. However, the noise/fog isn't seamless. As in, the fog is always the same even when moving through the map, it doesn't move with the player/camera.

How do I make it so the fog is generated whenever the camera moves sideways/upwards while still being seamless, as in fitting in with the fog from before moving the camera?

For example, when I move right, the fog background should move left, instead of being the same backdrop anywhere I am on the map.

The shader I've set up is based on this one from Morgan McGuire/patriciogv:

// Author @patriciogv - 2015
// http://patriciogonzalezvivo.com

#ifdef GL_ES
precision mediump float;
#endif

uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_time;

float random (in vec2 _st) {
    return fract(sin(dot(_st.xy,
                         vec2(12.9898,78.233)))*
        43758.5453123);
}

// Based on Morgan McGuire @morgan3d
// https://www.shadertoy.com/view/4dS3Wd
float noise (in vec2 _st) {
    vec2 i = floor(_st);
    vec2 f = fract(_st);

    // Four corners in 2D of a tile
    float a = random(i);
    float b = random(i + vec2(1.0, 0.0));
    float c = random(i + vec2(0.0, 1.0));
    float d = random(i + vec2(1.0, 1.0));

    vec2 u = f * f * (3.0 - 2.0 * f);

    return mix(a, b, u.x) +
            (c - a)* u.y * (1.0 - u.x) +
            (d - b) * u.x * u.y;
}

#define NUM_OCTAVES 5

float fbm ( in vec2 _st) {
    float v = 0.0;
    float a = 0.5;
    vec2 shift = vec2(100.0);
    // Rotate to reduce axial bias
    mat2 rot = mat2(cos(0.5), sin(0.5),
                    -sin(0.5), cos(0.50));
    for (int i = 0; i < NUM_OCTAVES; ++i) {
        v += a * noise(_st);
        _st = rot * _st * 2.0 + shift;
        a *= 0.5;
    }
    return v;
}

void main() {
    vec2 st = gl_FragCoord.xy/u_resolution.xy*3.;
    // st += st * abs(sin(u_time*0.1)*3.0);
    vec3 color = vec3(0.0);

    vec2 q = vec2(0.);
    q.x = fbm( st + 0.00*u_time);
    q.y = fbm( st + vec2(1.0));

    vec2 r = vec2(0.);
    r.x = fbm( st + 1.0*q + vec2(1.7,9.2)+ 0.15*u_time );
    r.y = fbm( st + 1.0*q + vec2(8.3,2.8)+ 0.126*u_time);

    float f = fbm(st+r);

    color = mix(vec3(0.101961,0.619608,0.666667),
                vec3(0.666667,0.666667,0.498039),
                clamp((f*f)*4.0,0.0,1.0));

    color = mix(color,
                vec3(0,0,0.164706),
                clamp(length(q),0.0,1.0));

    color = mix(color,
                vec3(0.666667,1,1),
                clamp(length(r.x),0.0,1.0));

    gl_FragColor = vec4((f*f*f+.6*f*f+.5*f)*color,1.);
}


texts: what's wrong with this Lua code (creating text inside listener in Corona)

texts:
If you double/triple click on the myObject here the text does NOT disappear.  Why is this not working when there are multiple events being fired?

That is, are there actually multiple "text" objects, with some existing but no longer having a reference to them held by the local "myText" variable?  Do I have to manually removeSelf() on the local "myText" field before assigning it another "display.newText(...)"?

display.setStatusBar( display.HiddenStatusBar )

local myText

local function hideMyText(event)
    print ("hideMyText")
    myText.isVisible = false
end

local function showTextListener(event)
    if event.phase == "began" then
        print("showTextListener")
        myText = display.newText("Hello World!", 0, 0, native.systemFont, 30)
        timer.performWithDelay(1000, hideMyText, 1 )
    end
end

-- Display object to press to show text
local myObject = display.newImage( "inventory_button.png", display.contentWidth/2, display.contentHeight/2)
myObject:addEventListener("touch", showTextListener)

Question 2 - Also why is it the case that if I add a line BEFORE "myText = ..." of:
a) "if myText then myText:removeSelf() end" => THIS FIXES THINGS, whereas
b) "if myText then myText=nil end" => DOES NOT FIX THINGS

Interested in hearing how Lua works here re the answer...


texts: Saving and loading a GameObject's full state easily in Unity3D?

texts:
I'm working on placing predesigned tilemap rooms in my procedural dungeons, and I would like to design the items' and monsters' placement in these special rooms as well.

Currently I "compile" my predesigned room scene into a scriptable object, and the map generator loads that tilemap into "gameplay" tilemap.

I already parse the special game objects in the scene (like items and monsters), and store their transforms and prefab paths in the scriptable object.

But this has 2 problems:

Having every item and monster in the resources folder would make my executable huge.

But this could be solved by making a "MonsterPrefabDictionary" on a manager like gameobject, and drop every prefab into this list in the editor. The map generator would simply use this dictionary to find the object's prefab.

The biggest problem is that every variation of monster would need another prefab (or prefab variation). And by variation I mean the little changes as well.

Want a mob to have only 50% health in the room at start? Make a prefab for this?
Want a monster to start with a specific buff in this room? Make a prefab for this?
Want a monster to start in a different stance than usual in this room? Make a prefab for this?
So as you can see, this scales pretty badly.
But this could be solved by storing the MonsterScript's every data in the scriptable object.
But this would scale badly as well, because every new information about a monster would have to be added to this serialization process as well.

Is there a built-in, automatic, easy way to just save a GameObject's full state and just load everything with one line later on?


texts:
I'm working on a strategy game. It's turn-based and card-based (think Dominion-style), done in a client, with eventual AI in the works. I've already implemented almost all of the game logic (methods for calculations and suchlike) and I'm starting to work on the actual game loop.

What is the "best" way to implement a game loop in such a game? Should I use a simple "while gameActive" loop that keeps running until gameActive is False, with sections that wait for player input? Or should it be managed through the UI with player actions determining what happens and when?

Any help is appreciated. I'm doing it in Python (for now at least) to get my Python skills up a bit, although the language shouldn't matter for this question.


texts:
From what I understand, the main difference between software rendering and hardware rendering is that in software rendering you use the CPU to determine what to color each pixel, and in hardware rendering you let the GPU take care of calculations and determine how to draw each pixel.

However, in the end, isn't an API such as OpenGL still required to do the actual drawing no matter which method you pick? I saw a basic software rendering engine that someone built, and the person said he still used OpenGL to do the actual drawing after using the CPU to do the rendering. So is an API like OpenGL or DirectX still required in the end? And if so, is it true that a computer must at least have an integrated GPU or dedicated GPU to display anything at all?


texts: XNA 4.0 How to change GraphicsDevice Default DepthStencilState Value

texts:
I want to change one of the deafult values of my GraphicsDevice to that:

GraphicsDevice.DepthStencilState.DepthBufferEnable = true;

But I know only to change it on runtime in the Draw method by putting this code (which means it's changing the value everytime that the compiler is running the draw method!):

DepthStencilState state = new DepthStencilState();
state.DepthBufferEnable = true;
GraphicsDevice.DepthStencilState = state;

Does someone know how to change it once in an officient way?


texts: How to stop sinking bodies in physics engine C++

texts:
I'm writing a rigid body simulation in C++, and have come across a problem when an object should come to rest on the ground.

Because gravity is being applied to it's velocity, the object starts sinking through the ground, or whatever else it's resting on.

To combat this, I am adjusting the position of the object, by moving it along the collision normal by the penetration depth. This has the drawback of making the object look like its vibrating, so it never comes to rest.

I read somewhere ages ago, that there is a way to counter this, by generating a force along the normal which will cancel out the force which is causing it to sink. A google search did not return any useful answers however. I suspect this is because I'm not asking the right question, but I don't know a more concise way to word it, so I'd appreciate if someone here has solved this, and could steer me in the right direction.


texts:
I got a model, and a camera pointing at this model, I think my camera position is the problem.
Its showing the front of the model, but I want it to show its back like in third person.
My camera code is:

Vector3 thirdPersonReference = new Vector3(0, 100, -100);
public Camera(Vector3 landscapePosition, Player _player)
    {
        this.player = _player;
        rotationMatrix = Matrix.CreateRotationY(this.player.Rotation);
        Vector3 transformedReference = Vector3.Transform(thirdPersonReference, rotationMatrix);
        this.position = transformedReference + this.player.Position;
        viewMatrix = Matrix.CreateLookAt(this.position, this.player.Position, new Vector3(0.0f, 1.0f, 0.0f));
        projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, this.player.AspectRatio,
            1.0f, 1000.0f);
        terrainMatrix = Matrix.CreateTranslation(landscapePosition);
    }

What is that Im doing wrong???


texts:
I want to implement a dev console similar to what is in DOOM.
Is there a standard implementation for dev consoles or would I have to build everything from scratch?


texts:
I'm using a graphics format reading library which has an enum called "MaterialLuminanceMode". There are three luminance modes for materials available:

Self-illumination, which I interpret to mean "glow", as in a glowing light bulb,
Color emission, which I interpret to be using the diffuse color mask for the lumination,
Luminance, which I interpret to be the exact same as self-illumination.

Does anybody know what the difference between the first and third enum value is?

The best resource I could find seems to suggest that self-illumination is a superset of luminance, but I'm still not certain what exactly separates the two! Note this is from 3ds, which i also an Autodesk product - although not the exact format I'm reading (which is DWG)


texts: Using CNN's in Unity via Tensorflow and TensorFlowSharp

texts:
I have a project that tracks hands made in python, shown here: https://github.com/timctho/convolutional-pose-machines-tensorflow

I want to effectively import this into Unity. I have generates the .bytes file from the model, but have no idea how to do anything further than this. If anyone has worked with ML-Agents or TensorflowSharp in Unity and/or would be willing to have a look, this would be great. The image-processing stuff would be done probably in a C# file beforehand, I just want to know how to run the network.

Thanks.


texts: Unity - Scaling down a GameObject containing a child Final IK (VRIK) rig

texts:
I'm currently building a VR / AR hybrid in Unity, where I'm controlling an IK rig using VR, then sending the VR controllers positions to an iOS device using network transforms to mirror the IK rig's movement in ARKit. I'm having trouble implementing pinch to scale the scene locally on the iOS device.

I'm attempting to uniformly scale down a parent GameObject containing the IK rig which has its Head target connected to SteamVR Vive headset and its Hand targets set hand controllers positions. The vectors that describe the positions of the controllers are being sent over the network, so I'm applying the same scale factor to those, so that the targets match up to the scaled down character. However, the IK rig appears to break when scaling the character down, and in particular the legs appear to be too far apart, and the hand movements no longer look correct

Could the problem be to do with the internal relative transforms within the IK rig needing to be modified? And is there a better approach?


texts:
I've followed the instructions on installing SFML on the website to the letter. But, I get this when I try to build the sample program on the same page using Code::Blocks.

C:\Users\nic\Desktop\sfmltest.o:sfmltest.cxx|| undefined reference to `_imp___ZN2sf6StringC1EPKcRKSt6locale'|

...

||=== Build failed: 20 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

I get 20 error messages, which are all similar to the one given above. SFML worked like a charm on my ubuntu 14.04 amd64 install, but it simply does not work on Windows. I am using SFML 2.1 (the GCC 4.7 TDM (SJLJ) - 64 bits package as the other ones did not work) on a Windows 7 x64 installation with MinGW (gcc 4.8.1). How can I make SFML work on Windows?

edit: I'm not sure if I have to copy-paste all the SFML dlls to the working directory. Should I do this?

edit2: c/ping the dlls does not help.


texts: What is the recommended way to store game entity data?

texts:
The following is specific to my problem, but I believe the principles can be applied to any game.

I am currently working on a 3D game which will have many different types of spaceships.
The physics and behavior of the spaceships are controlled by a base 'Ship' class. This base class in turn derives from a 'Drawable Object' class which handles the transformations and drawing of the ship.

I want the spaceships to have a set of stats such as

Max speed
Cargo capacity
Weapon power
etc

that can be passed into the physics and behavior functions.

However, during gameplay new spaceships will be able to be bought/upgraded, but i want to be able to pre-define a (possibly large) list of setups that will be available to the player.

What is the best way to store the available stat setups?

Should I be using a large JSON/XML file or similar to store the stats which is loaded at runtime?
Or might I just as well hard-code the stats into the constructors of a set of derived classes?

The actual physics attributes (location, velocity etc) and its stats of a particular spaceship are being saved to file when the game is actually played.

I have researched about entity-component-system architecture, but I haven't found much about how to define these entity stats.

Any advice on improving my entity architecture would be much appreciated - this is one of my first attempts at hobby game development.


texts: Using Unity and MonoBehavior for UI only?

texts:
I've made a turn-based game (think xcom) in Unity, and because I don't need real-time, asynchronous elements, or physics calculations I decided to make a pure c# Model (in the sense of Model, View, Controller) which everything is based on. I use Unity and a MonoBehavior based game loop to handle rendering, camera, UI and input, but stuff like a character attacking another and then calculating a counterattack, or player equipment and spells, are all pure c#.

Am I missing some capabilities of Unity that I should be looking at or is this a basically reasonable approach?


texts: Entity Component Systems with Model View Controller

texts: Can the Model View Controller design pattern be used with non-OOP coding style, specifically with Entity Component System?


texts:
This question is specific to unity:

I want to spawn multiple blocks, each representing a letter. There will be more than one copy of an alphabet.

I have a big texture which contains all the letters in it. I use a prefab to Instance all the Blocks(quads) during Awake(). At runtime, I'd like to assign a texture to these quads (identifying the letter). My code looks like this:

    void Update () {
            // if there is no active block, spawn it
            if (activeBlock == null) {
                this.getNextBlock (ref this.activeBlock);
    }
    protected Block getNextBlock(ref Block block){
            block = this.deQueueBlock ();
            char letter = LetterMgr.Instance.getNextLetter();
            // based on the letter, index into texture
            // and assign the texture + indices to this block ?
    }

How can I reuse this one big texture and index into each letter amidst all these blocks (quads) ? I will be rendering this on a mobile, so will need to squeeze all the performance I can.
Details:

256 x 256 per letter
8 columns x 4 rows
Total Texture Size: 2048 x 2048
Total number of blocks: ~100

PS: Each of the letters will be moving and will eventually come to rest. So I will have some (around 6-7) actively moving blocks and others will be stationary.


texts: I need help with my pathfinding algorithm

texts:
I am a student that is learning how to program and I started to develop my first platform game using C. However, I’m struggling with the pathfinding algorithm for the enemies.

My levels are basically a 30x45 array with numbers that have a 1 where there is a block, 2 ladders and 0 an empty space. I don’t know which path finding algorithm to use, mainly, because I have no idea how to create the graph.

Being a grid-based level, using an adjacency list or matrix, I guess that it would be quite complex if I had every walkable cell as a node.
I was thinking of using BFS or Dijkstra’s, but I don’t even know where to start.
I already know how the algorithms work, but I can’t figure out how to implement any of those.

I would appreciate if anyone could help me.


texts: How would I combine FABRIK inverse kinematic results with a skeletal animation?

texts:
So, I've been working on a skeletal animation system in OpenGL/C++, and it's actually not coming along too badly. I can play animations, which I do by sending bone transform matrices to my animation shader, as per this tutorial.

Now I want to combine these animations with inverse kinematics. Seems doable!  The FABRIK algorithm seems simple and computationally efficient. However, I noticed that it puts out a list of positions, not a list of local quaternions. How would I go about using this algorithm in a way that is compatible with a skeletal animation system, i.e. how do I get the calculated IK world positions to combine nicely with the 4x4 transformation matrices of my skeletal animation system's joints?

I was thinking of just combining the IK positions with each vertex position in my vertex shader, but then I don't get the blended bone positions on the CPU side. Is there a way to do this that is elegant and not a performance nightmare?


texts: Unity5 mixing animations with different properties

texts:
Maybe there are tons of questions about this but i dont know what to look for. I have 2 animations, one is aiming a weapon and the other one is shooting.

When i aim the weapon i animate only its position upward and a little bit to the left so its in front of the camera.

When i shoot, i just rotate it a bit on the x-axis.

My problem is, when i shoot while the weapon is aimed (animated upwards and left) the whole Weaponholder get back to its initial (not aimed) position.

I thought when i just animate the position in one clip and only rotation in another i can mix them together. Am i on the wrong way or just did something wrong?

Thank you


texts: Implementing Scrolling Background in LibGDX game

texts:
I am making a game in LibGDX. After working for whole a day..I could not come out with a solution on  Scrolling background.

My Screen width n height is 960 x 540. I have a png image of 1024 x 540. I want to scroll the background in such a way that it contuosly goes back with camera

x-- as per camera

I tried many alternatives... drawing the image twice ..did a lot of calculations and many others....
but finally end up with this dirty code

if(bg_x2 >= - Assets.bg.getRegionWidth())   {
//calculated it to position bg .. camera was initially at 15
                bg_x2 = (16 -4*camera.position.x);
                bg_x1=bg_x2+Assets.bg.getRegionWidth();
            }
            else{
                bg_x1 = (16 -4*camera.position.x)%224;  // this 16 is not proper
//I think there can be other ways
                bg_x2=bg_x1+Assets.bg.getRegionWidth();
            }

//drawing twice
       batch.draw(Assets.bg, bg_x2, bg_y);
        batch.draw(Assets.bg, bg_x1, bg_y);

The Simple idea is SCROLLING BACKGROUND WITH SIZE SOMEWHAT MORE THAN SCREEN SIZE SO THAT IT LOOK SMOOTH. Even after a lot of search, i didn't find an online solution. Please help.


texts: Unity: Controlling animation by switching between a GameObjects children

texts:
I bought an asset the other day containing an Atlas of character parts (head, hairs, clothes, body-parts). It's great and allows me to tint each piece any color I want. However, The artist decided to devide up the character like this:

Each child is a fully setup character, facing a certain direction, with an Animator attached to it, inside each Animator Controller you find this:

Some sample animations, pretty self-explanatory.
However, I have never worked with sprites like this where its several parts, the entire character is maybe 30-40 parts (allowing for some fun animations).
I'm used to making Blend Trees (on a single GameObject) and have one animation for each direction.
The best solution for controlling these animations I could think of was something like this:

private void AnimControl() //call in update
    {
        if(direction != directionLastFrame) //do not run method if we are moving same direction
        {
            //standing still
            if (direction.x == 0 && direction.y == 0)
            {
                directionLastFrame = direction;
            }
            ////left
            else if (direction.x < 0.5f && direction.y == 0)
            {
                currentCharacterDirection.SetActive(false); //set current gameObject (which is a character facing a certain direction) inactive
                currentCharacterDirection = character.leftDirection; //change to correct direction
                currentCharacterDirection.SetActive(true); //set gameobject active again
                anim = currentCharacterDirection.GetComponent<Animator>(); //set the animation controller to the new gameObject
                directionLastFrame = direction; //set the new direction to check for
            }
            ////right
            else if (direction.x >= 0.5f && direction.y == 0)
            {
                currentCharacterDirection.SetActive(false);
                currentCharacterDirection = character.rightDirection;
                currentCharacterDirection.SetActive(true);
                anim = currentCharacterDirection.GetComponent<Animator>();
                directionLastFrame = direction;
            }
            ////down
            else if (direction.y < 0.5f && direction.x == 0)
            {
                currentCharacterDirection.SetActive(false);
                currentCharacterDirection = character.downDirection;
                currentCharacterDirection.SetActive(true);
                anim = currentCharacterDirection.GetComponent<Animator>();
                directionLastFrame = direction;
            }
            ////up
            else if (direction.y >= 0.5f && direction.x == 0)
            {
                currentCharacterDirection.SetActive(false);
                currentCharacterDirection = character.upDirection;
                currentCharacterDirection.SetActive(true);
                anim = currentCharacterDirection.GetComponent<Animator>();
                directionLastFrame = direction;
            }
        }

        anim.SetBool("Moving", playerMoving);
    }

I mean it works, but feels wrong? Anyone that can think of a better Idea here, worried this might be too slow. setting an object to active/inactive too often.


texts: Restarting a game be resetting an object

texts:
In a game I made, I want to restart the game when the players presses a button.

I have an instance of a Game class, which is where most of the game happens.

I though that I could simply initialize it again, and it will be reset.

Game game = new Game(); - When the program launches.
game = new Game(); - When restarting the game.

But the game uses a lot of additional classes, such as Tank and Missile. Do I have to initialize all of them too, or is initializing the Game class, which will create new Tank objects and Missile objects (with the same reference names as the previous Game instance), enough?

In general, what would be the best way to reset a game or a level in a game?

Thanks


texts:
I am learning to create a snake game (from this tutorial) .

The problem is arising when the object(Snake) collides with the borders,nothing happens and it moves out of the box (white square on the left).

I have added BoxCollider2D components on the bounds.

For the player (Snake), I've added BoxCollider2D component and Rigidbody2D.

Here's the script attached to the snake

using UnityEngine;
using System.Collections;

public class Snake : MonoBehaviour {

    Vector2 dir=Vector2.left;

    // Use this for initialization
    void Start () {
        InvokeRepeating ("Move", 0.3f, 0.3f);

    }

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

    }

    void Move(){
        transform.Translate (dir);
    }
}


texts: How to handle multiple story threads in a RPG game?

texts:
I designed an RPG game that has multiple story threads, meaning that, depending on the user's choice some things may or may not happen, you can achieve the same thing in several ways, the ending can be different and so on.

I implemented a simple decision engine, which works fine but has one huge flaw, in the moment you take a decision the story is influenced immediately by your decision, which means that you can't take a decision that will affect you in the far future. This is because the story unfolds like a branch in a tree structure, and it always needs to know which node is next. Under the hood, the decisions are implemented using a queue: each node knows about the previous node and the next node (or if it's a decision node it waits for user input to set the next node)

I saw lots of games that have complex decision engines, and I wonder, how are they made? Is there a special design that makes the things really easy? Did anyone did something similar and can give me a hint on how to tackle this?

UPDATE 1:

An important aspect is to manage to somehow keep the story code independent, so that it can be manipulated from an external file. I plan to use this as an engine so even the possible choices have to come from an external file. The code has to be totally abstract.

Also, I'm interested in a design solution, a nice way to do it, how others do it or did it.


texts:
I'm generating a basic terrain and it looks something like this:

// Load the vertex and index array with the terrain data.
    for (j = 0; j<(m_terrainHeight - 1); j++)
    {
        for (i = 0; i<(m_terrainWidth - 1); i++)
        {
            index1 = (m_terrainHeight * j) + i;          // Top left.
            index2 = (m_terrainHeight * (j + 1)) + i;      // Bottom left.
            index3 = (m_terrainHeight * j) + (i + 1);      // Top right.
            index4 = (m_terrainHeight * (j + 1)) + (i + 1);  // Bottom right.

            // Top left
            vertices[index].position = glm::vec3(m_heightMap[index1].x, m_heightMap[index1].y, m_heightMap[index1].z);
            vertices[index].texture = glm::vec2(m_heightMap[index1].tu = 0.0f, m_heightMap[index1].tv = 0.0f);
            indices[index] = index;
            index++;

            // Bottom left.
            vertices[index].position = glm::vec3(m_heightMap[index2].x, m_heightMap[index2].y, m_heightMap[index2].z);
            vertices[index].texture = glm::vec2(m_heightMap[index2].tu = 0.0f, m_heightMap[index2].tv = 1.0f);
            indices[index] = index;
            index++;

            // Top right.
            vertices[index].position = glm::vec3(m_heightMap[index3].x, m_heightMap[index3].y, m_heightMap[index3].z);
            vertices[index].texture = glm::vec2(m_heightMap[index3].tu = 1.0f, m_heightMap[index3].tv = 0.0f);
            indices[index] = index;
            index++;

            // Top right.
            vertices[index].position = glm::vec3(m_heightMap[index3].x, m_heightMap[index3].y, m_heightMap[index3].z);
            vertices[index].texture = glm::vec2(m_heightMap[index3].tu = 1.0f, m_heightMap[index3].tv = 0.0f);
            indices[index] = index;
            index++;

            // Bottom left.
            vertices[index].position = glm::vec3(m_heightMap[index2].x, m_heightMap[index2].y, m_heightMap[index2].z);
            vertices[index].texture = glm::vec2(m_heightMap[index2].tu = 0.0f, m_heightMap[index2].tv = 1.0f);
            indices[index] = index;
            index++;

            // Bottom right
            vertices[index].position = glm::vec3(m_heightMap[index4].x, m_heightMap[index4].y, m_heightMap[index4].z);
            vertices[index].texture = glm::vec2(m_heightMap[index4].tu = 1.0f, m_heightMap[index4].tv = 1.0f);
            indices[index] = index;
            index++;
        }
    }

Now If I wanted to find which grid square the player is on, we could simply (if the camera position is relative to the terrain)

    //Grid square the camera is on
    int gridX = (int)std::floor(cameraX / gridSquareSize);
    int gridZ = (int)std::floor(cameraZ / gridSquareSize);

Continuing, we know that each face consists of two triangles, and the top triangle is represented by three vertices which index corresponds to top left, bottom left and top right. The bottom triangle would then be top right, bottom left and bottom right. Now I'm having a hard time trying to find height values (y-values) at these points because if I try to do

//Top left triangle
glm::vec3(0, vertices[(m_terrainHeight * gridZ) + gridX].position.y, 0) //Top left
glm::vec3(0, vertices[(m_terrainHeight * (gridZ) + 1) + gridX].position.y, 1) //Bottom left
glm::vec3(1, vertices[((m_terrainHeight * gridZ)) + (gridX + 1)].position.y, 0) //Top right

we conclude that the top left and bottom left position will be okay, but the top right position won't get the correct index, because as it is now (if we say that gridX = 0 and gridZ = 0), the index will generate a value of 1, which is not the correct height value at that position because the index we want should be 2 (top right). So, is there a way I could write the code so I would get the correct index for the triangles of the terrain?


texts: Memory allocation strategy for the vertex buffers (DirectX 10/11)

texts:
I'm writing a CAD system. I have a 3D scene and there are many different objects (walls, doors, windows and so on). The user can add or delete objects.
The question is: How do I keep track of all the vertices for all my objects?

I can create vertex buffer for every object. But I think drawing/switching from one buffer to another would have performance penalty.

Another way - I can create several big buffers for every object type. But I don't understand how to update such buffers. It is too big to update whole buffer (for example buffer for all walls). What would I do if I wanted to delete an object that's in the middle of the buffer?

I have the similar question here on Stack Overflow.

Most examples I've found work with static models. Therefore, they tend to create a single vertex buffer with their list of points, and then are just manipulated by matrix transformations. I, on the other hand, will be updating the scene very often. So what's the best way to keep track of and store this information?


texts: How to Generate Level Map Based on Golden Ratio

texts:
I am trying to generate a map based on the Golden Ratio:

a+b is to a as a is to b.

I was looking at a JavaScript math library that had a built-in phi, but I wasn't sure how to apply it.
I also tried using hard-coded values as can be seen in this example:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Konva Drag and Drop Demo</title>

Which creates the following pattern:

What I am looking for is more like this:

Note: this grid was roughly hand drawn and is not to scale.


texts: Why aren't tangent space normal maps completely blue?

texts:
Why aren't normal maps just blue? I would think that normal maps should be predominantly blue in color because the Z component of the normal is represented by blue. Normals point out of the surface in the Z direction so we should see blue as the predominant colour since the Z component is dominant.

By definition tangent space is perpendicular to the surface. At any point we should have the normal always pointing in the Z (blue direction) with no X (red direction) or Y (green direction). Thus the normal map (since it is a "normal map") should have the colour of the normals which is just blue (R = x = 0, G = y = 0, B = z = 1) with no shades in between.

But normal maps are not so, and they have gradients of shades in them. Why is this so?


texts: how to make my camera follow script work for Photon Pun2

texts:
I´m currently working on the Multiplayer part for a 2D top-down game. I´m using Photon Pun2, to do this. My problem is, that always just the last player, who joined the game get´s my camera follow script attached. I´ve tried setting an
if (!myPV.IsMine)
return;

on top of the function, but it doesn´t seem to work. I give you the script here, so it would be nice, if you tell me, where I have to do what, to get 2 (and more) different views of the camera
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    public Transform followTransform;

    // Update is called once per frame
    void FixedUpdate()
    {
        this.transform.position = new Vector3(followTransform.position.x, followTransform.position.y, this.transform.position.z);

    }
}


texts: Why not pre-render story parts in a game?

texts:
When playing games nowadays there are often story related cut-scenes, during which you cannot interact with the game, you can only listen to it or watch it while it plays.

However in a lot of games these story scenes are rendered live with the game engine, and not with pre-rendered videos. I can't seem to understand why the story scenes aren't pre-rendered during game development

My question is:

Why not pre-render a story cut-scene during game development as a video with the highest settings so the user doesn't need to render it on his/her end?

My guess is that game developers don't choose to do this because videos and real-time game rendering need a smooth transition a lot.


texts: Why are MVC & TDD not employed more in game architecture?

texts:
I will preface this by saying I haven't looked a huge amount of game source, nor built much in the way of games.
But coming from trying to employ 'enterprise' coding practices in web apps, looking at game source code seriously hurts my head:
"What is this view logic doing in with business logic? this needs refactoring... so does this, refactor, refactorrr"
This worries me as I'm about to start a game project, and I'm not sure whether trying to mvc/tdd the dev process is going to hinder us or help us, as I don't see many game examples that use this or much push for better architectural practices it in the community.
The following is an extract from a great article on prototyping games, though to me it seemed exactly the attitude many game devs seem to use when writing production game code:

Mistake #4: Building a system, not a game
...if you
ever find yourself working on
something that isn’t directly moving
your forward, stop right there. As
programmers, we have a tendency to try
to generalize our code, and make it
elegant and be able to handle every
situation. We find that an itch
terribly hard not scratch, but we need
to learn how. It took me many years to
realize that it’s not about the code,
it’s about the game you ship in the
end.
Don’t write an elegant game component
system, skip the editor completely and
hardwire the state in code, avoid the
data-driven, self-parsing, XML
craziness, and just code the damned
thing.
... Just get stuff on the screen as
quickly as you can.
And don’t ever, ever, use the argument
“if we take some extra time and do
this the right way, we can reuse it in
the game”. EVER.

is it because games are (mostly) visually oriented so it makes sense that the code will be weighted heavily in the view, thus any benefits from moving stuff out to models/controllers, is fairly minimal, so why bother?
I've heard the argument that MVC introduces a performance overhead, but this seems to me to be a premature optimisation, and that there'd more important performance issues to tackle before you worry about MVC overheads (eg render pipeline, AI algorithms, datastructure traversal, etc).
Same thing regarding TDD. It's not often I see games employing test cases, but perhaps this is due to the design issues above (mixed view/business) and the fact that it's difficult to test visual components, or components that rely on probablistic results (eg operate within physics simulations).
Perhaps I'm just looking at the wrong source code, but why do we not see more of these 'enterprise' practices employed in game design? Are games really so different in their requirements, or is a people/culture issue (ie game devs come from a different background and thus have different coding habits)?


texts: Pretty open source game/rendering engine?

texts:
It might be outside the domain of open source (as there isn't much in the way of open source games that would want/need to implement all these) but is there an existing open source game or rendering engine capable of things such as :

day/night cycles
dynamic weather wind/rain/clouds/etc
wet surfaces (surfaces look wet during rain)
realistic water
large terrains with the ability to define "roads"
seamless exterior and interior
forests (lots of trees, clutter, etc)
realistic lighting (ie. light from a fire/candle flickers)

if game engine :

integrated physics
support for vehicles
ai
multiplayer/network capable.. maybe mmo
voice recognition
etc


texts:
I am looking for some good online (ebooks) resources about strategy games discussing the gameplay and the interactive aspects of strategy games, and how to design interesting and challenging strategy game.

I found this book (http://www.amazon.co.uk/Game-Guru-Strategy-Dave-Morris/dp/1904705456) and seems interesting by reading table of contents. Unfortunately, I did not find any way to buy an ebook version of it and I am in Middle East and ordering this book would take lots of time.

Any idea?


texts: Unity - Sprite disappears completely when just a part of it is outside the camera's FOV

texts:
I'm making a game in Unity, and when the player walks past a sprite, the sprite disappears, and when the player walks back toward it, it reappears. You can see a video of the problem here https://www.youtube.com/watch?v=jgLN3m94tBo

I've also included my camera script below if anyone wants to check that out. Any help on this matter would be more than appreciated.

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

public class Camera : MonoBehaviour {

private Transform target;

private float minX = 7.99f;
private float minY = -19.09f;

public float maxX, maxY;

void Start()
{
    target = GameObject.Find("Player").transform;
}

void LateUpdate()
{

    transform.position = new Vector3(Mathf.Clamp(target.position.x, minX, maxX), Mathf.Clamp(target.position.y, minY, maxY), transform.position.z);
}
}

Here's a screenshot of my camera's settings


texts: Unity settings overlapping other settings error

texts:
In my unity game, I am using the amazing unity asset aura volumetric lighting and when I add its script into my camera this happens:

Yeah... I can't see anyone else who got these settings overlapping each other on the stack exchange or anywhere else. Not only does it overlap but I can actually change its settings and the camera settings if I click in the right areas! I restarted unity but it still doesn't fix anything. Please help. Thanks in advance!


texts: Mesh does not translate accordingly to WheelCollider

texts:
So I am trying to implement a car controller script in Unity were the WheelTransform position and rotation is set with every update as the same as the WheelCollider position and rotation, it all works fine except for one thing: when translating the WheelTransform, if the car goes slowly, WheelTransform translates as expected, but when the car goes faster, there's a clear offset between the WheelTransform position and the actual position of WheelCollider. Here's the code were WheelTransform position and rotation is set as the same as the WheelCollider position and rotation:
private void UpdateWheels()
    {
        UpdateWheelPos(frontLeftWheelCollider, frontLeftWheelTransform);
        UpdateWheelPos(frontRightWheelCollider, frontRightWheelTransform);
        UpdateWheelPos(rearLeftWheelCollider, rearLeftWheelTransform);
        UpdateWheelPos(rearRightWheelCollider, rearRightWheelTransform);
    }

    private void UpdateWheelPos(WheelCollider wheelCollider, Transform trans)
    {
        Vector3 pos;
        Quaternion rot;
        wheelCollider.GetWorldPose(out pos, out rot);
        trans.rotation = rot;
        trans.position = pos;
    }

Every single one of the car controller scripts I've found and tried use the same code for this section, I have also tried with 2d sprites without any colliders as WheelTransform but neither the scripts or changing WheelTransform solved the problem. Thanks in advance for the help.


texts: Can I Debug.Log() on Android without all the callstack spam?

texts:
I get this:

I/Unity   ( 1908): Serialized file length: 754 bytes.
I/Unity   ( 1908): UnityEngine.Debug:Internal_Log(Int32, String, Object)
I/Unity   ( 1908): UnityEngine.Debug:Log(Object)
I/Unity   ( 1908): SerializeTest:Test() (at Z:\Pong\Devel2010\Src\UnityGames\BhvrDemo\BinarySerialization\Assets\Script\SerializeTest.cs:64)
I/Unity   ( 1908): UnityEngine.Events.InvokableCall:Invoke(Object[])
I/Unity   ( 1908): UnityEngine.Events.InvokableCallList:Invoke(Object[])
I/Unity   ( 1908): UnityEngine.Events.UnityEventBase:Invoke(Object[])
I/Unity   ( 1908): UnityEngine.Events.UnityEvent:Invoke()
I/Unity   ( 1908): UnityEngine.UI.Button:Press() (at C:\BuildAgent\work\d63dfc6385190b60\Extensions\guisystem\guisystem\UI\Core\Button.cs:36)
I/Unity   ( 1908): UnityEngine.UI.Button:OnPointerClick(PointerEventData) (at C:\BuildAgent\work\d63dfc6385190b60\Extensions\guisystem\guisystem\UI\Core\Button.cs:45)
I/Unity   ( 1908): UnityEngine.EventSystems.ExecuteEvents:Execute(IPointerClickHandler, BaseEventData) (at C:\BuildAgent\work\d63dfc6385190b60\Extensions\guisystem\guisystem\EventSystem\ExecuteEvents.cs:52)
I/Unity   ( 1908): UnityEngine.EventSystems.ExecuteEvents:Execute(GameObject, BaseEventData, EventFunction`1) (at C:\BuildAgent\work\d63dfc6385190b6

but I would like this:

I/Unity   ( 1908): Serialized file length: 754 bytes.


texts: How should I implement an Observer patter in the following example

texts:
I am wondering how I implement an observer pattern in the following example. I am mostly wondering what should be in charge of subscribing.

The Example

A factory produces cars (Observable), they drive from A to B. Once at B the car has finished.  The scoreboard increases by +1 (Observer).

The Solution?

Option A.) The factory spawns a car, it then calls a method to subscribe the car to the scoreboard

observableCar.FinishedEvent += observerScoreboard.HandleEvent;

Option B.) Should the cars on being created register / tell the the scoreboard to subscribe itself to it the cars finishedEvent()

this.FinishedEvent += observerScoreboard.HandleEvent;

Option C.) The scoreboard is subscribed to a 'carSpawned' event on the factory. On recieving this event it then subscribes itself to the cars finishedEvent(). It then unsubscribes.

Option D.) I am missing something fundamental about the observer pattern, do more homework

I'm thinking its something more akin to option C? I'm not sure.

Thanks very much

Jim


texts: Disposing of ContentManager increases memory usage

texts:
I'm trying to wrap my head around how memory management works in XNA 4.0
I've created a screen management test and when I close a screen, the ContentManager created by that screen is unloaded.
I have used ANTS Memory Manager to look at how the memory usage is altered when I do this, and it gives me some results which makes me scratch my head.

The game starts with loading two textures (435kB and 48,3kB) which puts the usage at about 61MB. Then, when I delete the screen and runs Unload on the ContentManager, the memory usage drops to 56,5MB but instantly after goes up to 64,8MB.

Am I doing something wrong or is this usual for XNA games? Do I have to dispose of everything the ContentManager loads seperatly or do I need to do something more to the ContentManager?

Thanks in advance!


texts: How can I make relative movement in GameMaker studio?

texts:
I know I can change the hspeed and vspeed properties on my object. Assume I do it for the directional diamond in a squared-style movement game (not necesarily snapping to tiles, but it could). So the following scenarios apply (for any constant K) for my obj_Hero object:

Pressing UP: vspeed is -K, hspeed is 0
Pressing DOWN: vspeed is K, hspeed is 0
Pressing LEFT: vspeed is 0, hspeed is -K
Pressing RIGHT: vspeed is 0, hspeed is +K
Otherwis: vspeed and hspeed are 0
Only one directional arrow at the same time will be considered (the last pressed).

My player starts from position of an obj_Start object, and wins when reaching (colliding) an obj_End object. In the meantime, an obj_Enemy will be chasing the player using a step avoid strategy to avoid the player. The player loses if the enemy collides with him. Assuming I can correctly select the enemy current direction sprite, I'm done.

So far, so good.

Now assume some parts of my game have moving platforms. They have a specific platform speed vector (PSH, PSV), assuming I have such constants.

I know I could always condition my player movement speed to be:

(K + PSH, PSV) for player moving right
(-K + PSH, PSV) for player moving left
(PSH, K + PSV) for player moving down
(PSH, -K + PSV) for player moving up
(PSH, PSV) for player not moving

But... How do I alter (relative to the platform movement, as I do with the player) the enemy movement when it is actually generated by the step avoiding strategy?


texts:
So I'm starting work on a multi-player space shooter. And I've run into some issues. As I type this, my system is currently:

//Main While Loop
Gather Input
Update Own Sprites Based on Input
Send Position Information to Server. [Owner,Obj#,Image,X,Y,Theta] (TCP)
Receive All Position Information for All Objects From Server
Update Game Screen.

Now I won't end up using this, it's for the initial networking testing phase. I'll probably end up using dead reckoning. However I have a couple questions:

1: I am using TCP for all my networking. However it jumps and skips if you drop any packets at all, so I'd like to switch to UDP and have a numbering mechanism to make sure all packets arrive. Is there a preferred Networking Schema for game communication?

2: For critical things like object hits with bullets Should I implement a second port for these important events, or just use the same UDP proto?

3: (Side Question) How should I regulate my framerate with the networked game? I don't want to have an unnecessary Sleep in each frame...


texts: How to use a .cube LUT file with Color Lookup?

texts:
I have used "Image 2 LUT" to create a LUT for Unity from a certain movie.
However, currently "Image 2 LUT" only outputs ".cube" files.
For HDRP, this is great, but for some reason, URP doesn't accept .cube file.
URP expects specially laid out .png LUT file.
Is there any way to convert a .cube LUT file to a PNG that I can put into the slot of Color Lookup-> Lookup Texture with URP?
Unity expect this format:

The tutorial that Google finds and recommends is this.
However, I don't have Photoshop. Also, the tutorial deals with a square LUT that looks like this:

So even if I had Photoshop and I would follow the tutorial, I would still have a square LUT which is not laid out as Unity would expect it, so I did not use that tutorial.
How do I create a LUT png from a .cube file that I can use with URP?
Thank you.


texts: How do I draw a multi-object mesh at once?

texts:
This is a very elementary question. At the moment I am drawing lots of faces separately by setting a location uniform separately for each one of them. This is very slow. As I understand it, the correct way to do this is to build a large mesh and draw it all at once.

I am not sure if I understand how to do this, and since it is quite a bit of work, I would prefer to know before I start doing.

The only thing I can think of is to create a large vertex coordinate array that has the information of global world position instead of the vertex coordinates in -1...1 range, and use that as vertex position attribute without changing the location uniform for each face. Then I need to create a corresponding array that takes care of the indices of the points to form proper faces.

In case this is correct so far, are texture coordinates and face normals produced the same way?


texts: Is it a good idea to simplify a character-driven game engine to the point where it's unnecessary to learn scripting/programming?

texts:
I remember, and I still think, that one cannot even make a prototyped 3D game to test just simple behaviors without using gigantic tools like unity or knowing extensive C++ programming, design patterns, a decent or basic 3D engine, etc.

Now I'm wondering, since I know programming, whether I'm even more lucky than the ones who need to learn programming before knowing how to make something. Even scripted engines such as Unity are not for kids, and to my sense they tend to dictate their ways of doing things. This is not the case with engine like Ogre or Irrlicht.

Now I'm thinking that character-driven games occupy a big part of the game market. Do you think it is a good idea to make a character-control oriented game engine which only allows building AI to the exclusion of anything else?

When I say prototype, I also mean "generic" in the sense that one can quickly choose from a set of gameplay parameters such as the scene manager, the camera POV of the player, the controls, some very basic collisions/physics, and integration of basic steering (OpenSteer for example). The main idea is to make an AI sandbox but in 3D, so it can be demonstrated without the 2D constraints (and also make it more fit to prototype in 3D for a 3D project instead of 2D).


texts: Only apply Advanced Graphics on high FPS Dynamically

texts:
I wonder why not prevent lags by only appying advanced optional graphics stuff when the FPS are high at time. So The game could use simpler or even no shaders and skip decorative models some time.

It there an approach of dynamically calculating more or less each frame for higher FPS yet?

Is there a project using this approach yet?


texts: TiledMap resizing and aspect ratio with LibGDX

texts:
I'm making a game and I don't know how to resize my TiledMap when the window is bigger but keeping its squared shape.

Here is a screen:

When I change window size, here's what happens:

I want to see all the map with all window sizes.

Here's my GameScreen file

http://pastebin.com/rgKgHskN

Thank you for your help and I'm sorry for those big screenshots and for my english.


texts:
I'm trying to create a simple turn based console (command line) game but I'm confused of what approach to use when creating classes for objects. My concern is maintainability and flexibility.

First Approach:

class Weapon{
    ...
}

class Sword:Weapon{
    ...
}

class ShortSword:Sword{
    ...
}

class TwoHandedSword:Sword{
    ...
}

class Axe:Weapon{
    ...
}

class HeavyAxe:Axe{
    ...
}

Second Approach:

class Sword{
    SwordType type;
    ...
}

class Axe{
    AxeType type;
    ...
}

So which is better, first or second? Why?

Important Note: I'm a beginner in game development.


texts: Cylindrical billboarding around an arbitrary axis in geometry shader

texts:
I found an answer on this site relating to this question already, but it doesn't seem applicable in the context of my project.
Basically I'd like to create a method which fits this signature:
float3x3 AxisBillboard(float3 source, float3 target, float3 axis)

That is to say, when given a source point (i.e an object's position in world space), a target (camera position in world space), and an axis (the object's up vector, which is not necessarily the global y axis), it produces a 3x3 rotation matrix by which I can multiply the vertices of my point so that it's properly rotated.
I've found many solutions and tutorials online which work nicely assuming I only want to rotate around the y axis.
For example, here's a solution which billboards around the global y axis:
float3 dir = normalize(target - source);

float angleY = atan2(dir.x, dir.z);
c = cos(angleY);
s = sin(angleY);

float3x3 rotYMatrix;
rotYMatrix[0].xyz = float3(c, 0, s);
rotYMatrix[1].xyz = float3(0, 1, 0);
rotYMatrix[2].xyz = float3(-s, 0, c);

For context, I'm working on a grass shader, and each individual blade of grass should be billboarded to face the camera while remaining aligned with the normal of the terrain.
edit:
Thanks to @DMGregory I'm using his matrix method in the following way:
float3 viewDir = normalize(vertexPosition); // camera is at (0, 0, 0)
float3x3 billboardMatrix = transpose(AxisBillboard(worldUp, viewDir));
float3 worldPosition = vertexPosition + mul(billboardMatrix, localPosition);

This works correctly when grass is rotated to align with world space. In other rotations, grass is still billboarding 'correctly' around its local y axis but also has another rotation applied. Any ideas?


texts: How do I end a behavior tree's action early without evaluating the entire active branch?

texts:
I'm reading about behavior trees, and one of the common recommendations I've seen is to maintain a reference to your running action so that you don't have to traverse the entire tree during every game loop.  Without traversing the entire tree every time, how do I check if an action should end early?

For example, suppose I have the following tree and the AI encounters an enemy that's closer than 10m, so he starts to aim his weapon.  But then while he's aiming, his HP drops below 50%.  I would want the agent to stop the aiming/firing sequence and move to the "use medkit" action.

The only way that I can think of to accomplish that sort of behavior is to evaluate every node in the active branch -- starting from the root node -- during every game loop.  But based on what I've read, evaluating the entire active branch every game loop is discouraged.

Is there a way to be able to abort an action if a higher-level node is no longer valid, while not spending a lot of processing power evaluating the entire branch every game loop?


texts:
I'm creating a basic endless runner game on Android using SurfaceView.

I have background that recreates itself constantly, which was simple enough.

One problem I've always had is getting my head around animating sprite-sheets, not just in Android but other platforms as well.

Based on the problem I'm stuck on right now.. I have a sprite sheet thats 9 images 2 rows, 5 columns, with an empty space at the end of the second row.  All of which is one single running animation.

I've made a Sprite Class.

public class Sprite {
    GameView gameView;
    Bitmap bmp;
    private int x, y, width, height;
    private int spriteColumns 5, spriteRows= 2;
    private int currentAnim = 1;

    public Sprite(GameView gameView, Bitmap bmp) {
        this.gameView = gameView;
        this.bmp = bmp;
        this.width = bmp.getWidth() / spriteColumns;
        this.height = bmp.getHeight() / spriteRows;
    }

    public void update() {
       // do something here with currentAnim, x and y;
    }

    public void onDraw(Canvas c) {
       update();
       canvas.drawBitmap(bmp, x, y, null);
    }

}

How do I go about doing this?  Am I on the right track so far?


texts: I am working on Bowling Ball game for android. And I want the Bowling Ball to feel like a Bowling ball in the real world. I've already tweaked the Rigidbody values and PhysicsMaterial but it's giving me that result. So, how do I make Bowling ball like real BowlingBall in Unity?


texts: How can I load a file in memory on the Apple IIGS?

texts:
I recently got an Apple IIGS and have it booting GS/OS off of a compact flash with 10 32MB ProDOS volumes. It's a great little setup and I've installed ORCA/M, 816 Paint, Merlin 16+ and Complete Pascal (also known as TML Pascal II) so I can get started programming games for it.

My first goal, for now, is to just display an image on the screen that I've saved from 816 Paint. But I don't even know how to load a file as binary into memory. How can I accomplish that using Pascal and the other tools I've listed above?


texts: Android/OpenGL ES2: How do I set fragment shader value using C;

texts:
This should be easy So I am using the following to create a fragment shader.

 GLbyte fShaderStr[] = "precision mediump float;"
    "void main()                                \n"
    "{                                          \n"
    "  gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); \n"
    "}                                          \n";

I then render a circle (collection of lines) the circle comes our red. If I change the code to...

GLbyte fShaderStr[] = "precision mediump float;"
    "void main()                                \n"
    "{                                          \n"
    "  gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0); \n"
    "}                                          \n";

The circle is now purple. My question is how do I control this dynamically? So for example when I receive an input I toggle the two colors?

I tried...

GLbyte vShaderStr[] = "attribute vec4 vPosition;   \n"
            "attribute vec4 inColor;   \n"
    "uniform mat4 Projection;   \n"
    "varying vec4 fragColor;   \n"
    "void main()                 \n"
    "{                           \n"
    "   gl_Position = Projection * vPosition; \n"
    "   fragColor = inColor; \n"
    "}                           \n";

GLbyte fShaderStr[] = "precision mediump float;"
    "varying vec4 fragColor;                   \n"
    "void main()                                \n"
    "{                                          \n"
    "  gl_FragColor = fragColor; \n"
    "}\n";

void initColor(){
    LOGD("Initing Color");
    GLfloat vVertices[] = { 1.0f, 0.0f, 0.0f, 1.0f };
    glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, vVertices);
}

However, this doesn't seem to work as the circle is now black.


texts: A good approach on working on player controller for movable platforms?

texts:
I have got my player controlling working out decent enough, except with mediocre animation controller for the player, but oh well.  All I have done so far is basic input: move, run, jump, multi-jump.  How would I approach making my player conform to the movement of the moving platform.  I know to move the platform relative to my player on top of adding more force if player has moved.  I have looked up some resources on line, but I am confused why they use certain methods.

def Platform ():
        //BROKEN
        if (activePlatform != null):
            newGlobalPlatformPoint = activePlatform.TransformPoint(activeLocalPlatformPoint)
            moveDistance = (newGlobalPlatformPoint - activeGlobalPlatformPoint)

            if (moveDistance != Vector3.zero):
                controller.Move(moveDistance)

            lastPlatformVelocity = (newGlobalPlatformPoint - activeGlobalPlatformPoint) / Time.deltaTime

        else:
            lastPlatformVelocity = Vector3.zero

        activePlatform = null

        if activePlatform != null:
            activeGlobalPlatformPoint = transform.position
            activeLocalPlatformPoint = activePlatform.InverseTransformPoint (transform.position)

I don't understand why it is important to get local and world positions.  Also, I don't understand moveDistance calculation.

My first intuition was doing something like moveDistance.y or moveDistance.x and changing them depending on the hit object positive or negative velocity.  Just getting some ideas.

I also use:

def OnControllerColliderHit (hit as ControllerColliderHit):
        if (hit.moveDirection.y < -0.9) & (hit.normal.y > 0.5):
            activePlatform = hit.collider.transform

to check which platform I have collided with and strictly focusing on the one below the player.


texts:
I'm trying to decide which engine I should start using to try to start building a game in.

I had chosen Unity, but upon hearing that Unreal Engine 3 had just become kinda free to use, I found myself questioning my decision.

Technically Unreal is still the most expensive commercially, then Unity, then id Tech 3 (free).

But, it also could be the fastest to work in? Or is just the most powerful, but Unity actually does so much for you, that it makes the most sense to work with this, and take a hit on performance/tuning (like Java/C#).

Thoughts please, can anyone speak from experience of all three?

I have experience with modding since the doom days, then in Quake 1 and Half Life. I also have experience in 3DS Max. I don't have a desire at this point my life to really get into the nitty gritty of C++ animation and rendering issues, I'd rather get something up and running quickly, to see if it's possible. But Unreal experience tempts me greatly.


texts: Algorithm for "healing" multiple rectangles into a smaller number of rectangles?

texts:
Say I have a grid of rectangles of different shapes and colors and I want to reduce (reasonably close to optimal is fine, optimal is not necessary) the number of rectangles to represent the same layout of colors.

The image above is a very simplified case and the whitespace between the rectangles is for visualization only -- they would actually be tightly packed.

What is an approach or algorithm name (happy to google) that can help me do this?


texts:
My car is moving very slowly even though I apply high amounts of torque to the wheel colliders. The only thing I found to be helpful was to increase the wheel's friction stiffness, but that really messes up the braking and makes the car shake.
The values I use for setting up the car and torque are realistic (1500 kg car, 20 kg wheels, a realistic torque value accounting for gear ratios etc.), so I don't understand the problem.


texts:
As this post title suggest, font of the scene become disappear when same scene call more than two time.

Following code I used for creating font.

 mNumberFontTexture = new BitmapTextureAtlas(
                            alienAttack.getTextureManager(), 256, 256);
 numberFont = new Font(alienAttack.getFontManager(), mNumberFontTexture,
                            Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 52, true,
                            Color.YELLOW);

Based on requirement I load a font texture as per the following way.

    public void loadLevelSelectGraphics() {
            levelSelectBitmapTextureAtlas.load();
            mNumberFontTexture.load();
            numberFont.load();
    }

    public void unloadLevelSelectGraphics() {
            levelSelectBitmapTextureAtlas.unload();
            numberFont.unload();
    }

I am using scene base approach for developing game.
Please suggest me in which thing I am doing mistake. Thanks for your effort.

EDIT

Screenshot represent the problem which was occur after multiple load and unload font method.


texts: I am looking for a good application for generating 3d terrains (really allowing generation and then some user-editing) . After a google search, I found many, but I need one that can export the entire terrain as a mesh. This, I was unable to find. (I need either a .obj .fbx or .3ds output) The size of the file that is written and the price of the program are not major factors in my decision.


texts: What way to draw random sprite from spritesheet in SFML?

texts:
I have a spritesheet(900x100) with of different colored shapes each size 100x100. I am trying to code a program such that, after every 2 seconds, one random sprite appears on screen. If I click, it should disappear and after 2 seconds another random shape should appear. If I don't, it should continue to show that image.

Using IntRect, I am able to cut out individual shapes out of the spritesheet and display them. I thought that in the IntRect parameters:

Shape.setTextureRect(sf::IntRect(0, 0, 100, 100));

I could replace the first 0, like this:

Shape.setTextureRect(sf::IntRect(((rand() % 8) * 100), 0, 100, 100));

and after 2 seconds, it would show me a new random sprite. However, after 2 seconds, the window shows what looks like a bunch of random shapes playing really fast one after the other, nothing and then 2 seconds later it repeats.

If I can't get the random images to work properly I don't think I'll be able to do the mouse events.

Here is my code so far:
main.cpp

#include <SFML/Graphics.hpp>
#include <iostream>
#include <stdlib.h>
#include <time.h>

int main()
{
    sf::RenderWindow window(sf::VideoMode(640, 480), "Tile Game");

    sf::Clock clock;
    sf::Time timer;

    sf::Texture shapeSpriteSheet;
    sf::Texture Background;

    sf::Sprite bg;
    sf::Sprite Shape;

    srand(time(NULL));

    Background.loadFromFile("bg.png");
    bg.setTexture(Background);

    shapeSpriteSheet.loadFromFile("shapes.png");
    shapeSpriteSheet.setSmooth(true);

    Shape.setTexture(shapeSpriteSheet);
    Shape.setPosition(sf::Vector2f(192, 146));

    while (window.isOpen())
    {
        sf::Event event;
        window.draw(bg);

        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        timer = clock.getElapsedTime();

        if (timer.asSeconds() >= 2)
        {
            Shape.setTextureRect(sf::IntRect(((rand() % 8) * 100), 0, 100, 100));
            window.draw(Shape);

            if (timer.asSeconds() > 2.1)
            clock.restart();
        }

        window.display();
    }

    return 0;
}

Update:

I've finally made it so that, every 2 seconds a sprite appears, on click it disappears. Now Im working on making every sprite randomly selected

New code:

if (clock.getElapsedTime().asSeconds() >= 2)
        {
            shapeVisible = true;
            Shape[0].setPosition(sf::Vector2f(192, 146));
            window.draw(Shape[0]);

            if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
            {
                if (Shape[0].getGlobalBounds().contains(window.mapPixelToCoords(sf::Mouse::getPosition(window))))
                {
                    clock.restart();
                }
            }

        }


texts:
I am planning to do geometry instancing in OpenGL ES 2.0
Basically I plan to render the same geometry(a chair) maybe 1000 times in my scene.

What is the best way to do this in OpenGL ES 2.0?

I am considering passing model view mat4 as an attribute. Since attributes are per vertex data do I need to pass this same mat4, three times for each vertex of the same triangle(since modelview remains constant across vertices of the triangle).

That would amount to a lot of extra data sent to the GPU( 2 extra vertices*16 floats*(Number of triangles) amount of extra data).

Or should I be sending the mat4 only once per triangle?But how is that possible using attributes since attributes are defined as "per vertex" data?

What is the best and efficient way to do instancing in OpenGL ES 2.0?


texts: How can I use voice commands to control my Windows Phone game?

texts:
Is it possible to use simple voice commands like "run right", "run left", "jump", "stop", "attack", "defend", "finish" to control the player in a Windows Phone 8 game?

How can I implement voice recognition and some voice commands in my game?


texts: I am going to make a terrain ( not too big ) for my RTS and I was wondering whether to use Unity's terrain tool or create a terrain in Blender and import it to Unity?..I have been told that Unity's terrain is intense work for the mobile GPU..So would it be any good to make the terrain in Blender ( in terms of performance )?


texts: Overcoming float limitations for planet-sized worlds in Unity

texts:
As far as I know, going further than 1M units from the world origin in Unity is hardly possible due to floating point precision issues.

Making a world more than 1M units in radius would require either using double vars for coordinates or utilizing some space division technique to divide a massive scene into hierarchical chunks with the smallest of them being around 10 000 units, i.e. each world-space position would be expressed by the chunk hierarchy the object's in and a bunch of float vars representing its local position (and possibly rotation and scaling) inside the last chunk.

Either way, doing this would require implementing a completly new coordinate system, so I'd like to know whether or not that is possible in Unity, and if so, how may I make it work with existing Unity systems like physics and so on.

P.S I can't just move the world into origin as the player moves since I want to have things going on simultaneously around the planet.

Thanks!


texts: How to display and hide complex object part in 2.5D

texts:
I am working on a 2.5D mechanical app. I use 3D software like Blender to render the 3D model to create the 2D assets for the 2D game engine (which's cocos-creator , but it doesn't matter for this case).

How can I hide a part of object which's covered by another object with in the game engine? A sort of mask or something else, I am not sure.

For it has hundreds of object in the scene, like a car engine with all parts. So the solution I am looking for need to be automatic or half-automatic generated by 3D software (eg.Blender, etc), instead of full manual work like using Photoshop to create the mask.


texts:
I have an array of sprites that are displayed in-order to make an animation. There is code in an update loop that has access to a value 'time' indicating how far along the animation is. Time is a float between 0 and 1 inclusive. It uses this value to calculate which frame to display.

update(time) {
  frames // An array of animation frames
  current_frame_index = time / animation_length
  display_frame(frame[current_frame_index])
}

This works if you assume that each frame is displayed for the same amount of time.

I would like to enhance this by allowing frames to have arbitrarily defined durations. So if I have a set of frames and durations:

name           duration

frame_one      0.2
frame_two      1.1
frame_three    1.0
frame_four     0.75
frame_five     1.4

and a value indicating the animation's progress, how can I determine which frame to display?

Thanks!


texts:
I'm writing a game which is situated on a tiled map. I have a PlayState on which there's a Board which cosists of Fields.

My Board is an isometric map of a city, where each tile is a kind of road. Depending on the type of the road, there's a different texture of a car (if we go up/ down or left/ right) + on some tiles a car will take more than one texture (because it turns).

I don't know what's the correct idea of putting a car into the game. Should a class Car be part of Field? Probably not because there are moments in which the car is on more than one field. So maybe a part of Board? But the texture of a car depends on the type of the road that it is on. What is more, I must deal with the fact that once a car is on a field, it moves in the boundaries of it - so should I insert some coordinates of a field itself?

Could someone write a pseudocode of classes Board and Field with the necessary variables? And explain how I should deal with car's movements? I'm working in Java's Libgdx if it matters.


texts: Failed to pass uniform in Metal shader modifier

texts:
I'm trying to write a simple shader able to pass the color to be used for drawing in the fragment shader, through a uniform. I load the shader modifier and pass the uniform:

let fragmentShaderPath = bundle.pathForResource("Cube", ofType: "fragment")!
let fragmentShader = try String(contentsOfFile: fragmentShaderPath)

let shaderModifiers : [String:String] = [
    SCNShaderModifierEntryPointFragment : fragmentShader
]

cube.geometry?.shaderModifiers = shaderModifiers

SCNTransaction.begin()
cube.geometry?.setValue(NSValue(SCNVector4: SCNVector4Make(0.0,1.0,0.0,1.0)), forKey: "myColor")
SCNTransaction.commit()

And this is my fragment shader modifier code:

#include <metal_stdlib>
using namespace metal;

float4 myColor;

_output.color = myColor;

But nothing happens: the object is drawn as black. If I try declaring myColor as a uniform, I get an error:


texts: Most efficient way to modify character mesh at run time

texts:
What is the most efficient way in unity to alter the mesh of a character in this scenario:

When the player pick up an item:

-A part of the mesh should be replaced, for example, the left arm is swapped by a robotic, rock, wood etc... arm.

-The animations are the same.

-Other parts may change in a different way, for example, left arm stone right wood.(This happens in a different pick up later)

-There is no problem if the game slows for a sec as this not happen "in action".

One more thing:

In general terms, what are the thing to consider when doing these modifications in terms of performance?(Such as polygons of the mesh, resolution of textures...)

Will many changes end up in consuming memory or other resources?


texts: How to integrate images into text lines in Unity?

texts: Here are two screenshots from Stellaris, where images are seamlessly integrated into the text. How can I achieve this in Unity?


texts:
I'm working for the first time on a game for Android using Unity and I need to use Google Cloud Messaging to receive push messages.

I've already done the integration of my Unity project with GCM, using this project, and of now I can receive and read messages sent to my phone while the game is running. However, I want to be able to receive them while the app is closed. Currently, if I send a message and the app is not running, I get an error stating that my app stopped working.

So, in essence, I want to know: what are the steps to handle incoming push messages when my app is closed, display them as a notification in Android and launch my game app when I open such notification? What else should I do outside Unity so my project can handle Android notifications while closed?


texts: What tool should I use for drawing 2D OpenGL shapes?

texts:
I'm working on a very simple OpenGL ES 2.0 game, and I'm not sure what tool to use to create the vertex data I need. My first thought was adobe illustrator, but I can't seem to find any info on how to convert an .ai file to vertices. I'm only going to be using very simple 2D shapes so I wonder if I need to use a 3d modelling program?

How is this typically done, when you are working with 2D non-sprite shapes?


texts: How can I place prefabs into a world in Unity?

texts:
I've looked around for a bit and can't seem to find any way to get a prefab with "Resource.Load" and then to place that object into the world. I'm making a roguelike so when the player enters a room, all rooms around load in. The room to the top would load a random prefab from a list of rooms, check if there's already a room where it wants to go and then PlacePrefab(transform.position, transform.position + 10units); So it would place the prefab 10 units above where the current room is (All code for the rooms will run from a centre object and the prefab would be placed on the centre.)

Thanks in advance for any help :)


texts: What will happen with PlayerPrefs data after updating the app?

texts:
I'm using PlayerPrefs (Unity3D, on Android).

If a user updates my application via the Google Play store, what happens to the data I've stored in PlayerPrefs?


texts: web based quizz game database design, how do I store results?

texts:
I'm building a very basic quizz type of php/mysql/ajax game.

At this stage I'm thinking about the DB design, and specifically how to score results, I've two options in my mind. But cannot decide which one is better (being self taught. mostly by doing things, I have no idea what are best practices or what can be useful or not.)

So, I've 3 tables:

Users -> contains: user_id, user_name, user_pass, user_score
Quizz -> contains: quizz_id, quizz_answer, quizz_question, quizz_value
Results -> this is the one I'm debating. Should I keep user results in a separate table and have it like: result_id, result_user_id, result_quizz_id, result_score
Or simply include results for user inside users table under user_results and save it as array of answered quizz_ids

I'm debating if it is good practice to have separate results table or not. If I've it separately it means 10K users can easily create 10K*100 results rows. On the other hand array in user_results can become to contain 100 keys.

Performance wise, and taking into consideration good practices, which way is better?

Can mysql handle 10K*100 row lookups constantly on the bases of user_ID? Or is it wiser to just explode array from user_results column?