texts: My method for switching between cameras in Unity does not change the main camera

texts:
I would like to be able to switch between a variable number of cameras in my scene.

The common approach requires toggling the active camera's 'enabled' property to true and setting the others to false.  This is an issue when iterating through the 'Camera.allCameras' array as it doesn't contain the inactive cameras.

I therefore thought that I could get around this by creating a local array of cameras during initialisation and then iterate through that:

using UnityEngine;
using System.Collections;

public class CameraSwitcher : MonoBehaviour
{
    int cameraIndex;
    Camera[] cameras;

    void Start()
    {
        cameraIndex = 0;

        // Assumes that all cameras are initially active in the scene
        cameras = new Camera[Camera.allCameras.Length];

        int i = 0;

        while (Camera.allCameras.Length > 0)
        {
            cameras[i++] = Camera.allCameras[0];
            Camera.allCameras[0].enabled = false;
        }

        // Does not get recognised as main camera when activated
        cameras[cameraIndex].enabled = true;
    }

    void HandleInput()
    {
        if (Input.GetKeyDown(KeyCode.F1))
        {
            cameras[cameraIndex].enabled = false;

            cameraIndex = ++cameraIndex == cameras.Length ? 0: cameraIndex;

            cameras[cameraIndex].enabled = true;
        }
    }

    void Update()
    {
        HandleInput();
    }
}

The two problems with this approach are:

1) I assume that all cameras in the scene are initially active

2) Setting the camera's 'isenabled' to true in the local camera array does not set the main camera and it therefore remains 'null'

How can I store all the cameras in the scene, regardless of their active status, iterate through the array and set the main camera based on the array index?


texts: Expensive operations and threading in XNA games

texts:
There's this post, it's highest voted answer got me curious about the many ways of threading games.

My game has input update, game logic update, user interface update and expensive operations methods. Usually the game runs smoothly, but sometimes the user triggers a very expensive method that makes the game freeze for a few seconds, which is of course unacceptable for release, but the method serves development purposes. I hope the freezing can be resolved by threading, so that expensive method may be used in release.

Everyone says the UI thread must have the highest priority, but I'd like it to be second to the input update thread, so the interface (as well as player controls) is as responsive as it can be. But maybe I'm wrong and it doesn't work as I'm imagining, I haven't really succeeded in trying out either way, since XNA is a bit different from a normal C# application (always running Update method instead of just going down the code).

Which threading option (ThreadPool, Thread or BackgroundWorker) should I use (and how) to achieve maximum responsiveness, while not letting the game freeze when doing occasional expensive operations?

Stuff to read on threading:

https://stackoverflow.com/questions/1506838/backgroundworker-vs-background-thread
https://stackoverflow.com/questions/1837962/asynchronous-delegates-vs-thread-threadpool
http://blog.stephencleary.com/2012/02/async-and-await.html


texts:
Console and PC games have patches sometimes to fix bugs which the developers missed/didn't have time to fix.

My question is how do these work?

Sometimes the patch files are a few megabytes in size. I don't understand how a small file can alter a complied program.


texts:
Why normal maps are predominantly blue instead of a random color?

I guess normal vectors of a 3D object can point in every direction, like:

(1.0, 0.1, 0.5), (0.1, -0.5, 0.3), (-0.51, 0.46, -1.0) ...


texts: How to update game handle touch input faster

texts:
I'm making a LibGDX game where the player needs to tap to jump. But in this game, the player has to tap extra fast because the player needs to jump extra fast.

The problem is, the program can't register the taps fast enough to keep up with the user.

I've tried to handle the input 3 times per frame, but that turned out to be very problematic.

public void handleInput(float dt){
        if(Gdx.input.justTouched()){
                player.jump();
        }
    }

@Override
    public void render(float delta) {
        handleInput(dt);
        handleInput(dt);
        handleInput(dt);

        //handle everything else down here

    }

Are there any other ways to handle input at the speed of the user?


texts: Referenced script only working for one asset Unity C#

texts:
In my game, there is a maze, which has its walls generated by several types of points. In the top row, there are points that I call "type A" point - they only generate walls vertically (downward). "Type B" points have only horizontal (sideways) walls, and "type C" points generate both horizontal and vertical walls. All "A, B and C" points also generate items

because of this, I am using "shared" functions that are referenced on another script, in order to boost efficiency and so that I don't have identical code for the functions of generation on these points, as they all generate items the same way, and where applicable, generate horizontal and vertical walls in exactly the same way.

The issue here is, that I have a central script, that, within the scripts for "A, B and C", is referenced (public void function). the referencing works perfectly well.

however all the vertical walls generate on exactly the same point "A", (of which is first in terms of it's position in the row, and additionally first in the hierarchy); instead of all the different point "A"'s, meaning the rest of the point "A"'s are blank.

My function is "GenVwall", short for "Generate Vertical Wall", located in the central script:

public void GenVwall () {

    GameObject objV;

    //Decide the probability of there being a tile
    float lvlF = Mathf.Log10(gameManagerS.lvlNum);
    float pointF = 38.2f + (9.8f * (lvlF + 1));
    float decideV = Random.Range(0, 100);

    //Spawn different wall types (vertically)
    if (decideV < pointF) {
        int vWall = Random.Range (0, 40);
        if (vWall <= 24) {
            objV = Instantiate (Resources.Load ("tiles/wallReg"), new Vector2 (transform.position.x, (transform.position.y - 0.417f)), transform.rotation) as GameObject;
        } else if (vWall > 24 && vWall <= 26) {
            objV = Instantiate (Resources.Load ("tiles/wallSpiked"), new Vector2 (transform.position.x, (transform.position.y - 0.417f)), transform.rotation) as GameObject;
        } else if (vWall > 26 && vWall <= 31) {
            objV = Instantiate (Resources.Load ("tiles/wallBreak"), new Vector2 (transform.position.x, (transform.position.y - 0.417f)), transform.rotation) as GameObject;
        } else if (vWall > 31 && vWall <= 35) {
            objV = Instantiate (Resources.Load ("tiles/wallHalf"), new Vector2 (transform.position.x, (transform.position.y - 0.417f)), transform.rotation) as GameObject;
        } else if (vWall > 35 && vWall <= 38) {
            objV = Instantiate (Resources.Load ("tiles/wallGate"), new Vector2 (transform.position.x, (transform.position.y - 0.417f)), transform.rotation) as GameObject;
        } else if (vWall > 38) {
            objV = Instantiate (Resources.Load ("tiles/wallExplode"), new Vector2 (transform.position.x, (transform.position.y - 0.417f)), transform.rotation) as GameObject;
        }
    }
}

and the referencing of the public void function, located within the "A" point script, is:

GameObject tempObj = GameObject.Find("genPointA");
    genPointS = tempObj.GetComponent<GenPointS>();
    genPointS.GenVwall();

Now, I believe the issue lies within the fact i use transform.position, and it's referring to the position of the first "point A" in the hierarchy.

Now, I'd like to know,

Is there a better way to make use of these functions? as I can't consider it too efficient to have the same function copy-pasted into the individual scripts for point "A, B and C".


texts: Farseer Physics collision detection vs intersection detection with sensors

texts:
I'm trying to make a game that uses Farseer physics engine as its main collision detection engine. I have a 2d circle body object that has a matching fixture (I used the CreatCircle method. I did not create the fixtures and bodies separate). When IsSensor is set to false, objects collide with this circle and bounce off. My goal was to have events triggered when other physics enabled bodies move through this field and just use the engine to detect the collisions (or rather intersections) so I set it to IsSensor = true, and now all the other bodies pass right through but I do not get collision events. The be specific, sometimes I do get events but not continuously as I would expect. My intention was to have this collision code fired each time the world re evaluated collisions.

Does anyone know a way to do this. My googling has led me nowhere and I'll be fudging with the limited farseer documentation I can find this weekend to try and get this right.

Thanks ahead of time.


texts: OpenGL back/front end threading and Doom 3 BFG engine

texts:
Introduction

I have been reading through the source code of id Software's Doom 3 BFG engine. The whole codebase is on GitHub at id-Software/DOOM-3-BFG. The architecture is both clean and elegant. The whole code base is of exceptional code quality. (It makes for a great code read.)

Fabian Sanglard has an easy to follow code review of the engine. In particular, I am interested in id Software's implementation of the renderer, which is explained here: http://fabiensanglard.net/doom3_bfg/renderer.php.

Architecture of renderer

Fabian's site offers this architectural diagram of the renderer.

From the source code, and from the review, you can see that the renderer consists of a frontend and a backend. The engine is multithreaded in two ways, first there is a job pool whose task items are consumed by worker threads without relying on mutexes (this is awesome). In addition to the job pool, the renderer front end and back also each have their own thread.

My implementation of something similar

I played around with trying to build something similar in my own game engine. I will probably make the repo public and link to it here at some point, in the future.

The renderer front end lives on the same thread as the program entry point main(), where my Service Provider and Subsystem Singletons also live. Upon startup it launches the backend on a separate thread. The front end talks to the back end via a non-blocking command buffer. I implemented it using this awesome single-producer / single-consumer non-locking queue on GitHub at cameron314/readerwriterqueue.

The backend consumes commands of the command buffer queue, and turns them into OpenGL calls. The backend creates and manages the OpenGL context lifecycle. (At the moment this is an obstacle, because I am using SDL2, and I don't want SDL API related functionality, like input, running on the renderer backend thread.

Is it worth it?

Aren't OpenGL calls suppose to occur asynchronously, given that we are somewhat successful at minimizing GPU / CPU synchronization? Is all the added architectural complexity worth it from a performance perspective? With more modern rendering techniques like vertex buffer streaming, it seems as if more and more work is done to transfer load from the CPU to the GPU, and to make drawing asynchronous.

Adding the command buffer queue also adds a relatively heavy layer of abstraction between the originating draw service call and the underlying driver call. This complexity certainly must impact cache coherence and branch prediction.

Newer, closer to the silicon graphics APIs like METAL, only further exaggerate my point. I guess moving away from the CPU is the obvious future path of progression for graphics performance.

Is it relevant?

As elegant as the Doom 3 BFG engine is, the architecture is probably a bit dated, and probably misses out on some new innovations. Did the engine originally rely on a fixed pipeline? This might explain this design choice.

Do any modern game engines use something like this?

Apology

Sorry for the long-winded and multi-faceted question. I hope the community will forgive me. I also realize, profiling would be able to answer my question. Unfortunately, neither my implementation of the technique I described, nor the method without it, is mature enough, to do any meaningful profiling. Not to mention, there are a whole lot of other variables as well.

I'd rather not build a complete rendering pipeline around a flawed and outdated idea, only to discover that it is over engineered and slow.

In the meantime, I will continue to develop my job schedular approach, but this could be a feature design improvement.

Any insights or discussion would be greatly appreciated. Thanks!


texts: Spherecast - enabling MeshRenderer of selector target around prefabbed object once hit and disabling Meshrenderer when not hit anymore

texts:
I have an interesting problem - I have been looking up for solutions on this but I think there is something I am missing and I require a little more knowledge.

I have a scene and the scene has an Oculus OVRRig set up.  I have a script with sphereCast connected to the right hand. This Spherecast shoots out to select a particular layer.  This is all working fine.

I have also the setting of an alpha color on the cross hair brings up the object when the SphereCast hits.

It is up until here it all works fine.  It is here I reiterate that my object is a spawned prefab - which seems to be causing trouble.  I say this because I cannot select and change the material of the crossHair as it affects all the prefabs.

I simply cannot deactivate it once the SphereCast stops pointing at it.

Two Pieces of code.  The first sets up the sphere cast - attaches to a specific target and sets up a bool - Switcher - for the next scene to allocate the MeshRenderer for the crosshair.

public float radius;//For the radius of the SphereCast
public LayerMask LayerMask1;//The current Layer I use for focusing on the Raycasting Objects
public float MaxtDistance;// The Overall reach of the Spherecast

public GameObject currentHitObject;
public Vector3 up;
public RaycastHit hit;
public Vector3 startPos;
public int moveSpeed;
public bool TransitionSwitcher = false;
public bool Switcher = false;

void Update()
{
    startPos = transform.position;
    up = transform.forward;

    if (TransitionSwitcher)
    {
        StartCoroutine(MoveTo());
    }

    if (Physics.SphereCast(startPos, radius, up, out hit, MaxtDistance, LayerMask1, QueryTriggerInteraction.UseGlobal))
    {
    //    Transform target = hit.collider.transform.GetChild(2).GetChild(0);
     //   target.GetComponent<MeshRenderer>().enabled = true;
        // OVRInput.SetControllerVibration(0.3f, 0.3f, OVRInput.Controller.RTouch);
        TransitionSwitcher = true;
        Switcher = true;
        currentHitObject = hit.transform.gameObject;
    }
    else
    {
        OVRInput.SetControllerVibration(0.0f, 0.0f, OVRInput.Controller.RTouch);
        Switcher = false;
    }

}
IEnumerator MoveTo()
{
    hit.collider.gameObject.transform.position = Vector3.Lerp(hit.transform.position, startPos, Time.deltaTime * moveSpeed);
    TransitionSwitcher = false;
    yield return null;
}

This second piece of code takes the Bool Switcher from the code above and either switches on or off the renderer.  I know why it isn't working properly in this - it allocates the boolean to all the prefabs this is attached to.

public GameObject cube;
public GameObject crossHair;
public bool result = false;

// Use this for initialization
void Start()
{
    cube = GameObject.FindWithTag("Player");
    crossHair.GetComponent<MeshRenderer>().enabled = false;
}

void Update()
{
    bool result = cube.GetComponent<Sphere2>().Switcher;
    print(result);

    if (result == true)
    {
        print("on");
        OVRInput.SetControllerVibration(0.3f, 0.3f, OVRInput.Controller.RTouch);
        crossHair.gameObject.GetComponent<MeshRenderer>().enabled = true;
    }
    else if (result == false)
    {
        print("off");
        OVRInput.SetControllerVibration(0.0f, 0.0f, OVRInput.Controller.RTouch);
        crossHair.gameObject.GetComponent<MeshRenderer>().enabled = false;
    }
}

Can anyone point me in the right direction with this?  It doesn't have to be the solution handed to me - rather how do I turn specific meshrenderers on and off when my spherecast hits them and leaves their reach respectively?


texts: Unity3d : Make prefab follow raycast hit

texts:
I've been trying to make a weapon script which fires a projectile (prefab) straight forward.I added to the bullet the first script shown here.And the second one to the main camera.The problem is that the gun doesn't shoot straight forward.I mean it shoots straight but in small distances it looks...crap.How can I make it so it follows the hit point of the raycast.I placed my attempt below.

Script 1:

var bulletSpeed : float = 20;

function Update ()
{
    transform.Translate(Vector3.forward * bulletSpeed * Time.deltaTime);
}

Script 2 :

var hit : RaycastHit;
    var forward = transform.TransformDirection(Vector3.forward);

    if(Physics.Raycast(transform.position, forward, hit, rayLength))
    {

    if(Input.GetButtonDown("Fire1") && canShoot==true && clip > 0)
    {
        var rocketInstance : Transform;
        rocketInstance = Instantiate(rocketPrefab, barrelEnd.position, transform.rotation);
        rocketPrefab.LookAt(hit.point);
        w();
        gun.animation.Play("Shoot");
        audio.PlayOneShot(soundEffect);
        clip -= 1;
    }
}

Thank you for your time,please help me!


texts: How do you convert an object to camera view with a matrix

texts:
I've been stuck with this math problem for quite some time. I'm trying to convert an object to viewport coordinates, similar to gluLookAt. I tried putting the threads and articles I found into code, but it doesn't give me the correct results.

import numpy as np

def toCameraCoords(points, cameraLoc, itemLoc):
    up_h = np.array([0, 1, 0])
    forward = (cameraLoc - itemLoc) / np.linalg.norm(cameraLoc - itemLoc)
    right = -np.cross(forward, up_h) / np.linalg.norm(np.cross(forward, up_h))
    up = np.cross(forward, right)

    M_translation = np.eye(4)
    M_translation[0:3, 3] = -cameraLoc

    M_rotation = np.eye(4)
    M_rotation[0, 0:3] = right
    M_rotation[1, 0:3] = up
    M_rotation[2, 0:3] = forward

    M = M_rotation.dot(M_translation)

    return M.dot(points)

points = np.array([
    [7, 7, 9, 9, 7, 7, 9, 9],
    [3, 5, 5, 3, 3, 5, 5, 3],
    [3, 3, 3, 3, 1, 1, 1, 1],
    [1, 1, 1, 1, 1, 1, 1, 1]
])

locations = toCameraCoords(points, np.array([0, 0, 8]), np.array([8, 4, 2]))

print(locations)

If you look at the image below, the top row shows a camera at location |0 0 8| which points at the centre of a cube |8 4 2|. I've used |0 1 0| as the upward direction.

The bottom row shows a camera in the origin pointing towards -z. If the camera is rotated around the z-axis, it does show the cube correctly, but this is as far as I got. Could someone point out what I'm doing wrong?


texts: GLSL shader performance reduced by loop?

texts:
I hav a fragment shader like this:

#version 330 core

in vec4 v_color;
in vec2 v_texCoords[10];

out vec4 frag_color;

uniform int actual_textures;
uniform sampler2D u_texture[10];

void main() {
    vec4 final_color = texture(u_texture[0], v_texCoords[0]);
    for(int i = 1; i < actual_textures; i++){
        vec4 tex = texture(u_texture[i], v_texCoords[i]);
        final_color = tex * tex.a + final_color * (1 - tex.a);
    }

    frag_color = v_color * final_color;
}

But somehow this slows my game down by 30 - 40fps in comparison to this approach:

#version 330 core

in vec4 v_color;
in vec2 v_texCoords[10];

out vec4 frag_color;

uniform sampler2D u_texture[10];

void main() {
    vec4 final_color = texture(u_texture[0], v_texCoords[0]);
    vec4 tex = texture(u_texture[1], v_texCoords[1]);
    final_color = tex * tex.a + final_color * (1 - tex.a);
    tex = texture(u_texture[2], v_texCoords[2]);
    final_color = tex * tex.a + final_color * (1 - tex.a);
    //...

    frag_color = v_color * final_color;
}

Why does a single loop slow the gpu down so much?


texts:
I am making a 2d platform game with a tiled map,i now avoid passing through the walls an the ground but when the character hit the ground it shakes vertically,and when i make it walk on a wall it shakes horizontally.
the atualization code:

public void atualizar() {

    this.detectarColisoes(mapa.getTilesAdjacentes(this.getXAbsoluto(),this.getYAbsoluto(),this.getXAbsoluto()+this.getWidth(),this.getYAbsoluto()+this.getHeight()));
    if(movendo){

        this.setVelX(direcao*5);
        if(this.getVelX()>0 && colisaoLateral==1){
            this.setVelX(0);
        }
        if(this.getVelX()<0 && colisaoLateral==-1){
            this.setVelX(0);
        }
    }else if(this.getVelX()!=0){
        if(this.getVelX()>0){
            this.setVelX(this.getVelX()-1);
        }else{
            this.setVelX(this.getVelX()+1);
        }

    }
    if(this.getXRelativo()>490 && this.getVelX()>0){
        mapa.moveMapX(this.getVelX());
    }
    if(this.getXRelativo()<150 &&this.getVelX()<0){
        mapa.moveMapX(this.getVelX());
    }
    if(estadoSalto==2 && this.getVelY()>0){
        estadoSalto=1;
    }

    super.atualizar();
    if(estadoSalto!=0){
        this.gravidade();
    }
    System.out.println(estadoSalto);

}

the code for the collision detection:

public void detectarColisoes(ArrayList<Rectangle> adjTiles){
    Rectangle chara=new Rectangle(this.getXAbsoluto(),this.getYAbsoluto(),this.getWidth(),this.getHeight());
    if(adjTiles.isEmpty()){
        if(estadoSalto!=2){
            estadoSalto=1;
        }
    }
    boolean caindo=true;
    this.colisaoLateral=0;
    for(Rectangle aux:adjTiles){
        Rectangle ints=aux.intersection(chara);
        if(!ints.isEmpty()){

            if(ints.height<ints.width){

                if(ints.y>chara.y ){

                    estadoSalto=0;
                    this.setVelY(0);
                    this.setY(this.getYAbsoluto()-ints.height);
                    nSaltos=1;

                    caindo=false;

                }

            }else{
                if(ints.x>chara.x){
                    this.setX(this.getXAbsoluto()-ints.width+1);
                    this.colisaoLateral=1;

                }else{
                    this.setX(this.getXAbsoluto()+ints.width-1);
                    this.colisaoLateral=-1;
                }

            }
        }
    }
    if(caindo){
        estadoSalto=1;
    }

}


texts: AABB Collision Detection: Why does the simple broadphase algorithm work better?

texts:
Hi I am working on barrier detection.

I used this swept aabb algorithm http://www.gamedev.net/page/resources/_/technical/game-programming/swept-aabb-collision-detection-and-response-r3084.

It suggests two ways to detect collision.
1. broadphase: this is a shorter-algorithm which can only detect non-collision 100%.
2. In order to make sure that there is a collision, the more detailed swept aabb algorithm has to be executed right after the broadphase one.

Strangely the broadphase algorithm alone detects a barrier collision each and every time and the more precise one actually doesn't at all times.

What I do in my code is basically the following:
My object moves towards the barrier with a constand speed vx = direction * speed * delta (that's the amount it moves each frame). So positionx = positionx + (direction * speed * delta) each frame. The broadphase-collision is calculated each frame by using vx and vy.

Are there some rare cases where the broadphase can actually detect a collision like in this one I described? Thanks so much for your help

Thanks so much


texts: Unity / How can i prevent my model from blinking when it doesnt have normals?

texts:
Somehow the light which is shining on a moving model is making it "blink" (its like getting very dark and then very lit again.

The model has no normals. (unity import settings: normals: none)

Is there a way to prevent the blinking?


texts: Does XNA 4.0 for Windows Phone 7 require Visual Studio 2010?

texts: I have a copy of Visual Studio 2008 Pro. The Windows Phone Developments tools which include XNA 4 continuously fail to install on my machine. I am wondering if it was due to having 2008 vs 2010. Any ideas?


texts: I am developing a game using libGDX game engine and box2d physics engine. There are asteroids in my game, I want to destroy their bodies randomly and fill with texture. How can I do it?


texts: How can I tweak this A* search pathfinding algorithm to handle different terrain movement values?

texts:
I'm creating a 2D map-based action game with similar interaction design as Diablo II. In other words, the player clicks around a map to move their player. I just finished player movement and am moving on to pathfinding.

In the game, enemies should charge the player's character. There are also five different terrain types that give different movement bonuses. I want the AI to take advantage of these terrain bonuses as they try to reach the player.

I was told to check out the A* search algorithm (http://en.wikipedia.org/wiki/A*_search_algorithm). I'm doing this game in HTML5 and JavaScript, and found a version in JavaScript: http://www.briangrinstead.com/blog/astar-search-algorithm-in-javascript I'm trying to figure out how to tweak it though.

Below are my ideas about what I need to change. What else do I need to worry about?

When I create a graph, I will need to initialize the 2D array I pass in passed on with a traversal of a map that corresponds to the different terrain types.
in graph.js: "GraphNodeType" definition needs to be modified to handle the 5 terrain types. There will be no walls.
in astar.js: The g and h scoring will need to be modified. How should I do this?
in astar.js: isWall() should probably be removed. My game doesn't have walls.
in astar.js: I'm not sure what this is. I think it indicates a node that isn't valid to be processed. When would this happen, though?
At a high level, how do I change this algorithm from "oh, is there a wall there?" to "will this terrain get me to the player faster than the terrain around me?"

Because of time, I'm also debating reusing my Bresenham algorithm for the enemies. Unfortunately, the different terrain movement bonuses won't be used by the AI, which will make the game suck. :/ I'd really like to have this in for the prototype, but I'm not a developer by trade nor am I a computer scientist. :D

If you know of any code that does what I'm looking for, please share!

Sanity check tips for this are also appreciated.


texts:
I've created a triangle for jbox2d...

public void createTri(){

    PolygonDef shape = new PolygonDef();

    shape.density = 2.0f;

    shape.friction = 0.8f;
    shape.restitution = 0.3f;
    shape.addVertex( new Vec2(35/RATE,35/RATE) );
    shape.addVertex( new Vec2(65/RATE,35/RATE) );
    shape.addVertex( new Vec2(45/RATE,55/RATE) );

    BodyDef bodyDef = new BodyDef();
    bodyDef.position.set(50/RATE, 50/RATE);
    bodyT= world.createBody(bodyDef);
    bodyT.createShape(shape);
    bodyT.setMassFromShapes();
}

... but when drawing it on canvas, how to I get position of all the vertexes?

with bodyT.getPosition().x and .y I can get only the center spot.

Thanks!


texts: Creating an external tool to edit Unreal project optimization settings

texts:
INTRO
I am creating a C++ app that will help users to set up optimization settings in the Unreal game engine. I want to let the program make all this work on its own. This application is being written for Windows 10 platform (maybe it will be cross-platform in the future).

PROBLEM DESCRIPTION
To make the program working as intended, I must be able to change configuration files, add some UE objects to the project and call editor functions (e.g. rebuild lights).

MY SOLUTION
I can parse some of the .ini files and edit them. However, the real problem is with UE objects and editor functions. One of the possible ways is to get symbols from the .dll and run that function in a separate process. Another way is to use the actual UE4 code for these tasks.

QUESTION
Is there any easier and safer way to achieve what I need?


texts: Android Studio with libGDX doesn't recognize boolean

texts:
In my game, when the users clicks an image button, the value of a boolean changes and then the game is closed. I mean, if I want to restart the game, I click this image button, the game is closed and immediately is opened. However this doesn't happen because the value of the boolean is false and I don't know why at all.

Here is the code of the image-button:

    playagain.addListener(new ClickListener()
    {
        @Override
        public void clicked(InputEvent event, float x, float y)
        {
            interfaccia.rigioca();
            Gdx.app.exit();
        }
    });

And this is the code of the MainActivity:

public class MainActivity extends Activity implements MyGdxGame.GestioneClick, Serializable
{
MainActivity activity;
boolean start;
@Override
public void onCreate(final Bundle bundle)
{
    super.onCreate(bundle);
    setContentView(R.layout.layout);
    activity = this;
    findViewById(R.id.button).setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            startActivity();
        }
    });

}

@Override
public void onResume()
{
    super.onResume();
    if(start)
        startActivity();
}

@Override
public void menu()
{
    start=false;
}

@Override
public void rigioca()
{
    start=true;
}

public void startActivity()
{
    Intent intent = new Intent(MainActivity.this,AndroidLauncher.class);
    intent.putExtra("MainActivity",activity);
    activity.startActivity(intent);
}

}

As you can see, rigioca method is called and start sould be true. I checked ALL with logs and we can say that the value is true. Then resume method is called but start value is false! How is it possible? I also took away start=false; in menu method, but that isn't the problem. Why is this variable false!?

Note: onDestroy and onCreate aren't called but the activity is destroyed.


texts: Rendering only a part of text FTGL, OpenGL

texts:
I'm using FTGL library to render text in my C++ project.

I can easily render text by using:

CFontManager::Instance().renderWrappedText(font, lineLength, position, text);

Unfortunately there is a situation in which this Button which displays text, is partly hidden because of resizing container in which it is situated. I'm able without any problem to draw Button's background to fit the container, but I've got a problem with doing the same with a text. Is it possible to somehow draw only text for given width and the rest just ignore?

This is a screen which presents my problem:

As you can see, the Button "Click here" is being drawn properly, but I can't do the same with "Click here" text.


texts: Should I store a value for every damage type even if zero, when using the Decorator pattern?

texts:
My game characters take damage by the method TakeDamage(Damage amounts), and the Damage struct has every type of damage (fireDamage, iceDamage, bluntDamage, etc.).  For now every Weapon has a lot of info in the Damage struct that isn't used, e.g. the common Hammer just has bluntDamage; and the others (fireDamage, edgeDamage, etc.) are all zero.

Is this the correct way, or should I use the Decorator Pattern for every kind of damage instead?  Or is there another way?


texts: How to flip a box2d body when it can't move forward? LibGDX

texts: I'm attempting to create a simple enemy for a platformer. It should move forward constantly until it hits something like a wall, and then it should flip and move forward the other direction. How might I accomplish this?


texts: 3D infinite platform generation: Can't increase space between platforms. (Unity)

texts:
As seen in the images, changing the value of 'spawnZ' affects the distance between the initial platform and the first generated platform but afterwards it has no affect whatsoever.

public GameObject[] tilePrefabs;

public float spawnZ = 10f;
public float tilelength;
public int amnTilesOnScreen = 5;
public Transform playerTransform;

// Use this for initialization
void Start () {
    for (int i = 0; i<amnTilesOnScreen; i++)
    {
        SpawnTile();
    }
}

// Update is called once per frame
void Update () {
if(playerTransform.position.z>(spawnZ - amnTilesOnScreen * tilelength))
    {
        SpawnTile();
    }
}

private void SpawnTile(int prefabIndex = -1) {
    GameObject go;
    go = Instantiate(tilePrefabs[0]) as GameObject;
    go.transform.SetParent(transform);
    go.transform.position = Vector3.forward * spawnZ;
    spawnZ += tilelength;

}


texts: How to change alpha of a sprite through script in Unity

texts:
I have 4 buttons and they each flash when the button is pressed. However if you were to press a button, then while the button is darker (flashing) click another one, that button then stays dark. I want to reset the color of the sprite before disabling them however it's not working. When the buttons are pressed they no longer flash....

Here is the code:

void Start () {
        easy.GetComponent<SpriteRenderer>().color = color;
    }

    void Update () {
        if(difficultySelected[0] == true){
            enemyBehavior.shotsPerSecond = 0.2f;
            //Enabling the selected button
            easy.enabled = true;

            //Reseting the colors
            normal.GetComponent<SpriteRenderer>().color = color;
            hard.GetComponent<SpriteRenderer>().color = color;
            expert.GetComponent<SpriteRenderer>().color = color;

            //Disabling the 'unselected' buttons
            normal.enabled = false;
            hard.enabled = false;
            expert.enabled = false;

            easy.Play("Difficulty");
        }else if(difficultySelected[1] == true){
            enemyBehavior.shotsPerSecond = 0.5f;
            normal.enabled = true;

            easy.GetComponent<SpriteRenderer>().color = color;
            hard.GetComponent<SpriteRenderer>().color = color;
            expert.GetComponent<SpriteRenderer>().color = color;

            easy.enabled = false;
            hard.enabled = false;
            expert.enabled = false;

            normal.Play("Difficulty");
        }else if(difficultySelected[2] == true){
            enemyBehavior.shotsPerSecond = 1;
            hard.enabled = true;


texts: Unexpected Behavior - Calling method on MonoBehaviour before Start() is called

texts:
I'm implementing object-pooling, though that's not the issue, and a bit confused about the order of operations between Monobehaviours. In the InitGame() method of MyGameManager, I call SpawnEnemy() on the EnemyManager singleton. What I would expect to happen (but is not happening) is for the Awake() method in EnemyManager to be called, then the EnemyManager-> Start() method, and then and only then, would SpawnEnemy() be called.
What actually happens is that EnemyManager Awake() is called, then MyGameManager calls SpawnEnemy(), and when that's done, EnemyManager's Start() method is called last.

The docs say,

  Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.

I'm guessing that while my EnemyManager is Active, it is not Enabled, and thus it's Start() method is not called until after the call to SpawnEnemy(). I found it surprising that a method can be called on an object before Start() is called on that object.

I can work around this situation by simply including the line gameObject.SetActive(false); in my EnemyManager's Awake() method, and thus the SpawnEnemy() method will find and spawn an object from the pool, but it would be helpful to have a deeper understanding of when Start() is actually called. I've read the docs and whatever I could find, but don't feel like I fully understand.

Here is the Manager Singleton designed to easily create XxxxManager classes:

using UnityEngine;

public class Manager<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _sharedInstance = null;

    public static T sharedInstance
    {
        get
        {
            if (_sharedInstance == null)
            {
                _sharedInstance = Object.FindObjectOfType<T>();
                if (_sharedInstance == null)
                {
                    Debug.Log("Can't find " + typeof(T));
                }
            }
            return _sharedInstance;
        }
    }

    public virtual void Awake()
    {
        // ...
    }
 }

An EnemyManager class:

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

public class EnemyManager : Manager<EnemyManager>
{
    static private List<EnemyManager> enemyControllers;

    public EnemyManager SpawnEnemy(Vector3 location)
    {

        foreach (EnemyManager controller in enemyControllers)
        {
            if (controller.gameObject.activeSelf == false)
            {
                controller.gameObject.transform.position = location;

                // object available
                controller.gameObject.SetActive(true);
                return controller;
            }
        }

        Debug.Log("Not enough enemies available in pool.");
        return null;
    }

    public override void Awake()
    {
        if (enemyControllers == null)
        {
            enemyControllers = new List<EnemyManager>();
        }

        enemyControllers.Add(this);

        // If we SetActive(false) here, we DO get the desired behavior
        gameObject.SetActive(false); // <-----

        base.Awake();
    }

    protected void Start()
    {
        // wake up and disable self
        // If we SetActive(false) here, we do NOT get the desired behavior
        gameObject.SetActive(false);  // <-----
    }
}

And I'm using these classes in MyGameManager:

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

public class MyGameManager : Manager<MyGameManager> {

    private EnemyManager enemyManager;

    public override void Awake()
    {
        enemyManager = EnemyManager.sharedInstance;
        base.Awake();
    }

    private void Start()
    {
        InitGame();
    }

    void InitGame()
    {
        enemyManager.SpawnEnemy(new Vector3(0, 0, 0));
    }
}


texts: What tool should I use to make this game?

texts:
A little background info: I'm just about to graduate university with a software engineering degree. I have a fair amount of experience with more "serious" programming languages (C++/Java/C#), plenty of theoretical background, and good learning ability. I have minimal experience in web development as a whole (some JSP/JavaScript), and only very little with game engines (used Slick2D once to make a simple platformer, and had a brief introduction to 2D XNA).

I was recently approached by some people who have a game idea, and are looking for implementors. The game is a 2D turn-based strategy web game with a persistent world (meaning a DB backend would likely be required to store world state, user info, etc), and several UI interfaces.

I know this is a rather vague description, but based on this, which free game engine/framework/toolkit should I be looking at? Or at least, which technology (Flash/HTML5/JavaScript) would make it the easiest for me to develop this game?


texts: Collision detection / physics for simple game

texts:
I am currently working on a mini game for class (first time doing something like this) and I don't really know how to start with collision detection at all. The game I'm creating is a top down sumo fighting game on a icy circular arena where you move around gaining momentum and velocity and try to knock each other off to gain points.

So far I have the movement acceleration/friction pretty much down and I also have a system to detect when a collision occurs, I just don't know how to actually push the characters away when they collide. I think I will base the knock back amount/ damage on the velocity the attacker has against their velocity alongside the character's resistance stat that I will be adding. I also assume that I will have to do some intense math with like tangents and stuff to get the direction correct but I'm not sure how to do that at all.

I would greatly appreciate any help and I am open to future help if you want to assist me on this project later via Discord or something. Thanks for everything.

import pygame, sys, time
from pygame.locals import *
import random
import math

#Colors
colorRed=pygame.Color(241,59,62)
colorPurple=pygame.Color(200,254,249)
colorBlue=pygame.Color(52, 207, 235)
colorGreen=pygame.Color(100,182,100)
colorWhite=pygame.Color(255,250,250)
colorBlack=pygame.Color(0,0,0)
colorOrange=pygame.Color(242,164,0)
colorBrown=pygame.Color(148,103,58)

#Dimensions
w=800
h=600
pygame.init()
fpsClock=pygame.time.Clock()
screen=pygame.display.set_mode((w,h))
pygame.display.set_caption ('SUMO')
centerX=w//2
centerY=h//2

#Stage
stageR=250
def stage (centerX,centerY):
    """stage (centerX,centerY) - creates a stage with given centerpoint"""
    pygame.draw.circle(screen, colorBlue, (centerX,centerY),stageR)

#Character 1
xR=int((stageR//10))
x1=int(centerX-(stageR*0.8))
y1=centerY
x1_dir=0
y1_dir=0
def char1 (x1,y1):
    """char1 (x1,y1) - creates char1 at given coordinates"""
    pygame.draw.circle(screen, colorRed, (x1,y1),xR)
print (x1)
print (centerX)

#Character 2
x2=int(centerX+(stageR*0.8))
y2=centerY
x2_dir=0
y2_dir=0
def char2 (x2,y2):
    """char2 (x2,y2) - creates char1 at given coordinates"""
    pygame.draw.circle(screen, colorGreen, (x2,y2),xR)

while True:
    screen.fill(colorBlack)
    for event in pygame.event.get():
        #Game Exit
        if event.type== QUIT:
            pygame.quit()
            sys.exit()

    distance=math.hypot(x1-x2,y1-y2)
    if distance <= 2*xR:
        print ("HIT")

    keys = pygame.key.get_pressed()

    if keys[K_d] or keys[K_a]:
        x1_dir += 0.1 if keys[K_d] else -0.1
    else:
        x1_dir *= 0.98

    if keys[K_w] or keys[K_s]:
        y1_dir += 0.1 if keys[K_s] else -0.1
    else:
        y1_dir *= 0.98

# -------------------- CHAR2 MOVEMENT --------------------

    if keys[K_RIGHT] or keys[K_LEFT]:
        x2_dir += 0.1 if keys[K_RIGHT] else -0.1
    else:
        x2_dir *= 0.98

    if keys[K_UP] or keys[K_DOWN]:
        y2_dir += 0.1 if keys[K_DOWN] else -0.1
    else:
        y2_dir *= 0.98

    stage (centerX,centerY)
    char1 (round(x1),round(y1))
    char2 (round(x2),round(y2))
    x1+=x1_dir
    y1+=y1_dir
    x2+=x2_dir
    y2+=y2_dir
    pygame.display.update()
    fpsClock.tick(60)
    ```


texts: How can I draw many objects on screen instead of just one?

texts:
Like many beginner graphics programmers I followed a tutorial which showed me how to set up buffer descriptions and fill out the vertex buffer etc... - the steps involved in drawing a simple indexed cube on the screen. There is a leap however when it comes to drawing more than one of these cubes. My code below is the original cube drawing code, if called more than once, each call overwrites the vertex buffer and only one object is drawn - the last one.

So what are the options for drawing many of these cubes?

Cube::Cube(D3DXCOLOR colour, D3DXVECTOR3 min, D3DXVECTOR3 max)
{
// create eight vertices to represent the corners of the cube
VERTEX OurVertices[] =
{
    {D3DXVECTOR3(min.x, max.y, max.z), colour},
    {D3DXVECTOR3(min.x, max.y, min.z), colour},
    {D3DXVECTOR3(min.x, min.y, max.z), colour},
    {min, colour},
    {max, colour},
    {D3DXVECTOR3(max.x, max.y, min.z), colour},
    {D3DXVECTOR3(max.x, min.y, max.z), colour},
    {D3DXVECTOR3(max.x, min.y, min.z), colour},
};

// create the vertex buffer
D3D10_BUFFER_DESC bd;
bd.Usage = D3D10_USAGE_DYNAMIC;
bd.ByteWidth = sizeof(VERTEX) * 8;
bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;

device->CreateBuffer(&bd, NULL, &pBuffer);

void* pVoid;    // the void pointer

pBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &pVoid);    // map the vertex buffer
memcpy(pVoid, OurVertices, sizeof(OurVertices));    // copy the vertices to the buffer
pBuffer->Unmap();

// create the index buffer out of DWORDs
DWORD OurIndices[] =
{
    0, 1, 2,    // side 1
    2, 1, 3,
    4, 0, 6,    // side 2
    6, 0, 2,
    7, 5, 6,    // side 3
    6, 5, 4,
    3, 1, 7,    // side 4
    7, 1, 5,
    4, 5, 0,    // side 5
    0, 5, 1,
    3, 7, 2,    // side 6
    2, 7, 6,
};

// create the index buffer
// D3D10_BUFFER_DESC bd;    // redefinition
bd.Usage = D3D10_USAGE_DYNAMIC;
bd.ByteWidth = sizeof(DWORD) * 36;
bd.BindFlags = D3D10_BIND_INDEX_BUFFER;
bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;

device->CreateBuffer(&bd, NULL, &iBuffer);

iBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &pVoid);    // map the index buffer
memcpy(pVoid, OurIndices, sizeof(OurIndices));    // copy the indices to the buffer
iBuffer->Unmap();

//this is simply a single call to the update method that sets up the scale, rotation
//and translation matrices, in case the cubes are static and you don't want to have to
//call update every frame
Update(D3DXVECTOR3(1, 1, 1), D3DXVECTOR3(0, 0, 0), D3DXVECTOR3(0, 0, 0));
}


texts:
I'm working on a roguelike and would like to know how to structure my map data. I suppose this question could also be extended to any sort of top down 2d game. Anyways! My game will contain object types like terrain, doors, switches, monsters, and items. How should the objects be stored within a map?

Some ideas I've gathered online:

The map is a 2d array. Each cell in the array can store multiple references to objects occupying it.
The map contains several layers of 2d arrays, and each layer stores references to objects of a specific type.
Like 1. but only store static terrain information in the 2d array. The rest of the objects are dynamic and stored in lists for each type.


texts:
Also I am attempting to implement some simple coloring by "slope" onto my planet and to do this I take the normal mapped normal "y" component and subtract it from one. Yet I am getting some strange effects, using a small grid for example:

to get this image I had to use the following code:

float slope = 1.0 - normal.y;
if(slope < 0.89){
color = vec3(0.545,0.353,0.169);
}else{
color = vec3(0.237,0.457,0.137);
}

Which doesn't make much sense to me. Also, as you can see, only one side of the terrain is being colored in this way. Shouldn't lower values for slope being more level?
Thanks for the help

EDIT:
Here is the terrain colored according to the pixels normal:


texts: Varying the strength of attacks by holding down the button

texts:
I am preparing a conference session about game design, and a question occurred to me that I haven't been able to answer with Google:

In Mario the player varies the height of Mario's jump by holding down the button while Mario is in the air. Has this approach ever been used to vary the power or attacks, i.e. hold down for a hard attack, tap for a fast attack. I feel like this must have been done many times but I can't think of a concrete example.

UPDATE 1: I'm specifically thinking about systems where the attack is launched as soon as you press the button, but gains power as you hold it down (like Mario's jump), rather than systems where you hold down to charge-up and release to attack.


texts: Does cube map texturing works only for objects which vertices are is in [-1,1] range?

texts:
Im attempting to texture an .obj file that is not a skybox. So the question is, every tutorial about cubemap creates their hardcoded cubes with vertices ranging from [-1, 1]. Probably not, but is it necessary to scale my .obj model to be in that range?

Also, to map my fragments with the right texel - I saw people online telling that I should take a point p then subtract it with the model center c in the shader. Some said that I should normalize them? normalize(p - c)  I hope you can help me deliver a brief explanation.


texts: How do I setup positional audio in Unity?

texts:
I'm trying to make an audio game where by players can tell the position of an object listening to whether the right or left speaker is playing the audio.

The idea is:

If the object is on the left hand side

Play the audio of that object through the left speaker

Right hand side = right speaker

How would I do this in Unity?


texts: Unity - Collision detection issue with CharacterController

texts:
I am making an isometric game (3d scene, using 2d sprites). Currently I am trying to add collision to the enviroment to prevent the player from walking through everything. However no matter what I do the player seems to simply ignore the and walks through the object. Below are some combination I have tried and the results I got. For this instance I am looking at the windmill object

NOTE: Player has a character controller , no rigidbody.

Scenario 1:

Windmill has Rigibody
IsKinematic false
No rotation & Position constraints
Boxcollider isTrigger == false

result: On touching object it start flying around. So collision is there.

Scenario 2:

Windmill has Rigibody
IsKinematic false
has rotation & Position constraints (all axis)
Boxcollider isTrigger == false

result: I can walk through the object and somehow the collision is gone. the reason for constraints is so that the object wont move. (its a windmill)

Scenario 3:

Windmill has Rigibody

IsKinematic false
both with and without rotation & Position constraints (all axis)
Boxcollider isTrigger == true

result: Debug.Log shows that there is collision

Now what I would like to achieve is that the windmill can't be moved yet also can't be moved through.I am willing to programm collision if needed, but i rather do it with the unity provided tools. Any idea what I am overlooking?

EDIT 1:

Since it was asked how I moved the player, I use the Fingers asset. We make use of the joystick to move the player around. Below is our JoystickExecuted method depicting what exactly I do.

 private void JoystickExecuted(FingersJoystickScript script, Vector2 amount)
{
    if (amount.x > 0 && !_facingRight)
    {
        FlipXAxis();
    }
    else if (amount.x < 0 && _facingRight)
    {
        if (amount.x > 0 && !_facingRight)
        {
            FlipXAxis();
        }
        else if (amount.x < 0 && _facingRight)
        {
            FlipXAxis();
        }
    }
    var pos = transform.position;
    pos.x += amount.x * 8 * Time.deltaTime;
    pos.z += amount.y * 8 * Time.deltaTime;
    transform.position = pos;
    _anim.SetBool("isWalking", true);

    if (amount == Vector2.zero)
    {
        _anim.SetBool("isWalking", false);
    }
}


texts:
I am writing a chess game using Java and Swing, And I wanted to get the tile position on which a mouse clicked. I searched through internet, but all of them were really off, and never accurate. When I clicked on a tile's first half, it said it was tile 1, but on the second half, it said it was tile 2, but it was still tile 1. So I was wondering, how can I do it?
My tile size is (75, 75) This is the code I've written for tileX: Math.floor((double)evt.getX() / 75), and this is the code I've written for tileY: Math.floor((double)evt.getY() / 75).
Code for drawing:
ImageIcon l_winter = new ImageIcon("/Users/user/NetBeansProjects/chess/src/b/bibe/assets/winter/light.gif");
        ImageIcon d_winter = new ImageIcon("/Users/user/NetBeansProjects/chess/src/b/bibe/assets/winter/dark.gif");
        ImageIcon l_wood = new ImageIcon("/Users/user/NetBeansProjects/chess/src/b/bibe/assets/wood/light.png");
        ImageIcon d_wood = new ImageIcon("/Users/user/NetBeansProjects/chess/src/b/bibe/assets/wood/dark.png");
        String theme = th;
        int color = 0;
        for (int i = 0; i < 600; i = i + 75) {
            for (int j = 0; j < 600; j = j + 75) {
                JLabel panel = new JLabel();
                panel.setText(null);
                panel.setSize(75, 75);
                if (color == 0) {
                    if (theme.equals("wood")) {
                        panel.setIcon(l_wood);
                    } else if (theme.equals("winter")) {
                        panel.setIcon(l_winter);
                    } else {
                        panel.setText("notexture");
                    }
                    //panel.setBackground(new Color(white[0], white[1], white[2]));
                    color = 1;
                } else {
                    if (theme.equals("wood")) {
                        panel.setIcon(d_wood);
                    } else if (theme.equals("winter")) {
                        panel.setIcon(d_winter);
                    } else {
                        panel.setText("notexture");
                    }
                    //panel.setBackground(new Color(black[0], black[1], black[2]));
                    color = 0;
                }
                panel.setLocation(j, i);
                getContentPane().add(panel);
            }
        if (color == 0) {
            color = 1;
        } else {
               color = 0;
            }
        }


texts: Facet file that contains face coloring inside the file

texts:
I'm looking for a few example facet file types that allow applying face materials in the same file.  At the moment I know of COLLADA (.dae) but I'm looking for others due to the difficulty on manually parsing and writing that I'm implementing.  Other requests I have are that the file is human readable, ie ASCII vs binary.  I've looked at Wavefront (.obj) formats but they require a secondary file for the face materials.  I've also looked into the PLY format but that one looks focused around vertex coloring vs face coloring.

Having an open and easy to understand format is greatly appreciated.


texts: How do I apply skeletal animation from a .x (Direct X) file?

texts:
Using the .x format to export a model from Blender, I can load a mesh, armature and animation. I have no problems generating the mesh and viewing models in game. Additionally, I have animations and the armature properly loaded into appropriate data structures.

My problem is properly applying the animation to the models. I have the framework for applying the models and the code for selecting animations and stepping through frames.

From what I understand, the AnimationKeys inside the AnimationSet supplies the transformations to transform the bind pose to the pose in the animated frame. As small example:

Animation {
  {Armature_001_Bone}
  AnimationKey {
    2; //Position
    121; //number of frames
    0;3;     0.000000, 0.000000, 0.000000;;,
    1;3;     0.000000, 0.000000, 0.005524;;,
    2;3;     0.000000, 0.000000, 0.022217;;,
    ...
  }
  AnimationKey {
    0; //Quaternion Rotation
    121;
    0;4;   -0.707107, 0.707107, 0.000000, 0.000000;;,
    1;4;   -0.697332, 0.697332, 0.015710, 0.015710;;,
    2;4;   -0.684805, 0.684805, 0.035442, 0.035442;;,
    ...
  }
  AnimationKey {
    1; //Scale
    121;
    0;3;     1.000000, 1.000000, 1.000000;;,
    1;3;     1.000000, 1.000000, 1.000000;;,
    2;3;     1.000000, 1.000000, 1.000000;;,
    ...
  }
}

So, to apply frame 2, I would take the position, rotation and scale from frame 2, create a transformation matrix (call it Transform_A) from them and apply that matrix the vertices controlled by Armature_001_Bone at their weights. So I'd stuff TransformA into my shader and transform the vertex. Something like:

vertexPos = vertexPos * bones[ int(bfs_BoneIndices.x) ] * bfs_BoneWeights.x;

Where bfs_BoneIndices and bfs_BoneWeights are values specific to the current vertex.

When loading in the mesh vertices, I transform them by the rootTransform and the meshTransform. This ensures they're oriented and scaled correctly for viewing the bind pose.

The problem is when I create that transformation matrix (using the position, rotation and scale from the animation), it doesn't properly transform the vertex. There's likely more to it than just using the animation data. I also tried applying the bone transform hierarchies, still no dice. Basically I end up with some twisted models. It should also be noted that I'm working in openGL, so any matrix transposes that might need to be applied should be considered.

What data do I need and how do I combine it for applying .x animations to models?

I've made some mock ups of what this looks like, in case that's useful.

First I wanted to just test the translation, this is a bobbing head, what it looks like in Blender:

http://i.stack.imgur.com/NAc4B.gif

And what it looks like in game (don't mind the colors):

http://i.stack.imgur.com/nj2du.gif

Then for just rotation, the animation was the head rotating 360 degrees around the vertical axis. This is what that looks like in game:

http://i.stack.imgur.com/gVyUW.gif

Note, there should be no tilt, only rotation like a merry-go-round.

Update

I have the translation part of the animation working. But it feels kind of hacky and I don't see how to apply it to the rotation.

The translation works by taking these steps:

Take the position from the animation frame and swap the y and z values
Translate the transformation matrix by the altered position
Transpose the transformation matrix
Apply the transformation matrix to the vertices

So that's how it can work, but how is it supposed to work generally for position, scale and rotation?


texts: D3D9CAPS gives unusual maximum shader instructions value

texts:
I'm trying to implement a vertex and pixel shader on a piece of hardware we're developing a game for which uses the DirectX 9.0c runtime.  The shaders are for boned mesh animation and is a bit more complicated than the only other shader I have gotten working so far which is a simple 2d sprite shader.  The boned mesh shader seems to work fine when developing on my PC but doesn't work when I transfer it over to the target hardware.  This lead me to checking the hardware capabilities of both machines to check for any differences and I got the following unusual results:

Development machine Dx9 cap results:

Maximum primitive count: 16777215
Device supports level 3.0 vertex shaders
Vertex shader maximum number of instructions run when using flow control 65535
Vertex shader maximum number of constant buffers 256
Vertex shader maximum number of 30 instruction slots 4096
Vertex shader instruction predication supported
Vertex shader dynamic flow control depth 24
Vertex shader number of temporary registers 32
Vertex shader static flow control depth 4
Device supports level 3.0 pixel shaders
Pixel shader maximum number of instructions run when using flow control 65535
Pixel shader maximum value of arithmetic component 65504.000000
Pixel shader maximum number of instruction slots 4096
Pixel shader instruction predication supported
Pixel shader dynamic flow control depth 24
Pixel shader number of temporary registers 32
Pixel shader static flow control depth 4
Pixel shader number of instruction slots 512

Target machine Dx9 cap results:

Maximum primitive count: 5592405
Device supports level 3.0 vertex shaders
Vertex shader maximum number of instructions run when using flow control -1
Vertex shader maximum number of constant buffers 256
Vertex shader maximum number of 30 instruction slots 32768
Vertex shader instruction predication supported
Vertex shader dynamic flow control depth 24
Vertex shader number of temporary registers 32
Vertex shader static flow control depth 4
Device supports level 3.0 pixel shaders
Pixel shader maximum number of instructions run when using flow control -1
Pixel shader maximum value of arithmetic component 340282346638528860000000000000000000000.000000
Pixel shader maximum number of instruction slots 32768
Pixel shader instruction predication supported
Pixel shader dynamic flow control depth 24
Pixel shader number of temporary registers 32
Pixel shader static flow control depth 4
Pixel shader number of instruction slots 512

What I found unusual was the maximum number of instructions during flow control was -1 for both the pixel and vertex shaders on the target machine.  Is it the case that the target hardware can only support shaders with no flow control?  i.e. no for loops, if conditions etc.

The only reason I ask is because the simple shader, with no flow control, works fine but the more complicated boned mesh shader, with for loops and if conditions, isn't working.  It just seemed like too much of a coincidence that the only major difference between the two caps seems to be the flow control based one or am I barking up the wrong tree?

In case this helps I've linked the two shaders I've written just in case there's any obvious errors in there:

2D Sprite shader:
https://pastebin.com/0G9swKu6

3D Boned Mesh shader:
https://pastebin.com/Ayd0bXWU

Any input/ideas would be greatly appreciated.


texts:
I have a 2d int array which represents tiles on level like this:

0000000000000000000000
0000000000000000000000
0000000000000000000000
1111111111111111111111

I have a tileset vector, where each element has it's own tileX and tileY value(position of a tile in a tileset image), collision data etc. So, when I draw a level each time I draw a tile, I ask about them like this:

draw(tileset[currentTile]->tx, tileset[currentTile]->tY, tileWidth, tileHeight);

But, as you can see, there will be lots of the same elements when I iterate through for loop, so do I need to keep lastCollisionData variable in level class to reduce time used to access each tile separately?


texts: How to get faster iteration times in android development

texts:
I'm creating a game on the android platform that uses the resources/raw folder for assets and scripts. The problem is that every time I change something I have to rebuild the application to test the new variant. Of course this is bad for iteration times.

Any ideas about what I can do to avoid rebuilding every time I change something? This *.apk format is getting on my nerves now that I have to recreate it every time I change a word in my scripts.

Or at least how to make eclipse auto-rebuild every time I change something in my resources folder so that I don't have to go to Project->Build every time?


texts: Basic isometric projection in Javascript

texts:
I've been working on porting an old closed source game to Javascript with Canvas and I've come to a slight problem.

Right now, to display the land, I just have a pretty basic loop that just draws the 44px by 44px diamond-shaped tiles using ctx.drawImage().

It essentially looks like the left side of the image, while I need them to "stretch" to fill the entire tile (like on the right). The tiles have a Z axis which is just in the +j direction on the screen and it's supposed to look like a hill or incline.

Anyway, this leads to my question: Is there a way to correctly do this without using webgl? If not: would it be better to use webgl directly to do this, or use a library to handle it for me?

EDIT 2:
Well, after thinking for a while, I remembered that affine transformations are only linear (duh), so I won't be able to use certain transformations like transforming corner tiles... so I guess I can use the transformation matrices for the "light green" tiles, but not the pink tile in this example.

EDIT: With Phillips answer, I was able to create a few matrices to apply an affine transformation to the tile. However, I pretty much did "guess and check" to calculate the values for only one Z-value, but I can't seem to create a general form of it.

I'm guessing for different angles (like when there is an incline going from east->west, west->east, north->south, south->north), I will have to use a ton of if-statements for each scenario, but that's not much of a big deal.

I have the JSFiddle here: http://jsfiddle.net/awwPP/1/

<script>
window.onload = function(e) {
    multiply = function(a, b) {
        return [a[0]*b[0] + a[1]*b[2],
               a[0]*b[1] + a[1]*b[3],
               a[2]*b[0]+a[3]*b[2],
               a[2]*b[1]+a[3]*b[3]];
    };
    multiplyAll = function() {
        var result = arguments[0];
        for(var i = 1; i < arguments.length; i++) {
            result = multiply(result, arguments[i]);
        }
        return result;
    };
    drawDiamond = function(ctx, x, y) {
        ctx.beginPath();

        ctx.moveTo(x, y);
        ctx.lineTo(x+22, y+22);
        ctx.lineTo(x, y+44);
        ctx.lineTo(x-22, y+22);
        ctx.lineTo(x, y);
        ctx.stroke();
        ctx.fill();
    };

    var canvas = document.getElementById('c');
    var ctx = canvas.getContext('2d');
    var z = 2 * 3; // each z is like 2px up
    ctx.mozImageSmoothingEnabled = false;

    ctx.fillStyle = 'rgba(50, 50, 50, 0.5)';
    ctx.strokeStyle = 'rgba(255, 50, 50, 0.5)';

    //left:
    drawDiamond(ctx, 44, 22);
    drawDiamond(ctx, 66, 44);
    drawDiamond(ctx, 88, 66);

    var cos = Math.cos(Math.PI/4);
    var sin = Math.sin(Math.PI/4);

   // just negate
    var nCos = Math.cos(-Math.PI/4);
    var nSin = Math.sin(-Math.PI/4);

    var result = multiplyAll(
      //rotate it so the tile is a square:
      [cos, sin,
      -sin, cos],

      // scale the x axis (although it's actually the Y)
      // to make it look longer
      [50/44, 0,
      0, 1],
      // scew the opposite axis by factor K
      [1, -0.12,
      0, 1],

      //negate the rotation
      [nCos, nSin,
      -nSin, nCos]);

    ctx.setTransform(result[0], result[1],
                     result[2], result[3],
                //dunno why there is an x/y offset
                     0, 10);

    //middle:
    drawDiamond(ctx, 66, 0 - z);
    drawDiamond(ctx, 88, 22 - z);
    drawDiamond(ctx, 110, 44 - z);

    //right:
    ctx.setTransform(1, 0,
                         0, 1,
                         0, 0);
    drawDiamond(ctx, 88, -22 - z);
    drawDiamond(ctx, 110, 0 - z);
    drawDiamond(ctx, 132, 22 - z);
}
</script>

<canvas id="c" width="200" height="200"></canvas>


texts: keyPressed is not working after adding ActionListener to JButton

texts:
I have a serious problem while trying to build a menu for my game.
I've added two JButton to a main JPanel and added an ActionListener for each of them. The main JPanel also contains the game JPanel which have the keyPressed method inside keyController.

That's how it looks -

Main ->
      JPanel ->
        JButton, JButton,
        JPanel which contains the game and keyPressed function inside KeyController class which worked fine before I added the ActionListener for JButton.

For some reason after I added an ActionListener for each of the button, the game JPanel is not getting any keyPreseed events nor KeyRealesed.
Does anyone know the solution for my situation?
Thank you very much!

Main window -

  Scanner in = new Scanner(System.in);

    JFrame f = new JFrame("Square V.S Circles");
    f.setUndecorated(true);
    f.setResizable(false);
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    f.add(new JPanelHandler());
    f.pack();

    f.setVisible(true);
    f.setLocationRelativeTo(null);

JPanelHandler(main JPanel) -

  super.setFocusable(true);

        JButton mybutton = new JButton("Quit");
        JButton sayhi = new JButton("Say hi");

        sayhi.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            System.out.println("Hi");
        }
        });

         mybutton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e)
        {
           System.exit(0);
        }
        });
        add(mybutton);
        add(sayhi);
        add(new Board(2));

Board KeyController(The code inside is working so it's unnecessary to put it here) -

private class KeyController extends KeyAdapter {

    public KeyController()
    {
        ..Code
    }

    @Override
    public void keyPressed(KeyEvent e) {

    ...Code

    }

    @Override
    public void keyReleased(KeyEvent e){

     ...Code

    }

}


texts: How do I create a game design that can adapt to new platform environments?

texts:
I'm trying to design a game that can be considered versatile enough to be adapted to different platforms and control schemes without too much difficulty.  I asked this question to try to get a handle on what to expect as far as what technologies to try and plan for, but it was closed (justifiably, I agree) for basically asking others to predict what the future technologies were.

So my question now is, instead of trying to plan a game to suit specific technologies and control methods, what should I consider in my planning if i want to design a game that can easily adapt to new platform environments?


texts: AI movement is fragmented when following player

texts:
I'm making a 2D game with two spaceships flying around and shooting at each other. One is controlled by the player, the other by the AI.

Currently, I have the AI always try to get inside a certain radius from the player. When it is inside that radius, it stops moving. This works, but I have one problem with this. I'll present the problem after describing the implementation:

Each frame, the AI checks it's distance from the player. If the distance is larger than a certain number (the radius), the AI moves in the direction of the player.
If the distance is smaller or equal to that number (aka the AI's spaceship is inside the given radius from the player's ship), the AI stops moving.

This works fine, except for one problem:

When I stay in place and let the AI's ship reach the radius, it works. The AI moves in my direction, and stops the moment it got inside the radius. The movement is smooth.

The problem occurs when - after the AI had reached the radius and stopped - I start moving my ship. The AI senses that it's no longer inside the radius, and starts following me, but in a very fragmented fashion.

It moves for a few pixels in my direction, stops, then moves for a few pixels, than stops.

(These 'few pixels' are the 'moving step' both ships take while moving, every frame. The amount of pixels in each step is constant).

I figured out the reason for this problem:

When both ships are in place next to each other (aka the AI is inside the radius so it doesn't need to move), and then the player's ship starts moving, the AI senses right away that it is now outside of the radius. It moves immediately one step in the player's direction.

The next frame, the AI senses that it's once again inside the radius. So it stops.

But the player is in motion. So the frame after that, again the AI senses it's outside the radius, and moves.

This creates very fragmented motion. The AI moves a step, stops, moves another step, stops.

I know what causes this problem, but not how to fix it.

Any suggestions as to how to fix this problem? What could cause this in the design I described?

Thank you


texts:
I do realize there is no camera in OpenGL ES 2, but from my understanding you can simulate one using view and projection matrices. I'm using Android, by the way. Here's a video of the game, in case you are not familiar with it: https://www.youtube.com/watch?v=5mDjFdetU28

I am trying to understand how the world/camera is rotated and tilted. Is that done purely by rotating and tilting the view matrix? So you'd have a tilt and rotationSpeed fields that you'd use each frame in something like rotate(viewMatrix, angle + rotationSpeed) followed by rotate(viewMatrix, tilt)? How would you achieve a similar effect?


texts: Node representations in a navigation mesh

texts:
There are different ways to represent nodes in a navigation mesh. It's either along triangle centroid, along triangle vertices or along edge midpoints.

As I understand if you choose triangle centroid or edge midpoints as nodes, the path isn't going to be optimal, but you can use a funnel algorithm to optimize it.

If you choose triangle vertices as nodes however, I understand you can find the more optimal path from get-go. But you will get a "wall hugging" issue. Which you can solve by using some algorithm I unfortunately forgot the name of.

What is the preferred or most optimal option?


texts: How can I scale object on one side only with a speed factor?

texts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScaleOneSide : MonoBehaviour
{
    public float speed = 1;

    float mfX;
    float mfY;
    // Use this for initialization
    void Start()
    {
        mfX = transform.position.x - transform.localScale.x / 2.0f;
        mfY = transform.position.y - transform.localScale.y / 2.0f;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            Vector3 v3Scale = transform.localScale;
            //transform.localScale = new Vector3(v3Scale.x + 0.1f, v3Scale.y + 0.1f, v3Scale.z);
            //transform.position = new Vector3(mfX + transform.localScale.x / 2.0f, mfY + transform.localScale.y / 2.0f, 0);

            //transform.localScale = new Vector3(v3Scale.x + 0.1f, v3Scale.y, v3Scale.z);
            transform.position = new Vector3(mfX + transform.localScale.x / 2.0f, 0, 0);

            transform.localScale = Vector3.Lerp(transform.localScale, new Vector3(v3Scale.x + 0.1f,0,0), speed * Time.deltaTime);
        }
    }
}

When using only this two lines it was working fine without changing the speed:

 //transform.localScale = new Vector3(v3Scale.x + 0.1f, v3Scale.y + 0.1f, v3Scale.z);
   //transform.position = new Vector3(mfX + transform.localScale.x / 2.0f, mfY + transform.localScale.y / 2.0f, 0);

But now I'm trying to add to the scaling a speed.
I want when I press the mouse left button it will scale the object according to the speed.


texts:
I'm making a c++ multiplayer game, and I'm trying to implement a server list, where everyone can host his own server. But I don't know how to start, I've google'd for a while and I didn't find anything about this. I tried to search for a master server specially designed to handle with the server list, so if I refresh it, it will ask the master how many servers it has, and tell the client the servers' informations, and I don't have any idea on how I could make it.

Could you just show me an example, or tell me how could I begin?

Any help is really appreciated.


texts: Shadow artifacts/acne on block intersections

texts:
This is using the default shader and depth shader from LibGdx. It creates lines at the blocks intersections.

This is what I use to create the blocks models for now:

private Model createModel(Color color) {
    Model model = modelBuilder.createBox(
            cellSize, cellSize, cellSize,
            new Material(ColorAttribute.createDiffuse(color)),
            Usage.Position | Usage.Normal);
    return model;
}
...
for(int x = 0; x < data.models.length; x++) {
    for(int y = 0; y < data.models[x].length; y++) {
        int z = data.getElevation(x, y);
        ModelInstance instance = new ModelInstance(model);
        instance.transform.setTranslation(new Vector3(cellSize * x + cellSize/2, cellSize * y + cellSize/2, z * cellSize - cellSize/2));
        getWorld().addToCache(instance);
    }
}

This sets the environment lights:

getEnvironment().set(new ColorAttribute(ColorAttribute.AmbientLight, getAmbiantBrightness(), getAmbiantBrightness(), getAmbiantBrightness() , 1f));
getEnvironment().set(new ColorAttribute(ColorAttribute.Specular, getAmbiantBrightness(), getAmbiantBrightness(), getAmbiantBrightness() , 1f));
getEnvironment().add((shadowLight = new DirectionalShadowLight(1024*4, 1024*4, 600f, 600f, 0.1f, 100f)).set(db, db, db, dx, dy, dz));
getEnvironment().shadowMap = shadowLight;

This is how I render:

@Override
public void render(float delta) {
    getWorld().buildCache();
    clearScreen();
    renderShadows(delta);
    controls.update(delta);
    renderWorld(delta);
    renderHud(delta);
}
public void clearScreen() {
    Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    Gdx.gl.glClearColor(getBGColor().r, getBGColor().g, getBGColor().b, getBGColor().a);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
}

protected void renderShadows(float delta) {
    shadowLight.begin(Vector3.Zero, getCam().direction);
    shadowBatch.begin(shadowLight.getCamera());
    shadowBatch.render(world.cache, env);
    getWorld().tempModels.forEach(m -> shadowBatch.render(m, env));
    shadowBatch.end();
    shadowLight.end();
}

protected void renderWorld(float delta) {
    getBatch().begin(getCam());
    // render the cached models
    getBatch().render(getWorld().cache, getEnvironment());
    // render the temp models
    getWorld().tempModels.forEach(m -> getBatch().render(m, getEnvironment()));
    getBatch().end();
}

I tried to copy the default fragment and vertex shader and edit the PCFoffset with random values, but the result wasn't better.

float getShadow()
{

    float pcfOffset = 0.0f;
    return (//getShadowness(vec2(0,0)) +
            getShadowness(vec2(pcfOffset, pcfOffset)) +
            getShadowness(vec2(-pcfOffset, pcfOffset)) +
            getShadowness(vec2(pcfOffset, -pcfOffset)) +
            getShadowness(vec2(-pcfOffset, -pcfOffset))) * 0.25;
}

Should I code the lights/shadows myself using Lwjgl instead of using LibGdx defaults? Seems like a lot of work for something I expected to be included.


texts: How to Render to Texture using DirectXTex

texts:
I can display a textured quad by using D3D11 & DirectXTex's ScratchImage and CreateShaderResourceView. How would I be able to render this texture to another one similarly created? I know that I need to create a RenderTargetView and use Map somehow but I don't know how it all fits together I'm quite mixed up. I have studied Braynzarsoft's Tutorial 34 How to Render to Texture but I couldn't congeal the information into a logical form of understanding. Plus the registration doesn't work and can't download the source code. Finally should I actually just use DirectXTeX::CopyRectangle or is it too slow? In good faith here is how I create the texture:

m_spTexture.reset(new ScratchImage);

WCHAR wcExt[_MAX_EXT];
_wsplitpath_s(wsFilename.c_str(), nullptr, 0, nullptr, 0, nullptr, 0, wcExt, _MAX_EXT);

HRESULT hr;
if ( _wcsicmp(wcExt, L".dds") == 0)
{
    hr = LoadFromDDSFile(wsFilename.c_str(), DDS_FLAGS_NONE, &m_stInfo, *m_spTexture);
}
else if (_wcsicmp(wcExt, L".tga") == 0)
{
    hr = LoadFromTGAFile(wsFilename.c_str(), &m_stInfo, *m_spTexture);
}
else
{
    hr = LoadFromWICFile(wsFilename.c_str(), WIC_FLAGS_NONE, &m_stInfo, *m_spTexture);
}

if (SUCCEEDED(hr))
{
    hr = CreateShaderResourceView(g_pEngine->GetD3DObj()->m_spD3DDevice.Get(),
                                  m_spTexture->GetImages(),
                                  m_spTexture->GetImageCount(),
                                  m_stInfo,
                                  m_spSRV.GetAddressOf() );
    if (FAILED(hr))
        return hr;
}

return hr;

I look forward to and appreciate your thoughts.


texts:
I have a button for my game which has a MovieClip in it. It consists of an image of a lock and an image of an item, representing the item being locked and unlocked. I make the button become slightly smaller when the mouse is over it to create the effect of a button slightly down.

For some reason, however, this makes the MovieClip in the button go to the next frame. I have no Actionscript code in the button or any frame except stop() on the first frame of the MovieClip, so I really don't understand why this would happen. It only goes to the next frame when I hover my mouse over the button and then quickly goes back to the first frame (since there's no stop() in the second frame).

After experimenting with stop() in both frames of the movie clip, it does indeed only happen when my mouse enters the button. Leaving the button doesn't do anything and the button left alone doesn't do anything. It just changes the frame when I hover my cursor over it. There's absolutely no script involved aside from stop() in the first frame of the movie clip in the button. What could be the cause of this problem?


texts: How to open .xml files in Cryengine 5.6.2?

texts:
I am new at this engine and I am trying to understad its stuff before developing a game(I have good prior experience with unity and UE4) and this got me lots of headaches trying to understand it. My main problem is opening a .xml file, first of all I created a new project using third person shooter template and I started to study C# code and how character was animated using .xml files.

I know that cryengine V uses a thing called flow graph that makes the logic of an object by displaying a graph reading xml text.

What I have tried:

Clicking 1000 billion times the .xml file.

Trying to open it by importing into the flow chart thing.

How do I open this .xml file in a flow graph? There is poor documentation about this in docs.cryengine and makes hard for us to understand the logic.


texts: How to free up TEXCOORD slots for Unity's Universal Render Pipeline?

texts:
I am writing custom a custom shader for Unity's Universal Render Pipeline (Version 7.3.1). The meshes are built using three separate UVMaps for different portions of the mesh. The reason I actually need all three to be separate is because two of them are scaled & offset independently by a C# script, kind of like texture atlas. I need the front and back of a sphere to be independently textured using this.
I followed this tutorial from CyanGameDev to get an understanding of the new syntax for URP as I had previously done this with the Built-In RP. The older version still used the Vertex & Fragment functions to draw it, but it was unlit so I was free to use as many TEXCOORDs as I needed.
Now as I followed this tutorial, I found that I needed all 8 available TEXCOORDs immediately just to get it functioning:
struct Varyings // AKA v2f, or OUTPUT from Vertex function to Fragment function
        {

            float4 positionCS                    : SV_POSITION; // Position in ClipSpace AKA screen space
            float4 color                         : COLOR;

            float2 uv                               : TEXCOORD0;
            DECLARE_LIGHTMAP_OR_SH(lightmapUV, vertexSH, 1); // the 3rd argument is the TEXCOORD index

        #ifdef REQUIRES_WORLD_SPACE_POS_INTERPOLATOR
                float3 positionWS               : TEXCOORD2;
        #endif
                float3 normalWS                 : TEXCOORD3; // Normal in WorldSpace as defined in Vert function
        #ifdef _NORMALMAP
                float4 tangentWS                : TEXCOORD4; // Tangent in WorldSpace as defined in Vert Function
        #endif
                float3 viewDirWS                : TEXCOORD5;

                // Convert to half3 for just vertex lighting, free up a TEXCOORD?
                half4 fogFactorAndVertexLight   : TEXCOORD6; // x: fogFactor, yzw: vertex light

        #ifdef REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR
                float4 shadowCoord              : TEXCOORD7;
        #endif
        };

Is there anyway I can remove some of these and still get PBR-ish result? For instance, I don't necessarily need the fog on this object. As well, I do not really want to perform this in Shader Graph if I can avoid it.
One thought I am having is to declare the uv as a float4 and just swizzle the texcoord like uv.xy for UV1 and uv.zw for UV2 but my understanding is the texturing and offset is stored within the Z & W vectors which is why you used to define a _MainTex_ST float4.
EDIT:
The specific effect is this:
The background is one texture (not a solid color, or i'd do this differently)

And the Foreground is another texture (Alpha channel symbols)

Through the script, you control which background section or foreground symbol you want by changing the tiling of the texture. The idea is that you can have many different combinations of the two textures. The back of the sphere will always have just the background color. The script is such that the amount of tiles on a texture does not have to be square, and the foreground and background textures do not need the same amount of tiles (its calculated at start). At any given time, only one of the tiles is shown on the sphere, mapped to both sides.
The final look is explained in a previous question of mine
The final look is explained in a previous question of mine


texts: What is the recommended library for using Lua from C++?

texts:
I am currently planning how to integrate Lua scripting in my 2D Game Engine, and i would like to go straight to the most adequate solution for having C++ classes and objects exposed.

I've read this (if it helps you help): http://lua-users.org/wiki/BindingCodeToLua

If you have a better scripting language to recomend, go for it ;D

All help is welcome, i need to pickup the best solution to start implementing
Thanks


texts: Maya Rigging - Shoulder joint attached to head?

texts: I'm fairly new to modeling and rigging in Maya; so my question is: in the image below how can I unbind the rigs head from the shoulder pivot? I've searched online for why this occurs and I can only guess that it's due to bad Joint placement?


texts: Are any scripting languages designed to be reloaded at runtime?

texts:
I'm currently working on my first game engine. So far, I have a cross-platform rendering framework and support for numerous file types, but game development is still a hard slog when I'm having to wait for resources to reload and then follow the game flow to the point I need to test.

Ideally, I'd like to be able to develop the game while it's running, through a scripting language that could be reloaded at runtime without compromising the game's state.

However, my biggest problem with this plan has been with pointers-to-functions appearing in the state. Whenever a script gets reloaded, these pointers either point to an old copy of the bytecode, or worse, if the old bytecode gets garbage-collected, they end up dangling!

I've found this in two of the most common (and appealing) scripting languages - Python and Lua, and I know that Javascript is similarly capable of this same issue. All the cases I've tested have been JIT-compiled - I've thought about running interpreted-only, but I've been worried about the performance hit. I've also considered trying a stateless language, but I like object-oriented syntax, especially if my game actors in the script are going to mirror entities in the renderer.

So my question is, is there any scripting language that gives me the best of all worlds? A scripting language with OO syntax that's designed to be reloaded at runtime, or at least limits the ability for pointers-to-code to get stored in the runtime state?

Right now, my best option looks like taking a batteries-not-included scripting engine, like TinyPy, and modifying it myself!!!

EDIT:

In one last vain appeal, I'm going to try a slightly different question...

Does anyone know of any scripting languages that DON'T treat functions as first-class objects???


texts: Why would a borderless full-screen window stutter occasionally?

texts:
I want to be able to allow players to switch between full-screen, windowed, and full-screen-with-a-borderless-window rendering modes. The last mode, borderless is an important one lots of players, myself included.

I have noticed that my game will stutter a little bit in borderless windowed mode. It's not terrible, but choppy gameplay can get slightly annoying and I want to it to be as smooth as it is in full-screen. I know other games have always had some issue with being borderless. I just figured since my game isn't that intensive I shouldn't see much of problem.

I am using David Amador's "XNA 2D Independent Resolution Rendering" code. The trouble comes when I create my gameplay screen and use the following code to create a borderless window:

Form gameForm = (Form)Form.FromHandle(curGame.control.Handle);
gameForm.FormBorderStyle = FormBorderStyle.None;

If I have it set to fullscreen through Amador's Resolution class then this borderless code doesn't seem to do anything at all. If I have it set to windowed it does work as expected and creates a borderless window. The only problem is that strange choppy behavior.

In full screen it doesn't lag one bit so I'm wondering if there's some issue with how the borderless code works. Is how I'm doing a borderless window correct? Am I just going to have to deal with a little bit of stuttering in that mode?


texts: How to create a line that is always connected to two Objects. (iPhone, Cocos2d)

texts:
I'm wanting to create a rope like animation effect. I don't need any kind of rope physics, all I need is a straight line connected to Object A and the other end connected to object B. Object A and B move relative to one another. So how do I make it so that the line is always attached to both Objects, even thought the distance between the objects decrease and increase?

The game is in 2D space.


texts: How to implement a never-rebooting test world?

texts:
Am looking for ideas on how to do the following: I want to write a simple "world" in Java. One which I could start and then add new objects later at a later date to simulate/observe different behaviours between existing objects. The plan is then to code up newer objects after watching the old ones for a while and then load/drop them into the existing world. The problem is that I don't want to ever stop or restart the world once it's started, I want it to run for a few weeks but I do need the ability to drop in objects and redo/rewrite/delete/create/mutate them over time without needing a reboot.
The world could be as simple as a 100 x 100 array of X/Y locations, with a possible tiled-map GUI to visually represent the world. I know I need some kind of ticktimer process to monitor objects and give each one a 'chance to act' (if they wanted to? (and if it was their turn to act?)).

Example:
I code up World.java on Monday and leave it running.
Then on Tuesday I write a new class called Rock.java (that doesn't move). I then load/drop it (somehow?) into this already running world (which just drops it someplace random in the world array and never moves).
Then on Wednesday I create a new class called Cat.java and drop that into the world, again placed randomly, but this new object can move around the world (over some unit of time), then on Thursday i write a class called Dog.java which also moves around but can 'act' on another object if it's in the neighbour location and vice versa.

Here's the thing. I don't know what kinda of structure/design I would need to code the actual world class to know how to detect/load/track future (and currently non-existing) objects.

Any ideas on how you would do something like this using Java?


texts: Level loading with threads runs sometimes and doesn't run sometimes

texts:
I am trying to load a scene in the background while displaying a loading screen till the scene loads and then changing the scene to the loaded scene and I am using threads and ResourceLoader to do so. On my computer it runs sometimes and doesn't run other times. And, on android it never gets completed the loading screen comes up and then the game just hangs.
On pressing the play button:
func _on_play_pressed():
        $loading_screen.show()
        go_to_scene(level_to_load, true)

The gotoscene():
func go_to_scene(new_scene, loading):
    if (loading):
        loading_thread = Thread.new()
        loading_thread.start(self, 'prep_scene', ResourceLoader.load_interactive(new_scene), 2)

The prep_scene():
func prep_scene(interactive_ldr):
    while (true):
        var err = interactive_ldr.poll();
        if(err == ERR_FILE_EOF):
            call_deferred("_on_load_level_done");
            return interactive_ldr.get_resource();

The onloadleveldone():
func _on_load_level_done():
    var interactive_ldr = loading_thread.wait_to_finish()
    print('thread', loading_thread.is_active())
    if get_tree().change_scene_to(interactive_ldr) != OK:
        print('error')


texts: Detecting on which side did the objects collided unity 2d

texts:
I have a ball and a rectangle in my game.

The rectangle has a box collider 2d attached to it. How can I calculate or check when the ball hits the top of my collider, when it hits the bottom, left and right, so basically any side of the collider and also a corner of the collider, I have searched over the internet and not one answer that I found helped me into solving my problem. If anyone can help I would appreciate it.


texts: Looking for games in environments similar to a pinball table

texts:
I'm on a team of students working on a third-person adventure game that takes place inside a pinball machine (like, small scale, on the surface, avoiding pinballs, etc).

One of my responsibilities on the project is to find games that are similar to this concept in appearance and/or gameplay for reference.

So, does anyone know of games (other than pinball) that takes place in a pinball-like environment?  Or, adventure games that take place in small, cramped environments with multiple paths around the world?  Or games in which the player is often bombarded with balls (or other similar unintelligent obstacles)?  Or games that take place on a small scale?


texts: Quite conflicted on advice given to "learn programming" for game development

texts:
I have been reading a few sources online that talk about learning programming with the end goal of game development in mind. I have heard many people saying that starting with Unity is the best way to go but others stating that C++ is what you need to get started with in order to be a game developer.

But as far as I'm concerned, this leaves me in quite a dilemma. Am I right in thinking that if I'm not overly fussed about making little indie games at the moment and just want to get stuck in with learning how to program, is C++ the right choice?

I have begun my journey with C++ and I am really enjoying it. I think it is the time further down the line that I am confused about. I am quite unsure on where to turn and what direction to go down to try and do this game development thing.

My end goal isn't necessarily working on an indie game project, I'd much rather aim to work at a gaming company which in my mind is a bit more realistic.

Thank you in advance.


texts: How come the 3d graphics and animations of MMORPGs are usually worse than non-online 3d games?

texts:
I have noticed that in general it seems like the 3d graphics and animations for MMOs and MMORPGs seem not as seductive and polished as the graphics for normal, non-online 3d games.

How come this is the case?

or
Is my judgement inaccurate?

If my judgement is inaccurate please provide examples of MMORPGs that render 3d graphics and animations that are superior to normal, non-online 3d games.


texts:
I'm diving into the world of SDL2 and C++ and have a few questions after my first few weeks in. Seems like a lot of the tutorials are (from what I understand) limiting the frames per second with a formula that uses the SDL_GetTicks() function to calculate current and last ticks and setting it back, as to limit the frames per second. I could be wording that wrong. Anyways, I've learned about the SDL_RENDER_PRESENTVSYNC flag for SDL_CreateRenderer() and according to fraps it seems to be working quite nicely and locking my FPS at 60 (instaed of 2000+).

My question is, Is SDL_RENDER_PRESENTVSYNC enough to solve the issue or should I also be using that common formula I've been seeing in many tutorials with all the SDL_GetTicks() stuff? Are both methods doing something different that I'm not aware of? I thought they were both just setting/limiting the FPS.


texts: How to export MotionBuilder animations as 'Humanoid'?

texts:
The animations I export from MotionBuilder tend to be 'Generic'. When I try manually changing them to 'Humanoid' within Unity then they turn from *.anims into *.FBX's that seemingly don't work with my Humanoid characters.
Is there a setting in motionbuilder or something to make the animations export as Humanoid? Or what am I doing wrong?


texts: I'm making an game in libGDX and I have been noticing some image tearing when camera is moving. Note that it happens only when the game is maximized and the camera x position is less than screen width and camera y position is less than screen height. Here's a GIF showing what is the problem The color errors are not the problem here, it is the GIF fault


texts: 2D Camera doesn't work when I have split my code into DrawableComponents

texts:
I have the following camera written:

public class Camera
{
    public Vector2 Position;

    Viewport Viewport;

    public Matrix Transformation
    {
        get
        {
            return Matrix.CreateTranslation(new Vector3(-this.Position.X, -this.Position.Y, 0)) *

            Matrix.CreateRotationZ(0f) *
            Matrix.CreateScale(new Vector3(1f, 1f, 1)) *
            Matrix.CreateTranslation(new Vector3(Viewport.Width * 0.5f, Viewport.Height * 0.5f, 0));
        }
    }

    public Camera(GraphicsDevice device)
    {
        this.Position = Vector2.Zero;

        this.Viewport = device.Viewport;
    }
}

Now while this does work in tutorials where you have all your drawing in the Game.Draw like this:

protected override void Draw(GameTime gameTime)
        {
            this.GraphicsDevice.Clear(Color.SkyBlue);

            this.SpriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, cam.Transformation);

            this.Player.Draw(this.SpriteBatch);
            this.World.Draw(this.SpriteBatch);
            this.Enemies.Draw(this.SpriteBatch);

            this.SpriteBatch.End();

            base.Draw(gameTime);
        }

It fails when you have your code organized in DrawableGameComponents (which I have).
Now, technically speaking I could add the Camera as a service in the game, retrieve it in the constructor of my DrawableGameComponents, add it as a field within the Component and then edit the spriteBatch.Begin() within the Draw of each component like it is shown above. So actually that it WOULD look like this:

public class TestComponent : DrawableGameComponent
    {
        Camera Camera;

        SpriteBatch Batch;

        public TestComponent(Game game)
            : base(game)
        {
            this.Camera = (Camera)this.Game.Services.GetService(typeof(Camera));
            this.Batch = (SpriteBatch)this.Game.Services.GetService(typeof(SpriteBatch));
        }

        public override void Draw(GameTime gameTime)
        {
            this.Batch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, this.Camera.Transformation);

            // draw the component

            this.Batch.End();

            base.Draw(gameTime);
        }
    }

But as you might already have guessed this is a bad idea because it's basically redundant.

Is there a way I can maintain this at a central location?