texts: Help understanding radar sweep effect in shader code

texts:
Several days ago I asked about this question: How to construct a propeller clock in Unity? But I don't understand how the answer works.
I have 0 knowledge about shaders, so I picked up a tutorial to understand the math functions, but that still didn't helping much in understanding the code.
I cut off part of the code to check the effect on an image, and I want to understand why the code has this effect.

What is the range of values for the parameters i.uv.y or i.uv.x?

Next I discarded part of the code, simplifying the fragment shader to just:
fixed4 frag (v2f i) : SV_Target
{
    // Simulate the strip of LEDs spinning around very fast.
    float headAngle = _Time.y ;

    // Compute the angle of the pixel we're rendering.
    float angle = atan2(i.uv.y, i.uv.x);

    float difference = frac( angle / (2.0f * 3.141592653589f));

    return difference;
}

And I rendered this on a plane:

According to the documentation, atan2 gives an angle value in between -pi and pi. So the range of angle / (2.0f * 3.141592653589f)) is in between -0.5 and 0.5.
I tested with frac(0.3), frac(0.25), which is the same as return 0.3 or return 0.25 since frac preserves only the decimal number. But why I couldn't generate the same gradient image as the one above? Instead, the plane is all one shade of grey, no matter what number I use.

Next I tried the code float difference = frac(headAngle) and got an image which is constantly varying between dark and bright images like these:

Putting this together:

From the 1st picture, I have an image with a gradient that's dark in the 1st quadrant and bright in the 4th quadrant.

From the 2nd & 3rd pictures, I have all four quadrants at the same brightness, constantly varying between them.

What I don't understand is how the sum of these two pieces of code works. If I combine them like this:
float difference = frac(headAngle + angle / (2.0f * 3.141592653589f));

Shouldn't I get a gradient that stays in one place, like the 1st image, but just changes in brightness like in images 2 & 3?
Instead I get a A brightness gradient that is sweeping in a circle around the plane:

...and I don't understand why.


texts: How to create a reasonably sized urban area manually but efficiently

texts:
I have a game concept that only really works in an urban area that is of reasonable scale and diversity. In terms of what it should look like, think GTA, in terms of the size think more like a small neighbourhood with residents and a few local shops, perhaps a supermarket.

I'm mostly experienced in programming and not at all with modelling, texturing or drawing, but I've found that SketchUp allows me to design interesting looking buildings that I model after real world buildings in my own neighbourhood.

Designing these buildings and other objects can take from a few tens of minutes to a few hours. My question is: what is the best approach for a one man army like me who does manage to model buildings to create an interesting city environment in a reasonable amount of time? My game will not be based on procedural generation, the environment will actually be modelled like GTA cities.


texts: How do I find at least the closest penetrating point with SAT?

texts: For more accurate simulations, I want to find the closest point of another polygon to one polygon's center when they collide. Is this possible with the SAT algorithm? Is it a good strategy at all for semi-accurate physics simulations (more accurate than the normal between the 2 polygons' centers)?


texts:
I am trying to create a simple 3D game but things aren't working out as they should. For instance, the mode will not display. I created a class that does the rendering so I think that is where the problem lies.

P.S I am using models from the MSDN website so I know the models are compatible with XNA.

Code:

    class ModelRenderer
    {
        private float aspectratio;
        private Model model;
        private Vector3 camerapos;
        private Vector3 modelpos;
        private Matrix rotationy;
        float radiansy = 0;
        public ModelRenderer(Model m, float AspectRatio, Vector3 initial_pos, Vector3 initialcamerapos)
        {
            model = m;
            if (model.Meshes.Count == 0)
            {
                throw new Exception("Invalid model because it contains zero meshes!");
            }
            modelpos = initial_pos;
            camerapos = initialcamerapos;
            aspectratio = AspectRatio;
            return;
        }
        public Vector3 CameraPosition
        {
            set
            {
                camerapos = value;
            }
            get
            {
                return camerapos;
            }

        }
        public Vector3 ModelPosition
        {
            set
            {
                modelpos = value;
            }
            get
            {
                return modelpos;
            }
        }
        public void RotateY(float radians)
        {
            radiansy += radians;
            rotationy = Matrix.CreateRotationY(radiansy);
        }

        public float AspectRatio
        {
            set
            {
                aspectratio = value;
            }
            get
            {
                return aspectratio;
            }
        }
        public void Draw()
        {

            Matrix world = Matrix.CreateTranslation(modelpos) * rotationy;
            Matrix view = Matrix.CreateLookAt(this.CameraPosition, this.ModelPosition, Vector3.Up);
            Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), this.AspectRatio, 1.0f, 10000f);
            model.Draw(world, view, projection);
        }
    }

If you need more code just make a comment.


texts: What is causing my default libraries to conflict with OpenGL extensions?

texts:
So I'm currently following the tutorial for creating OpenGL programs on learnopengl.com,so I'm using GLFW, GLEW and the base library for OpenGL. However, when I go to build my code, I get a warning about how some of my default libraries "conflict with use of other libs; use /NODEFAULTLIB:library". So I went and disabled the appropriate defaults, and I get even more errors.

I'm trying to figure out, what other reason would there be that this error might be caused? From what I can tell, GLFW and GLEW should not experience this warning in the first place. I wouldn't have been too upset, since it compiles properly, however, when I add a third library in (one called soil, for adding images as textures), I get errors straight off the bat.

The libraries I used were from the official websites:

www.glfw.org/download.html (windows 32 bit binaries)

sourceforge.net/projects/glew/files/glew/1.13.0/ (the win32 .zip file)

I've seen people asking about this particular warning before, but the methods given to fixing it don't seem to apply to me :L

Edit: Here's the list of errors


texts: In Unity, Meta Files are Tracked but Behaviours Fall Off

texts:
My team is working on a Unity game, and we are using a mercurial repository on BitBucket. Whenever we update, all of the behaviours 'fall off' of state machines, behaviours, etc. When searching for a solution, I discovered that this information was stored in the meta files. I had previously ignored the meta files, but the are now being tracked. However, the files still 'fall off'. I cannot find any other reason this would be happening.

Any assistance you can give me would be appriciated. Let me know if you need any additional details.


texts: Do I lose/gain performance for discarding pixels even if I don't use depth testing?

texts: When I first searched for discard instruction, I've found experts saying using discard will result in performance drain. They said discarding pixels will break GPU's ability to use zBuffer properly because GPU have to first run Fragment shader for both objects to check if the one nearer to camera is discarded or not. For a 2D game I'm currently working on, I've disabled both depth-test and depth-write. I'm drawing all objects sorted by their depth and that's all, no need for GPU to do fancy things. now I'm wondering is it still bad if I discard pixels in my fragment shader?


texts:
I have a game where my code is designed to be on a single scene so I've implemented a singleton like that:

public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static bool _applicationIsQuitting;
private static readonly object Locker = new object ();
protected static T Instance;

public static T GetInstance {
    get {
        if (_applicationIsQuitting) {
            return null;
        }

        lock (Locker) {
            if (Instance == null) {
                Instance = (T)FindObjectOfType (typeof(T));

                if (FindObjectsOfType (typeof(T)).Length > 1) {
                    Debug.LogWarning ("More than one Singleton of type : " + typeof(T));
                    return Instance;
                }

                if (Instance == null) {
                    var singleton = new GameObject ();
                    Instance = singleton.AddComponent<T> ();
                    singleton.name = "(MonoSingleton) " + typeof(T);

                    DontDestroyOnLoad (singleton);

                    Debug.Log ("An instance of : " + typeof(T) + " is needed in the scene, so " + singleton +
                    " was create with DontDestroyOnLoad");

                    return Instance;
                }
                Debug.Log ("Using instance already created : " + Instance.gameObject.name);
                return Instance;
            }
            return Instance;
        }
    }
}

public void OnDestroy ()
{
    _applicationIsQuitting = true;
}

#region virtual methods

public virtual void Awake ()
{
        Debug.Log ("Awake".ColorMe (Color.green) + " instance of : " + typeof(T));
}
#endregion
}

But now with my game growing, I want to split it into mulitple scenes (easier to do now with Unity 5.3).

I mainly use singleton to manage UI. And for this i've a UI GameObject containing my script for current scenes. So on GameObject Awake it create a reference to my Scrit that i can call with script.GetInstance.

My problem is when i refresh a scene or i use a ui component that is already used in previous loaded scene my GetInstance return null. Is there any way to refresh instance reference in virtual Awake method ?

EDIT:

Obviously OnDestroy() set _applicationIsQuitting to true, so GetInstance return null. I've try to set it to false on Awake() but it doesn't change anything so I do that :

public static T SetInstance {
    set {
        Debug.Log (Prefix + ("Updating instance of : " + typeof(T)).ColorMe (Color.yellow));
        _applicationIsQuitting = false;
        Instance = value;
    }
}

and on each class when I awake i do the following :

public override void Awake ()
{
    base.Awake ();
    myScript.SetInstance = this;
}

I prefer to have separated getter and setter to provide myself mode readability.


texts: Entity system game design and input handler

texts:
I have started create a lightweight game engine with Ogre and C++. I have a abstract component class and an abstract entity class.

#ifndef ENTITY_HPP_
#define ENTITY_HPP_

#include <string>
#include <vector>

#include "Component.hpp"

class Entity
{
public:
    Entity(int uniqueId) { m_UniqueId = uniqueId; };
    ~Entity();

    void AddComponent(Component *comp);
    void RemoveComponent(Component *comp);

    Component *GetComponent(m_ComponentTypes type);

    int GetID() { return m_UniqueId; };
protected:
    std::vector<Component*> m_Components;
    int m_UniqueId;
};

#endif /* ENTITY_HPP_ */

Component:

/*
 * Component.hpp
 *
 *  Created on: Jul 15, 2013
 *      Author: dominik
 */

#ifndef COMPONENT_HPP_
#define COMPONENT_HPP_

#include <string>

class Entity;

typedef enum
{
    MESH_COMPONENT,
    POSITION_COMPONENT,
} m_ComponentTypes;

class Component
{
public:
    Component(m_ComponentTypes type) { m_Type = type; m_pParent = NULL; };
    virtual ~Component();

    void SetParent(Entity *entity) { m_pParent = entity; };
    Entity *GetParent() const { return m_pParent; };

    m_ComponentTypes GetType() const { return m_Type; };

protected:
    Entity *m_pParent;
    m_ComponentTypes m_Type;
};

#endif /* COMPONENT_HPP_ */

After this I created an EntityManager where I manage all entities in the game world, an a rendersystem where I render all entities and initialize Ogre. Now I have a window, but I need the escape button managed -> so I implement an inputsystem and here is the problem. My InputSystem works with OIS which needs a handle to the window, the handle to the window is available in the RenderSystem but not in the InputSystem, how can I get this data?

Here is my engine class:

/*
 * Engine.hpp
 *
 *  Created on: Jul 15, 2013
 *      Author: dominik
 */

#ifndef ENGINE_HPP_
#define ENGINE_HPP_

#include "EntityManager.hpp"
#include "RenderSystem.hpp"

#include <vector>

class Engine
{
public:
    static Engine *GetInstancePtr()
    {
        if (!instance)
            instance = new Engine();

        return instance;
    }

    EntityManager *m_pEntityManager;

    void update(double timeSinceLastFrame);
    void loop();

    void Shutdown() { m_bShutdown = true; };
private:
    static Engine *instance;

    Engine()
    {
        m_pEntityManager = new EntityManager();

        m_Systems.push_back(new RenderSystem());

        m_bShutdown = false;
    }
    Engine(const Engine&);

    ~Engine()
    {
        delete m_pEntityManager;

        while(!m_Systems.empty())
        {
            System *sys = m_Systems.back();
            delete sys;
            m_Systems.pop_back();
        }
    }

    std::vector<System*> m_Systems;

    bool m_bShutdown;
};

#endif /* CORE_HPP_ */

In my Engine singleton I have only the abstract system class, so I can't get the window handle. Is there a nice solution?

Any suggestions? Is my approach correct, or is it limitated in any way?

How should I implement the input manager, should he handle all the clicks on keyboard and mouse and send events, or should I create a component with the input manager fields and react on this in this entities which have this component added?


texts: Game laggy for everyone after second client joins with Unity mirror networking

texts:
I would like to ask a question about mirror networking in Unity. I’ve already programed almost a whole game, but I got stuck on unexpected issue. Everything works great (even multiplayer) unless there are more than two players present. At this point the game starts being extremely laggy for everyone.
I thought that it was happening due to my poor code optimization so I tried to disable all of these "features". It made absolutely no difference. I tracked down the problem until I disabled almost everything but the core functionality (movement). I’m using Opsive Ultimate character controller for movement so finding some "problems" in there is almost impossible! I would love to share the code with you, but since I disabled practically all of it, it does not make much sense at this point. Does anyone have similar experience with mirror networking asset?
My game has quite a big map so I set quality to the lowest possible, which resulted in no success either.


texts: Culling Techniques for 3d OpenGL ES game

texts: I'm developing a 3d flight simulator for Android and am using a relatively large (10k triangles) scene in 3ds format for the scenery. The scene is one polygon soup, not separated into separate objects. Frustum culling per triangle would be time consuming. What techniques could I use to render the triangles that are only visible in the view-port?


texts: How to decide sprite size for isometric tile textures?

texts:
When I draw these textures on screen, I put them in a sprite and specify a width and height to draw the sprites in like this:
new Sprite({
  width: 10,
  height: 10,
  texture: greenTileTexture
});

This draws the sprite at size 10x10 on screen. Let's say I want to have tile size of 10. I use this:
// This is the size of the textures as in png.
let textureWidth = greenTileTexture.width;
let textureHeight = greenTileTexture.height;
let textureRatio = textureWidth / textureHeight;

// This is the size that draws on screen.
let spriteWidth = 10;
let spriteHeight = 10 / textureRatio;

Now for the 3x2 tile I don't know what the width should be since it takes more tiles.
I want to draw isometric tiles with arbitrary tile sizes. For example above picture there are 1x1 and 3x2 sized tiles.
The textures have arbitrary height because of decoration. a is the tile's height b is texture's height c is tile's width.
I can't figure out what the sprite size should be when I lay these out on screen.
Maybe I should have exact tile sizes cover the whole texture without decorations (a == b). But still what the sprite size should be?


texts: How to make my components only contain raw data?

texts:
I'm reading that Components in ECS are just only data and have no logic. I'm trying to follow this and I got that working:

class Sprite : public Component
{
public:
    Sprite(const std::string &textureid = "");

    std::string getTextureId() const;
    void setTextureId(const std::string& textureid);

    void setColor(const Color& color);
    Color getColor() const;
private:
    std::string m_textureid;
    Color m_color;
};

Now in my SpriteRenderingSystem I have to create every frame for every Entity that has a Sprite component a SFML Sprite object (I'm using it right now), set the parameters of that object, render it and destroy it. I know it's not optimized and I don't like it.

I think that I can use my component to hold a pointer to the SFML::Sprite object and then I only have to render it every frame without having to create/set/render/destroy it as you can see there:

class Sprite : public Component
{
public:
    Sprite(const std::string &textureid = "");

    std::string getTextureId() const;
    void setTextureId(const std::string& textureid);

    void setColor(const Color& color);
    Color getColor() const;

private:
    friend class ::SpriteRenderSystem;
    std::shared_ptr<sf::Sprite> m_sfspr;
    std::string m_textureid;
};

Am I breaking the "only data in a component" rule here? If so, what other alternatives are there?


texts:
I am using this code below for a gradual fade into a scene/next level in Steam VR (HTC Vive)
The whole idea is to cover up the scene loading icon which is viewable for 3-4 seconds, and the default Steam landscape scene. The fade (to red) works fine…BUT it comes in after the loading icon so this defeats the whole purpose of it. Is there any simple way to fix this? thanks

public class NewFade : MonoBehaviour {

private float _fadeDuration = 4f;

private void Start()
{
    FadeFromWhite();
}

private void FadeFromWhite()
{
    //set start color
    SteamVR_Fade.View(Color.red, 0f);
    //set and start fade to
    SteamVR_Fade.View(Color.clear, _fadeDuration);
}

}


texts: How to deal with inconsitent game state in entity interpolation

texts:
I'm prototyping an online fast paced multiplayer game for educational purposes. I use a client-server model with the server being authoritative.

I've already implemented the client side prediction based and it works fine. Now i'm working on the entity interpolation, i'm using a simple algorithm:

interpolationTime = currentTime - INTERP_BACK_TIME //for my game 0.1s for INTERP_BACK_TIME
state1, state2 = getTwoInterpolationStates(interpolationTime) //get two states to interpolate between

length = state2.Time - state1.Time
t = 0.0

if (length > 0.0001) t = (interpolationTime - state1.Time) / length

entityPos = state.pos

entityPos.lerp(state2.pos, t)

This algorithm works fine if the server sends only correct states, which is not the case of my server, let me explain why:

The client sends what i call Actions to notify the server about what he is doing. For example, if the client press the right key, it will send a new action to the server, something like MoveAction(1, 0) to tell the server he is moving right. If the client keep pressing the right key for 5 seconds, the client will send only two actions, MoveAction(1, 0) at t = s and MoveAction(0, 0) at t = s + 5. I'm testing the whole thing with a ping of 150ms, so the server receive actions 150ms late.

Here is what happens on the server when the client presses the right key for 5 seconds (there is 150ms ping between client and server):

MoveAction(1, 0) is received at t = s (s is the time on the client)
The action starts being processed on the server (the player starts moving to the right until a new action is received)
MoveAction(0, 0) is received at t = s + 5
The server knows at this point that the action (MoveAction(1, 0)) has ended and lasted 5 seconds on the client (but on the server it lasted 5 seconds + 150ms since the MoveAction(0, 0) is received 150ms late)
The player then need to be snapped back to his correct position

The step 4 is actually the one causing me problems for the interpolation. Since the actions are received 150ms late, the player will keep moving right for 150ms on the server (after the action is completed on the client) before being snapped back to his correct position when the action finally arrives. My server sends game snapshots every 20ms so it will potentially sends 7 game snapshots with incorrect player positions.

How should i deal with this scenario? Should i avoid sending this kind of invalid states or should i handle them client side?


texts:
Example
I have an "Enemy" class, and 5 types of enemy subclasses.

These enemies will be spawn often, so I want to use an object pool.

However, this means I can no longer use an object pool for Enemies, now I have to use an object pool for each enemy subclass, so now, I have to make 5 object pools, and that's an arbitrary number that could just as easily be 25.

eg.

// Each with their own implementations of Enemy's "attack" or similar method
class Dragon extends Enemy { ... }
class Ogre extends Enemy { ... }

ObjectPool<Ogre> ogrePool;
ObjectPool<Dragon> dragonPool;
// etc ...

It seems a bit weird.

So what can I do?  If I take out the subclasses, I can either put all the functionallity of every subclass into the base class, and keep an id of the type of class this base class represents, calling the appropriate functions accordingly... But this leaves a bloated hard to maintain class that requires a lot of modification everytime I add or remove a subclass behaviour.

eg:

class Enemy {
    enum EnemyType {OGRE, DRAGON, ETC;}
    EnemyType enemyType;

    public Enemy(EnemyType type) { this.enemyType = type; }

    public void attack() {
        switch(enemyType) {
            case Ogre:
                //Do ogre attack
                break;
            // etc...
    }

    // ...

}

// Now I can instantiate things from 1 object pool

Alternately I could try and use composition.  I could have enemy contain components of other classes that govern behaviour.  For example, I could have something like an "WeaponBehaviour" and "ArmourBehaviour".  Then, the type of weapon behaviour, armour behavour, etc, would differentiate the different subclasses.  However, every time i obtain an inatnace of my enemy class, I would have to instantiate each behaviour, and would end up likely needing an object pool for each behaviour.

eg:

class Enemy {
    WeaponComponent weaponComponent;
    ArmourComponent armourComponent;

    public Enemy() {}

    public void init(WeaponComponent weapon, ArmourComponent armour) {
        weaponComponent = weapon;
        armourComponent = armour;
    }

   public void attack() {
       weaponComponent.attack();
   }

   // ...

}

// And then instantiate things like so:

ObjectPool<Enemy> enemyObjectPool;
Enemy enemy = enemyObjectPool.obtain();
enemy.initialize(new OgreWeapon(), new OgreArmour());
// or alternately have an object pool for OgreWeapons and OgreArmour

None of the solutions I can think of seem like they are ideal, and I was wondering what a good way to organize this was.


texts:
I'm using FTGL library to render fonts in my game, but I have completely no idea how to create an outline around text. Achieving a shadow could be easy, because I can simply do it like this:

(pseudo code)

font.render(Color::BLACK, position.x + 1, position.y + 1); // Shadow
font.render(Color::WHITE, position.x, position.y)          // Normal text

But how to create an outline? Unfortunately I haven't found any interesting solutions for it over internet which seemed to me a bit strange, because I thought it's quite popular problem.

Drawing outline with just a bigger font is not a right way, because as I found out, letters just don't match in this case:

So is there any simple way to create an outline for fonts? How do they do it in real games?

Thanks in advance for any answer


texts: Migrating from OpenGL to XNA (MonoGame)?

texts:
I just started working in MonoGame with 3D code.  I've used OpenGL before in the past, and I've also built engines with 2D Sprites/SpriteBatch's in MonoGame.

However, I'm getting extremely stumped with going from GL to XNA, likely due to the fact that I believe XNA is no longer a "state" machine like GL is.

I've looked thru the tutorials by RB Whitaker and Riemers -- but most of the stuff they have written covers models, etc.  I've already migrated some of my code to build procedural meshes into a VertexBuffer.  I'd like to test it now, but I'm getting very confused as to how to setup the World, View, Projection matrices, etc.

Are there any good tutorials that either show how to move from GL to XNA -- or optionally -- any good tutorials that assume you're not using Models, etc?  I'm looking to write something fairly low-level when it comes to primitives.


texts: Choppy edges with sub pixel movement MonoGame/XNA 4

texts:
When I move a texture slower that one pixel it moves using sub pixel movement inside but the edges jumps from pixel to pixel.

Video : https://www.youtube.com/watch?v=zcai1PUfzzA

Sorry for the low quality (Its hard to see), I'm using linear filtering. How do I fix it so everything moves smooth?

spriteBatch.Begin();
spriteBatch.Draw(texture, position, Color.White);
spriteBatch.End();


texts: How to specify colour in a single 32 bit value

texts:
I'm writing my first game using OpenGL 2 ES (for Android), and I've currently got a particle engine and some player sprites running successfully.  I'm using 4 floats for the colour of each particle which seems like total overkill.  It makes sense that I should be able to use a single 32 bit int (or perhaps a single float) to hold the colours (perhaps in RGBA format) which would presumably save a lot of unnecessary loading/copying/processing,  but I'm struggling to understand how I could do this.

I guess that I would need to change the shaders to take the relevant format, and also i'd need to change the way I load the color shader attribute.  My fragment shader has:

varying vec4 v_Color;
gl_FragColor = v_Color * texture2D(u_TextureUnit, gl_PointCoord);

and the attribute (passed into the fragment shader from the vertex shader) is set up with:

glVertexAttribPointer(aColourLocation, COLOUR_COMPONENT_COUNT, GL_FLOAT, false, BYTES_PER_VERTEX, floatBuffer);

I've searched the documentation for what I should change vec4 and GL_FLOAT to, and what/how I'd multiply the colour with the texture, and have tried a few things but with no success.


texts: Camera stacking for first-person view weapon in Universal Render Pipeline

texts:
I just added URP to my project then upgraded the materials to URP and now it's not rendering the environment anymore

I found the problem is that I have 2 cameras which are stacking on each other:  one with a priority of 1 and the other 0 . The camera that has higher priority is blocking the lower priority camera.
How can I fix that? I want to render the higher priority camera on top of the lower priority one.


texts:
I'm done implementing Moller's tri-tri intersection routine.  It gives you the location of where each triangle edge intersects the line of intersection between the 2 triangle planes:

Really you get the point location in the form of t values along the (really big) purple ray shown above.  So you can tell if the triangle intersects if the t values are overlapping..?

That's what the paper says.  But I can show you scenarios where the t values are overlapping, but the triangles don't intersect:

So I can't seem to figure out which edge value to discard.

The original paper is here: http://fileadmin.cs.lth.se/cs/Personal/Tomas_Akenine-Moller/pubs/tritri.pdf


texts: I am trying to make a game where the person can create their own character, but instead of using a character builder, i want the person to be able to draw their character. how do i code that in c# so that they only have to draw their character once, and the code can animate that character without the player having to do very much except draw their character on the screen?


texts:
I am having an issue i cannot seem to figure out within my code. What this code does at the moment is that it rotates the 3D Model around the z axis but i need it to rotate around the y axis. Any help would be greatly appreciated.

void Update ()
    {
        Vector3 moveVector = (Vector3.up * joystick.Horizontal + Vector3.left * joystick.Vertical);
        if (joystick.Horizontal != 0 || joystick.Vertical != 0)
        {
            transform.rotation = Quaternion.LookRotation(Vector3.forward, moveVector);
        }

    }


texts:
I am currently using the IEnumerator function to pause a for loop, in which a ball  should move towards another game object. From my print statements it seems like the ball moves a little, but it's actually never reaching the object and I'm not sure why. I have never used IEnumerator so I'm not sure if this is a part of the issue.

    public IEnumerator CoUpdate(){
    float waitTime = 8;

    yield return new WaitForSeconds (waitTime);

    for (int i = 0; i <= 19; i++) {
        //Finding Game Objects
        numbers = GameObject.FindGameObjectsWithTag ("num");
        ball = GameObject.FindGameObjectWithTag ("ball");
        float step = speed * Time.deltaTime * 2;

        //Picking the random cube
        index = Random.Range (0, numbers.Length);
        pickedNumber = numbers [index];

        print ("number picked");
        print (pickedNumber.name);

        print ("numer postion");
        print (pickedNumber.transform.position);

        //Moving ball to cube
        target = pickedNumber.transform;
        ball.transform.position = Vector3.MoveTowards(transform.position, target.position, step);

        //Checking balls position
        print ("ball Position");
        print (ball.transform.position);

        //Pause here
        print ("PAUSE!");
        yield return new WaitForSeconds (waitTime);

        //Ball Returns to position
        ball.transform.position = new Vector3 (0, 0, 0);
        print ("ball reset");
        print (ball.transform.position);
    }
}


texts:
I want to rotate my stick based on the movement of the touch on the screen. From my calculation I did not able to find correct angle in degree. So please provide guidance, my code snippet for that are below.

if (pSceneTouchEvent.isActionMove()) {
    pValueX = pSceneTouchEvent.getX();
    pValueY = CAMERA_HEIGHT - pSceneTouchEvent.getY();
    rotationAngle = (float) Math.atan2(pValueX, pValueY);
    stick.setRotation((float) MathUtils.radToDeg(rotationAngle));

}


texts: How can I make a good-looking explosion particle effect?

texts:
I'm not much of an artist, but I'm trying to make decent particle effects in a 2.5D game. I'm making a replica of Wii Play's "Tanks" and I can't quite get the explosions to look good. I'm not going for the exact style as they had, probably something more realistic, less childish.

My particle engine just draws a 2d texture on the screen, and supports, per particle: starting position, velocity, gravity (or any acceleration), air resistance (drag), color including alpha, starting size, size expansion rate, lifetime, and fade out rate.

In my tank explosions, I'm drawing around 100 particles, and I've been tweaking parameters for days trying to get things looking good. So I'm wondering, what are some tips for getting good results? What's most important, specifically for explosions?

Having good quality textures?
Having a variety of textures?
The right colors?
Realistic movement of the particles?
Having lots and lots of particles, many more than 100?

Check out this image. I tried to replicate it by making particles that shoot out and create more particles in their wake. But mine still isn't anything like that.


texts: How do I load/use substances with libgdx?

texts:
I've been looking at some substances (.sbsar file format) but I have no clue how to load or use these files. The links I find brings me to Unity & Unreal Engine, but if I search up anything related to libgdx or opengl, I can't get any results.
Does anyone know how I can use these textures in my libgdx java game?


texts:
I am trying to understand and implement AABB collision to learn simple 2D game physics. I'm following a tutorial and its method is a bit different to other websites. It uses the center of the object and its "half-size" to determine collision. This is its code:

public bool Overlaps(AABB other)
{
    if ( Mathf.Abs(center.x - other.center.x) > halfSize.x + other.halfSize.x ) return false;
    if ( Mathf.Abs(center.y - other.center.y) > halfSize.y + other.halfSize.y ) return false;
    return true;
}

And this is the seemingly more popular option:

if (rect1.x < rect2.x + rect2.width &&
   rect1.x + rect1.width > rect2.x &&
   rect1.y < rect2.y + rect2.height &&
   rect1.y + rect1.height > rect2.y) {
    // collision detected!
}

Which one is more efficient? And for the first option, would I define the center and half-size like this:

AABB = new AABB(new Vector2(Width / 2, Height / 2), new Vector2(Width / 2, Height / 2));

Center and half-size method source: https://gamedevelopment.tutsplus.com/tutorials/basic-2d-platformer-physics-part-1--cms-25799

Position and width/height source: https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection


texts: Different ways to load/select characters in a RPG game

texts:
I am brand new here, and have been designing a two player card game where from tens of thousands of cards each player selects up to 80 cards DECK, and then fights with those cards.

For reference Yu Gi Oh

There's a lot of data and a player can have up to 3 instances of a card to play and they select the cards they want before the game starts. How do I load this information when starting the game? Any suggestions on the different ways to do it during game initialization?

Like how this is done in RPG games like League of Legends.


texts: Should I be sharing data between graphics and physics engine in the game?

texts:
I'm writing the game engine that consists of few modules. Two of them are the graphics engine and the physics engine.

I wonder if it's a good solution to share data between them?

Two ways (sharing or not) looks like that:

Without sharing data

GraphicsModel{
    //some common for graphics and physics data like position

    //some only graphic data
    //like textures and detailed model's verticles that physics doesn't need
};

PhysicsModel{
    //some common for graphics and physics data like position

    //some only physics data
    //usually my physics data contains A LOT more informations than graphics data
}

engine3D->createModel3D(...);
physicsEngine->createModel3D(...);

//connect graphics and physics data
//e.g. update graphics model's position when physics model's position will change

I see two main problems:

A lot of redundant data (like two positions for both physics and graphics data)
Problem with updating data (I have to manually update graphics data when physics data changes)

With sharing data

Model{
     //some common for graphics and physics data like position
};

GraphicModel : public Model{
    //some only graphics data
    //like textures and detailed model's verticles that physics doesn't need
};

PhysicsModel : public Model{
     //some only physics data
    //usually my physics data contains A LOT more informations than graphics data
}

model = engine3D->createModel3D(...);
physicsEngine->assingModel3D(&model); //will cast to
//PhysicsModel for it's purposes??

//when physics changes anything (like position) in model
//(which it treats like PhysicsModel), the position for graphics data
//will change as well (because it's the same model)

Problems here:

physicsEngine cannot create new objects, just "assing" existing ones from engine3D (somehow it looks more anti-independent for me)
Casting data in assingModel3D function
physicsEngine and graphicsEngine must be careful - they cannot delete data when they don't need them (because second one may need it). But it's rare situation. Moreover, they can just delete the pointer, not the object. Or we can assume that graphicsEngine will delete objects, physicsEngine just pointers to them.

Which way is better?

Which will produce more problems in the future?

I like the second solution more, but I wonder why most graphics and physics engines prefer the first one (maybe because they normally make only graphics or only physics engine and somebody else connect them in the game?).

Have they any more hidden pros & contras?


texts: Javascript - create a new bullet instance every time a user event is triggered

texts:
Basically I have a function that I need to create an object of every time the user presses space(event listeners not shown here).

function arrow(){
    this.x = playerXPos + 40;
    this.y = playerYPos + 40;

    this.init = function(){
        var arrowImg = new Image();
        arrowImg.src = "arrow.png";
        c.drawImage(arrowImg,this.x,this.y);

        this.x+=10;

        if(this.x > 500){
            keySpace = false;
        }
    }
}

if(keySpace){
    arrowObj.init();
}

This works great, but I can only have 1 arrow on the screen at once, which is rather limiting. Is there some way to create a new object every time the if statement is true, and store it in an array or something?


texts: Random Calculations for Strategy Based Games in Java

texts:
I am making a console based strategy game like Genghis Khan: Legend of the White Wolf, although it is in console. How can I implement the Random Calculation in there? First off, the game goes like this, for example you have 34 Soldiers and the enemy has 45 Archers. Say you attack the Archers, normally it is not good to subtract the number of archers from the number of Soldiers. How can I implement a random difference using Random Method? I made it this way though:

int result = 1+r.nextInt(20);
        for (int j = 1; j <= 1; j++) {
            System.out.println(result);
        }
}
attacker -= result;

Is that okay? How about for the Defender? Should I make another random result for the damage to them? Is there an easy coding here rather than this lengthy one I did?


texts: How would I make behavioral AI, from a game engine, for character conversation modelling?

texts:
I want to use the behavioral AI from a game engine, for character conversation modelling. Most game engines provide very good graphics pipelines, like Unity, but I want to use the AI part, like in "Assassins Creed 2".

It looks like the character is always in a state machine during gameplay, especially when he talks to the other characters and the NPCs. The other characters, like Lucy, do not say the same thing. Instead, they say something which is related to the local goal of the state. Is it all scripted, or is there any AI?


texts:
For my game that I'm developing I want to have my cards dynamically drawn so if there is any changes done to them it could be drawn on the card itself.

What I have currently is that the cards are drawn to a RenderTarget at their originally designed size of 2100x1480 px. (I'll probably for game purposes have to scale that down to 1050x740 for its native size, but was designed that way to have 600 dpi for physical versions).

Anyway the way I want to do it is that after drawing everything to the RenderTarget I scale it down and store that scaled down texture to the card's texture (which will be 164 x 115 for the playing size, the 1050 x 740 is the zoomed in size that I want so players can view what the card does and stats). The issue that I'm facing is that the way I currently tried to do it was far too slow taking over 9 seconds to scale it down after drawing the original size to the RenderTarget.

Is there a way to scale a texture via GPU rather than by CPU? I'm currently using a CPU method as I'm new to working with textures and drawing.


texts: How to post player´s score on Facebook (with js)

texts:
I have my game made with Phaser (and compiled with cocoon.io) and on the leadersboard state I want to let the user to post his score on Facebook.

Well, I created an App on Facebook and I´m not finding a good solution to create this simple post, something like "I scored 10 points on this riduculous game..." Pretty easy on Twitter and not so easy on Facebook, I can find information about posting links and that stuff but I´m not finding a proper way to create a simple post just with text.

How do you guys do this? I guess I´m missing something, it shouldn´t be so complicated.

(I already tested this link and it´s not working for me Simple way to post score from my game to Facebook and Twitter? API Error Code: 191
API Error Description: The specified URL is not owned by the application
Error Message: redirect_uri is not owned by the application.)


texts: Export rig from one Maya project to another

texts:
We are a team creating 3D characters for a game. Each of us is doing a separate character in a separate project. But we need all the characters to have exactly the same rig, and the rigging will be done by a different person. There is a need to speed up the process so we are thinking of doing the rig only once.
Is there a way to export a rig from one Maya project and import it on a character in another?


texts:
How can I parse a spritesheet consisting of scattered sprites with different sizes, like this example and return the (x, y) and (width, height) values of each sprite?
It is trivial when the spritesheet is split on equal widths and heights, which for this thing I envy Unity for.
After spending some time researching, the best I could find is http://www.spritecow.com/, which is Javascript based and you have to manually click on your sprites to parse a single sprite, moreover it is really slow.


texts: Setting a jump counter in my 2d platformer built with phaser

texts:
I have a platforming game, written in javascript with the Phaser.js framework, where my character collects objects. I thought trying to collect all objects in the least amount of jumps would be interesting, so I tried to implement a jump counter. Relevant pieces of code:

var jumpCount = 0;
var jumpText;

function create (){
    jumpText = this.add.text(16, 48, 'Jumps Used: 0', {fontsize: '32px', fill: '#000'});
}

function update (jumpCount){
    if (cursors.space.isDown && player.body.touching.down){
        player.setVelocityY(-630);
        jumpCount++;
        jumpText.setText('Jumps Used: ' + jumpCount);
    }
}

This is displaying the counter and incrementing it sort of correctly, but it seems to count the amount of time that the spacebar is held down and is leading to jump counts that are floats well into the thousands.

Is there a more reasonable way to handle counting the number of times a player has manually jumped?

Thanks!


texts: Particle dynamics simulation and conservation of energy

texts:
Suppose you want to simulate the dynamics of a particle subject to Newton's laws of motion. We could just fix a discretization of the time dt and solve approximate differential equations like

    y+=vy*dt;
    vy+=ay*dt;

and so on for the other coordinates. If we are unsatisfied with the accuracy we could make dt smaller or use higher order approximation methods, at the cost of slowing the simulation and this would reduce the error, but the error can still sum up and become big in after a long time.

Now my point is: suppose that you want to run the simulation for long time so you don't mind short run accuracy but you want the system to preserve long run properties such as conservation laws.

Concrete example: suppose the particle is subject to gravity with the acceleration ay constantly equal to g. We have the conservation law 1/2 m v^2 + m g h =constant.

Now after the approximation step I could compute the energy and discover it is slightly changed, and this lead to a degeneration after long times (for example it can lead to overflow errors or particle slowing down). At each step I could then adjust v and h in order to make the energy conserved, but I have a lot of choice here... how do I decide for the better in this constrained choice?

In general what is the best way to deal with situation where you can sacrifice short time accuracy to save speed and preserve the long time behavior?


texts: How can I assign an icon to multiple game objects in the Unity Editor?

texts:
In my game, I have hundreds of enemy spawn points represented as invisible GameObjects, with one having an assigned icon as seen here:

However, I would like to give all of the spawn points icons like this through the inspector view like this first point. However, when selecting a group of them, the editor doesn't seem to allow me to give all of them the same icon. Is there a way to perform that task, without going through every single spawn point and assigning the icon?
EDIT: I am using the 2018.2.5f1 Personal version of the editor.


texts: Rendering a ID3D11Texture2D into a SkImage (SkiaSharp/Avalonia)

texts:
I'm currently trying to create an interop layer to render my render target texture into a Skia SkImage. This is being done to facilitate rendering from my graphics API into Avalonia.
I've managed to piece together enough code to get everything running without any errors (at least, none that I can see), but when I draw the SkImage I see nothing but a black image.
Of course, these things are easier to describe with code:
private EglPlatformOpenGlInterface _platform;
private AngleWin32EglDisplay _angleDisplay;
private readonly int[] _glTexHandle = new int[1];

IDrawingContextImpl context // <-- From Avalonia

_platform = (EglPlatformOpenGlInterface)platform;
_angleDisplay = (AngleWin32EglDisplay)_platform.Display;

IntPtr d3dDevicePtr = _angleDisplay.GetDirect3DDevice();

// Device5 is from SharpDX.
_d3dDevice = new Device5(d3dDevicePtr);

// Texture.GetSharedHandle() is the shared handle of my render target.
_eglTarget = _d3dDevice.OpenSharedResource<Texture2D>(_target.Texture.GetSharedHandle());

// WrapDirect3D11Texture calls eglCreatePbufferFromClientBuffer.
_glSurface = _angleDisplay.WrapDirect3D11Texture(_platform, _eglTarget.NativePointer);

using (_platform.PrimaryEglContext.MakeCurrent())
{
   _platform.PrimaryEglContext.GlInterface.GenTextures(1, _glTexHandle);
}

var fbInfo = new GRGlTextureInfo(GlConsts.GL_TEXTURE_2D, (uint)_glTexHandle[0], GlConsts.GL_RGBA8);
_backendTarget = new GRBackendTexture(_target.Width, _target.Height, false, fbInfo);

using (_platform.PrimaryEglContext.MakeCurrent())
{
   // Here's where we find the gl surface to our texture object apparently.
   _platform.PrimaryEglContext.GlInterface.BindTexture(GlConsts.GL_TEXTURE_2D, _glTexHandle[0]);

   EglBindTexImage(_angleDisplay.Handle, _glSurface.DangerousGetHandle(), EglConsts.EGL_BACK_BUFFER);

   _platform.PrimaryEglContext.GlInterface.BindTexture(GlConsts.GL_TEXTURE_2D, 0);
}

// context is a GRContext
_skiaSurface = SKImage.FromTexture(context, _backendTarget, GRSurfaceOrigin.BottomLeft, SKColorType.Rgba8888, SKAlphaType.Premul);

// This clears my render target (obviously). I should be seeing this when I draw the image right?
_target.Clear(GorgonColor.CornFlowerBlue);

canvas.DrawImage(_skiaSurface, new SKPoint(320, 240));

So, as far as I can tell, this should be working. But as I said before, it's only showing me a black image. It's supposed to be cornflower blue.  I've tried calling Flush on the ID3D11DeviceContext, but  I'm still getting the black image.
Anyone have any idea what I could be doing wrong?


texts:
I'm making a game, it's a terraria-like game, with 20x20 blocks, and you can place and remove those blocks. Now, I am trying to write collisions, but it isn't working as I want, the collision successfully stops the player from going through the ground, but, when I press a key like A + S, that means if I walk down and left (Noclip is on atm), my player will go into the ground, bug up, and exit the ground somewhere else in the level. I made a video of it. The red text means which buttons I am pressing.

You see, if I press A and S together, I go into the ground.
Here is my collision code:

Vector2 collisionDist, normal;

private bool IsColliding(Rectangle body1, Rectangle body2)
{
    normal = Vector2.Zero;

    Vector2 body1Centre = new Vector2(body1.X + (body1.Width / 2), body1.Y + (body1.Height / 2));
    Vector2 body2Centre = new Vector2(body2.X + (body2.Width / 2), body2.Y + (body2.Height / 2));

    Vector2 distance, absDistance;

    float xMag, yMag;

    distance = body1Centre - body2Centre;

    float xAdd = ((body1.Width) + (body2.Width)) / 2.0f;
    float yAdd = ((body1.Height) + (body2.Height)) / 2.0f;

    absDistance.X = (distance.X < 0) ? -distance.X : distance.X;
    absDistance.Y = (distance.Y < 0) ? -distance.Y : distance.Y;

    if (!((absDistance.X < xAdd) && (absDistance.Y < yAdd)))
        return false;

    xMag = xAdd - absDistance.X;
    yMag = yAdd - absDistance.Y;

    if (xMag < yMag)
        normal.X = (distance.X > 0) ? xMag : -xMag;
    else
        normal.Y = (distance.Y > 0) ? yMag : -yMag;

    return true;

}

private void PlayerCollisions()
{
    foreach (Block blocks in allTiles)
    {
        collisionDist = Vector2.Zero;
        if (blocks.Texture != airTile && blocks.Texture != stoneDarkTexture && blocks.Texture != stoneDarkTextureSelected && blocks.Texture != airTileSelected && blocks.Texture != doorTexture && blocks.Texture != doorTextureSelected)
        {
            if (IsColliding(player.plyRect, blocks.tileRect))
            {
                if (normal.Length() > collisionDist.Length())
                {
                    collisionDist = normal;
                }

                player.Position.X += collisionDist.X;
                player.Position.Y += collisionDist.Y;

                break;
            }
        }
    }
}

I got PlayerCollisions() running in my Update method.
As you can see it works partly, but if it runs perfectly, it would be awesome, though I have no idea how to fix this problem. Help would be greatly appreciated.

EDIT:

If I remove the break; it works partly, then it is just the thing that it spasms when it hits two or more blocks at once, like, if I touch 2/3 blocks at once, it does twice the force up. How can I make it so that it only does the force for one block, so it stays correct, and does not spasm? Thanks.


texts: Given a 2D array, how do I generate a random path of fixed length from a random point at length 0 to a random point at max length?

texts:
I'm trying to generate a random path on a 2D grid given that:

The width and height of the grid are given
The length of the path to generate is given
The path can't move "back"
The path starts from a random point at height 0 and ends at a random point at max height
A path segment cannot "touch" with a path segment that is at its height - 1 that is not the latest generated segment of the previous height

This is what two paths generated from the parameters {Width:11, Length:17, PathLength:30} would look like:

and this is an example of a path that should not be generated:

The result of the algorithm should be a list of value pairs such as this: (8,6) in any order, which indicates the segments of the path.
I've been trying to solve this problem for a while, but I have problems understanding how to make this have a given length. If the given length was not a requirement I could just generate it with a nested for cycle and some rules. Please help!


texts:
How to scale images to full screen on all devices, i want to use %

The method I've seen so far is to define pixels

image_variable_name = display.newImage( "testimage.jpg", 100, 300 )

I want to do something like

image_variable_name = display.newImage( "testimage.jpg", 100%, 100% )

But that won't work, I want something like fluid CSS, the image will maintain the size no matter what is the size of the screen. Is it possible?


texts: Should I wrap a template function with another template function, or...?

texts:
I'm currently making an Entity System, using C++, and I've questioned myself about how I should interface some methods. Specifically in my Entity and ComponentManager classes.

The ComponentManager, manages all components for all entities in a specific world. It can add/remove/determine if a Component exists, etc. Now to retrieve a component, I was thinking of using a template function, that way it looks neater and it doesn't have as many casts (outside the method). But then I want quick access to components through an Entity object.
e.g.

entity.getComponent<VelocityComponent>().x = 30;

(and yes I know an Entity is just an ID, that's why I have my components in the ComponentManager class, and each Entity is represented by an ID).

i.e.

ComponentManager's get function:
(Components are stored as a 2d array, with the first element being the ID of an entity and the 2nd element being the ID of a component's class type)

template <typename Comp> // Comp = Component
Comp* getComponent(Entity& e)
{
    return (Comp*)_components[e.getId()][Comp::GetClass().getId()];
}

And the Entity's get function:

template <typename Comp>
Comp* getComponent()
{
      return getWorld().getComponentManager().getComponent<Comp>(*this);
}

So if I was to use template functions I would just have 2 duplicates of template functions. Now of course, this goes the same for adding components to an Entity. So basically, is it a good idea to wrap a template function with another template function?

I can, alternatively make the the methods in the Entity system templates and make the methods in the component managers non-template functions, i.e.

Component* ComponentManager::getComponent(Entity& e, const Component::Class& componentClassType) const
{
     return _components[e.getId()][componentClassType.getId()];
}

I'm confused on what I should do.:


texts: Is there any harm in having the main game loop run uncontrolled?

texts:
I was wondering if there is any possible harm when my game loop runs as fast as the system allows?

I currently have a loop, that, by measuring passed time in nanoseconds, runs the game logic and rendering logic at predefined speeds without a problem. In fact any logic I do in the loop is clocked to a certain amount of calls each second.

The loop itself though just runs about as fast as it likes to which comes up to around 11.7 million loops a second on my machine.

Loop (simple pseudocode):

while(!isGameOver){

 if(canPollInputs){
    pollInputs()
 }

 while(canStepLogic){
    stepLogic()
 }

 if(canRender){
    render()
 }
}

My question is basically if that simple loop, if its not running at a controlled speed, can do any harm to a system?

Edit:
That means my logic is running 30 times a second (30 tps), my renderer is running at 60 fps, I'm polling inputs a 100 times a second and there's also some logic to cope with logic or rendering taking longer than expected. But the loop itself is not throttled.

Edit:
Using Thread.sleep() to e.g. Throttle the main loop down to 250 loops per second leads to a reduction but the loops runs at around 570 loops per second instead of the desired 250 (will add code when I'm at my desktop machine..)

Edit:
Here we go, a working java gameloop in order to clarify things. Also feel free to use it but don't claim it yours ;)

private void gameLoop() {

    // Time that must elapse before a new run
    double timePerPoll = 1000000000l / targetPPS;
    double timePerTick = 1000000000l / targetTPS;
    double timePerFrame = 1000000000l / targetFPS;
    int maxFrameSkip = (int) ( (1000000000l / MINIMUM_FPS) / timePerTick);

    int achievedPPS = 0;
    int achievedFPS = 0;
    int achievedTPS = 0;

    long timer = TimeUtils.getMillis();

    int loops = 0;

    int achievedLoops = 0;

    long currTime = 0l;
    long loopTime = 0l;

    long accumulatorPPS = 0l;
    long accumulatorTPS = 0l;
    long accumulatorFPS = 0l;

    long lastTime = TimeUtils.getNano();

    while(!isRequestedToStop) {
        currTime = TimeUtils.getNano();
        loopTime = currTime - lastTime;
        lastTime = currTime;

        loops = 0;

        accumulatorPPS += loopTime;
        accumulatorTPS += loopTime;
        accumulatorFPS += loopTime;

        if(accumulatorPPS >= timePerPoll) {
            pollInputs();
            playerLogic();
            achievedPPS++;
            accumulatorPPS -= timePerPoll;
        }

        while(accumulatorTPS >= timePerTick && loops < maxFrameSkip) {
            tick();
            achievedTPS++;
            accumulatorTPS -= timePerTick;
            loops++;
        }

        // Max 1 render per loop so player movement stays fluent
        if(accumulatorFPS >= timePerFrame) {
            render();
            achievedFPS++;
            accumulatorFPS -= timePerFrame;
        }

        if(TimeUtils.getDeltaMillis(timer) > 1000) {
            timer += 1000;
            logger.debug(achievedTPS + " TPS, " + achievedFPS + " FPS, "
                    + achievedPPS + " Polls, " + achievedLoops + " Loops");
            achievedTPS = 0;
            achievedFPS = 0;
            achievedLoops = 0;
        }

        achievedLoops++;
    }
}

As you can see there is almost no code run on each loop but always a certain selection based on how much real time has passed. The question is referring to that 'worker loop' and how it does influence the system.


texts: How to transition between states and mix states in a finite state machine?

texts:
I don't understand how to use a finite state machine with the entity controlled by the player.

For example I have a Mario style game (2d platform). I can jump, run, walk, take damage, swim, etc. So my first thought was to use this actions as states. But what happens, if you are running when you take damage? Or jumping, taking damage and shooting at the same time?

I just want to add functionalities (actions) to the player in a clean way (not using it for all the actions in the entity update) .


texts: Using DirectX9 within Visual Studio 2012 in Windows 8?

texts:
Asking the question here simply because my PC is down for the count for a while and wasn't able to stave a curiosity before that happened.

I picked up a few books about programming Games in DirectX, specifically 9.0c.

I have a Windows 8 machine, and have Visual Studio 2012, and remember a massive headache about following some of the more simple DirectX tutorials on the web as everything I could find was prior to Windows 8 when all headers and such we're available, and DirectX wasn't merged into the WindowsSDK. (I think specifically it was the absence of a commonly used DX UTILITY that was causing issues).

Before my PC went down, I wasn't able to try simply installing previous SDK's.

.. Does this work? Can one, under a Windows 8 environment with Visual 2012, install the previous DX9 SDK's and it'd work out alright? Are there going to be conflicts? How can I set this up correctly?
I'm just interested in getting going with the basics of what can be followed by the majority of the resources available today, and not so much "bleeding edge" at the moment...

Thank you in advance!


texts: Collision detection with multiple polygons simultaneously

texts:
I've written a collision system which detects/resolves collisions between a rectangular player and a convex polygon world using the Separating Axis Theorem. This scheme works fine when the player is colliding with a single polygon, but when I try to create a level made up of combinations of these shapes, the player gets "stuck" between shapes when trying to move from one polygon to the other.

The reason for this seems to be that collisions are detected after the player has been pushed through the shape by its movement or gravity. When the system resolves the collision, it resolves them in an order that doesn't make sense (for example, when the player is moving from one flat rectangle to another, gravity pushes them below the ground, but the collision with the left hand side of the second block is resolved before the collision with the top of the block, meaning the player is pushed back left before being pushed back up).

Other similar posts have resolved this problem by having a strict rule on which axes to resolve first. For example, always resolve the collision on the y axis, then if the object is still colliding with things, resolve on the x axis. This solution only works in the case of a completely axis oriented box world, and doesn't solve the problem if the player is stuck moving along a series of angled shapes or sliding down a wall.

Does any one have any ideas of how I could alter my collision system to prevent these situations from happening?


texts: What do you use to bundle / encrypt data?

texts:
More and more games are going the data driven route which means that there needs to be a layer of security around easy manipulation. I've seen it where games completely bundle up their assets (audio, art, data) and I'm wondering how they are managing that? Are there applications / libraries that will bundle and assist you with managing the assets within? If not is there any good resources that you would point to for packing / unpacking / encryption?

This specific question revolves around C++, but I would be open to hear how this is managed in C#/XNA as well.

Just to be clear -- I'm not out to engineer a solution to prevent hacking. At the fundamental level we're all manipulating 0's and 1's. But, we do want to keep the 99% of people that play the game from simply modifying XML files that are used to build the game world. I've seen plenty of games bundle all of their resources together. I'm simply curious about the methods they're using.


texts: Unity3D profiler isn't helping. How to debug increased memory?

texts:
Using Instruments or Xcode, my iOS game uses around 115 MB memory when the menu scene is loaded. After doing battles and other things within the game and reloading the menu, the memory usage is up to 170 MB.

The real problem is that Unity's profiler doesn't tell me anything: there are a few MB of extra system libraries and a few MB of extra Texture2D assets, but there's no explanation for the big increase. Adding more Resources.UnloadUnusedAssets() and GC.Collect() doesn't help.

How can I investigate this? (Note: it reaches a steady state. The memory doesn't continue to rise after a certain point.)


texts: Updating settings UI from script also triggers method to update settings from UI interaction

texts:
My application has a UI for settings which is a mixture of textboxes and scrollbars with which users can interact. I have created a class for these settings and create an object to store them. The user can also give command line arguments to apply settings from a file.
I have a function that loads this data into the UI from the object (i.e read from a file) and another function that changes object data when user make changes to the UI.
My problem is: if I load the data from file into UI, the function responsible to reflect these changes in the UI fires up but the other function also fires up because changes were made to the UI.
So what should I do to overcome this? Should I implement some kind of state mechanism that would tell code that user has made the changes, or setup some flag which will mark that the data is loaded from a file. If you can suggest some design patterns to follow?


texts: How to map trapezoid image to rectangle cubemap face?

texts:
I am writing a 360 video application on oculus mobile SDK. My video frame has a trapezoid region and I need to map it into a rectangle region.

In the above figure, trapezoid ABDC is part of my video frame. I need to map it into a rectangle A'B'D'C'. The rectangle is part of a face of a cube.

At the video frame generation side, the trapezoid region is generated from a rectangle region. The bigger side of the trapezoid (AC in the abovefigure) is same as the height of rectangle (side A'C') and smaller side of trapezoid (side BD) is smaller than the height of the rectangle. I know I am loosing some details in this process and I am fine with it.

At rendering side for mapping, I need to provide the region as combination of triangles. So I gave two triangles, ABC and CBD. But sice the triangle sizes are not equal, mapping was not proper. The triangle region CBD expands more compare to triangle region ABC.

I also tried drawing diagonals to trapezoid ABDC and mapped using four triangles. Even with that logic I observed same issue.

Update 1
Please refer to image3(https://i.stack.imgur.com/yRy9W.jpg) and image1(https://i.stack.imgur.com/dwOuI.jpg) of this question (https://stackoverflow.com/questions/15141039/transform-rectangle-to-trapezoid-for-perspective). Please note, in my application decoded image will be like image3 and I need to render it such that it appears like image1.

Can anyone suggest me the right way to map trapezoid to rectangle?


texts: How do I render 2D top-down tiled, directed water flow?

texts:
I'm working on a top-down tile-based fairly graphical 2D game inspired by Dwarf Fortress. I'm at the point of implementing a river in the game world, which covers a number of tiles, and I've calculated the flow direction for each tile, as shown below by the red line in each tile.

For reference of the graphical style, here's how my game looks currently:

What I need is some technique to animate water flowing in each of the river tiles, so that the flow blends into the surrounding tiles so that tile edges are not apparent.

The closest example I have found to what I am after is described at http://www.rug.nl/society-business/centre-for-information-technology/research/hpcv/publications/watershader/ but I'm not quite at the point of being able to understand what's going on in it? I have enough of an understanding of shader programming to have implemented my own dynamic lighting but I can't quite get my head around the approach taken in the linked article.

Could someone explain how the above effect is achieved or suggest another approach to get the result I want? I think part of the above solution is overlapping the tiles (though I'm not sure in which combinations) and rotating the normal map used for the distortion (again no idea on specifics) and past that I'm a bit lost, thanks for any help!


texts: Built-in Terrain analogs search: is it worth to use imported 3d-model?

texts:
I think 3d-model is better than the built-in terrain-component in Unity when it comes to optimization. But when it comes to texturing terrain made in 3rd party 3d-modeller, how to apply resulting texture in Unity? If the terrain is too big you can't bake it in UV map. Otherway you should split it in many UV's and each one is separate material, which kills performance in the game. Other decision that i see is to use generated type of material and just tile it across the terrain-mesh, but you can't draw the details like roads on it...

So i'm confused is it really worth it to use Unity's terrain analogs or there is no way to do so efficiently?


texts: Replicating Flight Mechanics of Star Wars Battlefront (2015)

texts:
I'm trying to replicate the flight mechanics from Star Wars Battlefront (2015) in Unity and I can't get my head around what exactly is going on.

Specifically, how do I get the camera to behave like this using Unity and C#:

https://youtu.be/gxZdOUiEiyY?t=1m1s

I don't mind if you don't give code, I'm just struggling to understand what happens and when in terms of camera movements and rotation.


texts:
I want to disable the Question Prefab so that when it is clicked the Prefab behind it will be shown:

I am using Unity 5.3.5 and C#.


texts: Unity animation: How to reset pivot after 3D character somersaults?

texts:
I have this new character animation that I made in Blender. None of my other animations use Root Transform or anything fancy, and they work great. This new one is special though. The character jumps up, flips upside-down, hits his head on the ground, lands on his back, and stands back up again. See, when he stands up, he is a distance from the pivot point. I imagine that after this animation concludes, transitions to other animations are going to be buggy.  Here is the animation:

I didn't know what to do at the end so I keyed his idle pose where the animation began. This means that for the animation to be seamless, Unity needs to know to move the character FORWARD a specific distance at the same rate that the distance between the character and the pivot point is closing, during the last 2 frames of the animation.

At this point, none of my other character animations need to be tweaked manually. What do I need to do to make sure this animation works with my other animations (walking, running, jumping, etc) so there is no jarring "snap" into position, and animations are correctly aligned?

Could I do this with an animation event? If so, how? I have never used one before.


texts: Need Feedback for PHP & MySQL Saving Game Progress

texts:
My team is planning to create a simulation game using Javascript, CodeIgniter and MySQL for the backend.

It will be mostly click based, ie: There will be buttons for activities like Eat, Play, Study, etc, and in the game environment, one day will contain 3 phases, day, noon, night . And for each phase, users can pick between those activities and those activities will increase certain character parameters (Intelligence, Focus, Fun, etc) then the game will progress to the next phase. Once it's night, the game will progress to the next day.

So I need feedbacks on how to saving the game progress. Here's what I had in mind :

There will be a table for Users (obviously) that will contain users' data including the parameters/stats, money, etc. Do you think the stats etc must be separated to another table so there will be a history of stat increases?

For the saving, I'm thinking of using a Logs table that record every activity is by users. So if in day 1 phase 1 (phase day) the user picks Eat, I will insert to this logs table more or less like : user_id = 1, day = 1, phase = 1, activity = eat. So for example when the user stops playing and exits the game after day 1 phase night, the database will have :

user_id = 1, day = 1, phase = 1, activity = eat
user_id = 1, day = 1, phase = 2, activity = play
user_id = 1, day = 1, phase = 3, activity = sleep

And when they continue the game, I will read from this table and get the latest row of this user_id, and after checking that the latest row is day 1 phase 3, the game interface will display day 2 phase 1. However, this means that the phases for a day must be fixed from the start, so I can't include, for example, random additional time phases outside these phases (think of it as an extra opportunity to increase the stats).

So what do you think? I hope the explanation is clear enough.


texts: Data overwritten in MapSubresource() method

texts:
I am trying to dynamically update the vertex buffer in a UWP project using SharpDX, once every time I call the following method, where context is the device context member.

public void UpdateVertexBuffer(ScatterVertex data)
            {
                DataBox dataBox =
                this.context.MapSubresource(
                    scatterPointVertexBuffer,
                    0,
                    D3D11.MapMode.WriteNoOverwrite,
                    D3D11.MapFlags.None
                    );
                var pointer = dataBox.DataPointer;
                pointer = Utilities.WriteAndPosition(pointer, ref data);

                this.context.UnmapSubresource(scatterPointVertexBuffer, 0);
            }

I am expecting to keep the old data during the update process. However each time I call this method, the previous data is overwritten. I checked the pointer of dataBox.DataPointer and it remains the same value in every call.

Using DataStream as output doesn't help either. In either cases if I check the vertex buffer I get only one vertex.

But shouldn't the MapSubresource method protect the old data if I choose the WriteNoOverwrite mode?

What should I do to keep the previous data during update?


texts: How to do the Geometry Wars gravity well effect

texts:
I'm not talking about the background grid here, I'm talking about the swirly particles going around the Gravity Wells! I've always liked the effect and decided it'd be a fun experiment to replicate it, I know GW uses Hooke's law all over the place, but I don't think the Particle-to-Well effect is done using springs, it looks like a distance-squared function.

Here is a video demonstrating the effect: http://www.youtube.com/watch?v=YgJe0YI18Fg

I can implement a spring or gravity effect on some particles just fine, that's easy. But I can't seem to get the effect to look similar to GWs effect. When I watch the effect in game it seems that the particles are emitted in bunches from the Well itself, they spiral outward around the center of the well, and eventually get flung outward, fall back towards the well, and repeat.

How would I make the particles spiral outward when spawned? How would I keep the particle bunches together when near the Well but spread away from each other when they're flung outward? How would I keep the particles so strongly attached to the Well?

EDIT:
http://www.youtube.com/watch?v=1eEPl8kOXN8 <- Video
https://dl.dropbox.com/u/49283213/gw.gif <- GIF of the particle path

I disabled the randomization within GW to make the particle effect easier to see, here's a minute video where you can see a blue-green drain sending out it's bunch of particles. The red particles are from the explosions that normally appear all over the place. Some observations I made from the video:

The particles are emitted from the center (or near center) of the drain
All particles are being forced into a clockwise motion around the center so some sort of tangential motion is being applied, you can easily see this when the red explosion particles get close to the drain.


texts: Drawing a grid over a terrain using a mesh - Shader Depth and Z-Buffer

texts:
What I'm trying to achieve is rendering a (huge) tile grid over a terrain. For that I'm using a generated mesh of quads, one for every tile, whose vertices Y value is the same of the terrain to "shape" this mesh like the terrain.

My problem is that this mesh should be rendered always over the terrain, keeping every other object rendered on top of this grid. As you should guess I'm a beginner in shader programming. So here are some caps:

Rendering the mesh with simple unlit transparent shader (with ZTest, ZWrite and Cull values):

As you can see there are problems with the z-fighting, when the grid should always be drawn on top. Rising the terrain won't solve it, since the terrain have lots of "peaks" and the quads should be planes with lots of vertex to be able to follow the terrain (or rising a lot the grid which will cause it to float over the terrain).

Changing the ZTest to Always:

Here I've the problem that the tiles behind the mountains are still drawn when they shouldn't, which make sense since it's ignoring z-ordering, and therefore rendering over other objects too.

I've tried using a another shader pass to first write to the z buffer to avoid rendering the tiles behind the mountains with no success. I guess I'm missing something related to the terrain shader, but I have no clue what it may be.

Any help will be much appreciated.


texts: Editing attached component property in Unity (C#)

texts:
This might be more of a general C#/programming query, but since it's game dev related, I'm putting it here.

I am trying to randomise a property in a custom component (C# script) across several Unity game objects.

hostiles is a list of game objects, each with an attached Stats component.

foreach (GameObject gO in hostiles)
{
    // Randomise spawn area…
    gO.GetComponent<Stats>().AreaNo = Random.Range(0, 3);
}

Perhaps unsurprisingly, all of my objects end up with the same value for AreaNo. It seems as though I’m reassigning some global version of Stats.AreaNo in my loop, rather than the individual instances. What am I missing?

(Sorry in advance for the noobish question!)


texts: Using max for entry time in swept collision

texts:
I was reading this tutorial on swept AABB collision detection, and I was confused by this piece of code:

// find the earliest/latest times of collision
float entryTime = std::max(xEntry, yEntry);
float exitTime = std::min(xExit, yExit);

The tutorial says this about this code:

  entryTime will tell use when the collision first occurred and exitTime
  will tell us when it exited the object from the other side. This can
  be useful for certain effects, but at the moment, we just need it to
  calculate if a collision occurred at all.

So if entryTime is supposed to be the first time a collision occured, then why is max being used to determine the first time of collision? Shouldn't min be used instead? If max is used, then the highest value will be returned. The highest value would be the time of the last collision. Obviously this must be the correct way of doing this, but I'm not understanding it. If you are trying to find the first axis to collide, it would seem intuitive that you use min.


texts:
The terminology "game state" is a bit vague to me. Could anybody clarify what is included in the game state, please?

Is it a state of all the variables and objects within the game at particular moment?


texts: Why do I get java.lang.OutOfMemoryError in android studio after adding a 2nd activity?

texts:
After I decided to create an activity to show the results of the game with try again button. Every 3rd try the game will stop with this error.

  java.lang.OutOfMemoryError: Failed to allocate a 3819212 byte allocation with 610080 free bytes and 595KB until OOM

What am I doing wrong here?

My try again button code.

 public void tryAgain(View view) {
    startActivity(new Intent(getApplicationContext(), StartActivity.class));
}

How I call my result activity

Intent intent = new Intent(Constants.CURRENT_CONTEXT.getApplicationContext(), ResultActivity.class);
            intent.putExtra("SCORE", obstacleManager.getScore());
            Constants.CURRENT_CONTEXT.startActivity(intent);


texts: Need help converting LPDIRECT3DTEXTURE9 to openGl libgdx Pixmap

texts:
What i'm trying to achieve. I need to know the equivalent of LPDIRECT3DTEXTURE9 to openGL, the problem is I only know Pixmap class of libgdx which pixmap.drawPixel(x, y, color) is only available, I cannot find how to convert layer->lightMap->LockRect(0, &rectLock, 0, 0)

Below is example code of c, LPDIRECT3DTEXTURE9 lightMap is used which unknown in openGL to me.

D3DLOCKED_RECT rectLock;
D3DCOLOR* pixels;
LandLayer* layer;
int j;

for (int i = 0; i < m_layers.GetSize(); i++)
{
    layer = m_layers[i];
    layer->lightMap->LockRect(0, &rectLock, 0, 0);
    pixels = (D3DCOLOR*)rectLock.pBits;
    for (j = 0; j < MAP_SIZE * MAP_SIZE; j++)
        pixels[j] = D3DCOLOR_ARGB(layer->alphaMap[j], m_colorMap[j * 3], m_colorMap[j * 3 + 1], m_colorMap[j * 3 + 2]);
    layer->lightMap->UnlockRect(0);
}

What I have done in kotlin, using Pixmap from libgx https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/Pixmap.java

tmpColor.set( Color.toIntBits( r.toInt(),g.toInt(),b.toInt(),a.toInt()))
pixmap.drawPixel(x, y, tmpColor.toIntBits())


texts: OpenGL: How do I map a square texture onto a rectangular surface?

texts:
I'm not asking about how to map the texture itself. I'm just wondering how I could go about evenly mapping a texture to an object so that it repeats itself instead of stretching to the surface.

For example:

Thanks.


texts:
I have seen and implemented these ideas: Simple Physics based Movement SO answer. Building a Better Jump GDC Talk. And written a tutorial about it Making a Platformer in Pico 8.
Finally made a simple game Coler Js2020 using these ideas. People have complained the player is too fast, or the springs are not right.
But I want better,more juicy, control over player jump. Like as if I am drawing the trajectory. I don't want real life physics. I want juicy physics where it just feels right, like float-y in SMB or stiff like in Celeste, or Spelunky.
Maybe we can model this in terms of a sound envelope:
Attack is time it takes to reach peak of the jump.
Decay is time it takes to reach sustain level from the peak.
Sustain is, time to stay at maximum height, until the button is released or some timeout.
Release is the time to go to ground from maximum height.
I am studying Celeste source code so far I have this:
// p.dx p.dy is the velocity
// p.x p.y is computed through this velocity elsewhere.
// mu.appr(value, target, amount) returns value approached to target by specified amount. like `lerp`.

const JumpGraceTime = 4;
const DuckFriction = 0.1;
const MaxRun = 4;
const RunReduce = 0.3;
const RunAccel = 0.3;
const Gravity = 8;
const MaxFall = 4;
const FastMaxAccel = 0.5;
const JumpHBoost = 0.1;
const JumpSpeed = -6;
const LiftBoost = 0.3;

function update() {
  let onGround = false;
  if (p.dy >= 0) {
    if (base.isSolid(0, 1)) {
      onGround = true;
    }
  }
 let maxDx = MaxRun;
  if (Math.abs(p.dx) > maxDx && Math.sign(p.dx) == inputX) {
    p.dx = mu.appr(p.dx, maxDx * inputX, RunReduce);
  } else {
    p.dx = mu.appr(p.dx, maxDx * inputX, RunAccel);
  }
  p.dx = mu.appr(p.dx, 0, DuckFriction);

  let maxFall = MaxFall;
  let mf = MaxFall;
  maxFall = mu.appr(maxFall, mf, FastMaxAccel);

  let maxDy = maxFall;
  p.dy = mu.appr(p.dy, maxDy, Gravity);

  if (onGround) {
    jGrace = JumpGraceTime;
  } else if (jGrace > 0) {
    jGrace--;
  }

  if (jBuffer > 0) {
    if (jGrace > 0) {
    let liftBoost = fLiftBoost();
    p.dx += JumpHBoost * inputX;
    p.dy = JumpSpeed;
    p.dx += liftBoost[0];
    p.dy += liftBoost[1];
    }
  }
}

As you can see there are a lot of tweakable parameters, and I don't even know if I need them or use them correctly.
Maybe I can configure these parameters through an interface and test my player there, but is that the best approach.
Currently using the above code, my movement sucks.
Can you suggest me the ultimate techniques to implement a juicy jump that can fit all sizes.


texts: Color change effect, with a sharp line separating the old & new colors

texts:
I want to achieve some sort of "transformation" effect in Unity while changing colors in a mesh.

For instance, when changing its color from red to blue, I have a line going around the mesh, where the part of the mesh on one side of the line is red and the other is blue. Over time, the line moves so the object is entirely blue.

From what I understand, I would need some sort of custom shader to do that? Or would I need some sort of animation? I really have no clue how to achieve this kind of effect so any tips are welcome.


texts:
OK, I have a 2d sprite in a scene and I would like to know the theory behind the camera orbiting around it with an analog stick.
I know the basic code to get the input from the gamepad, but I'm having trouble getting the desired result.
Basically, to simplify, the sprite is at the center of the screen. With the left analog stick I want to orbit the sprite between its a maximum distance (-1 or 1) and its minimum (0) around the centered sprite. It must be a simple thing to do, but I'm struggling with it.
Thanks in advance.


texts:
I'm making an Android game using LibGDX. I would like to render a cropped version of the camera's viewport.

Here's an original camera view (in 3ds max):

I can get the same view in LibGDX without any problems, with this code:

perspCam = new PerspectiveCamera(40, screenHeight, screenWidth * h / w);
perspCam.position.set(1, 6, 18f);
perspCam.lookAt(1, 3, -1f);
perspCam.update();

Now the tricky part: I actually want to see this view in-game:

It's basically just a crop of the camera viewport, keeping the original perspective and other camera properties.

Could someone explain the general concept? (No need for working code.)


texts: Singleton GameManager - instance loses refefrences after scene load

texts:
I've been looking around sample of a singleton gamemanager, like this from Unity's own page

if (instance == null)
        {
            instance = this;
        }
        else if (instance != this) // instance lost references
        {
            Destroy(gameObject); // this has the new references
        }

        DontDestroyOnLoad(gameObject);
}

I tried doing it the same way but after a LoadScene, the instance loses all of the GameObjects that I've referenced from the editor, which honestly makes sense to me (haven't used Unity much so I might have missed some lifecycle process or something) considering that everything else gets destroyed so the old instance would lose all of those reference while the new one, this, would have the fresh new references.

But also considering that nearly everyone is following this pattern and it seems to be working for them, what am I missing here?

I have no other code in an awake function, no coroutines and so- everything occurs right after the SceneLoad.

There is only one scene in the entire project and that's the scene that the game starts on and the scene that gets loaded after.


texts:
I've passed last 2 days reading articles and book for understand how can i make a plugin for iOS in Unity. Basically i need just a demo for understand how it work. For now i've tried to make this process (with really poor luck):

I've started a new project in Unity and writed a simple script

using UnityEngine;

using System.Collections;

using System;

using System.Runtime.InteropServices;

public class CallPlugin : MonoBehaviour {

    [DllImport ("__Internal")]

    private static extern int test();

    void Start ()

    {

        Debug.Log(test());

    }

}

Then i've created a project in Xcode with this simple script:

extern "C"{

    int test()

    {

       int che = 5;

        return che;

    }

}

Then i've tried:

to put the .mm and .h in the Assets/Plugins/iOS = nothing

to build the unity project and than add the .h and .mm in the Xcode project = nothing

In Unity i will always get the EntryPointNotFoundException, so unity see the file but is unable to reach the method. The problem is... how?! :)

Maybe i miss something or i've done something wrong?
Thanks a lot for every help that you can give me :)


texts:
I'm just trying to figure out the best approach for running a scolling background on an android device. The method I have so far.... its pretty laggy. I use threads, which I believe is not the best bet for android platforms

@Override
    public void run() {
        // Game Loop
        while(runningThread){
            //Scroll background down
            bgY += 1;

            try {
                this.postInvalidate();
                t.sleep(10);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

where postinvalidate in the onDraw function simply pushings the background image down

canvas.drawBitmap(backgroundImage, bgX, bgY, null);

Thanks in advance

UPDATE & SOLUTION

Thank you for everyone helping me. I came across this:

post https://stackoverflow.com/questions/1430741/how-to-draw-lots-of-bitmaps-on-screen-in-an-android-game-without-slow-performance

Helped my problem a lot. However, Seemed I was creating bitmaps in the onDraw every time is was caused, meaning that was doing 95% of the slowing down. oops :)

Below is my inner class in my surfaceview for reference purposes

class MapThread extends Thread{
    private Map map;
    private SurfaceHolder holder;
    private boolean run = false;

    public MapThread(Map map, SurfaceHolder holder){
        this.holder = holder;
        this.map = map;
        setRunning(true);
    }

    public void setRunning(boolean run){
        this.run = run;
    }

    @Override
    public void run(){
        while(run){
            try{
                Canvas c = null;

                 try {
                       c = holder.lockCanvas(null);
                       synchronized (holder) {
                            map.onDraw(c);
                     }
                 } finally {

                     if (c != null) {
                         holder.unlockCanvasAndPost(c);
                     }
                 }
        }
    }
}


texts: When should a game be announced to the public?

texts:
I'm not sure if this is where I should ask this as it might be opinion based so I apologize.

I am creating a game and I would like to know at what point in development I should reveal it to the public. An example would be posting on a forum about the language I am using, and having that post announce the game.

I am wondering how close to completion I should have the game before I begin to reveal it.

edit: Lets say that the game is a puzzle game similar to portal in style however without using a portal gun.


texts: What is the game design lingo for the computer's ability to render shiny water? I am new to game design and I'm trying to write a formal paper to a colleague.


texts: Activate and Deactivate Collider with Click

texts:
I'm having some trouble working with this, it's basically a sword that points toward your mouse position, and when you Left-Click, a Trigger Collider is activated and then deactivated, but I can't get it to work.

Here is my code :

void Attack()
{
    //Activates the Sword Collider
    polygonCollider2D.enabled = true;
    //Debug Line
    Debug.Log("Collider Active");
    StartCoroutine(Wait(0.1f));
    polygonCollider2D.enabled = false;
}

IEnumerator Wait(float seconds)
{
    yield return new WaitForSeconds(seconds);
}

I did it this way hoping that the Wait method would give the game enough time to react to an active collider, and using some Debug.Log(). I know that the collider actually activates, but it does not react to other colliders.

I keep wondering if this is the proper way of working with this. If it's not, do let me know.


texts: What is the logic behind the 'Loading' scenes in games?

texts:
I'm making my first game, it's a tower defense type of game, using Unity game engine and taking Fieldrunners as a reference. I would like to know more about the functionality behind 'Loading' scenes in games.

Until now I am instantiating/creating objects at run time and I'm not facing any delay or similar issues doing so. So what are 'Loading' scenes in other games used for? Is there some functionality or instantiation of specific objects for the next round or stage? If yes why do I need them if I'm not getting any delays?


texts: How do I rotate a single object in HLSL?

texts:
I have a World with a 3D model of a head in it and that World rotates, like such:

protected override void Update(GameTime gameTime)
{
    //other stuff

    angle += 0.00005f;

    //more other stuff
}

protected override void Draw(GameTime gameTime)
{
    //other stuff
    Matrix rotation = Matrix.CreateRotationY(3 * angle);
    effect.Parameters["World"].SetValue(rotation * Matrix.CreateScale(10.0f));

    // other stuff
}

And then in my Effects file I create a spotlight:

float4 SimplePixelShader(VertexShaderOutput input) : COLOR0
{
    float4 lightDirection = { 1, 1, 1, 0 };
    float theta = 10.0f;
    float phi = 30.0f;
    float4 color;
    float4 lambert = DiffuseColor * 0.2 * max(0, dot(input.Normals, input.lambertLightDir));

    float angle = acos(dot(input.lightDir, normalize(lightDirection)));
    if(angle > radians(phi))
        color = AmbientColor * AmbientIntensity;
    else if(angle < radians(theta))
        color = lambert;
    else
        color = max(AmbientColor * AmbientIntensity, smoothstep(radians(phi), radians(theta), angle) * lambert);

    return color;
}

And naturally this spotlight also rotates with the world. However, I dont want it to rotate. I tried everything, multiplying, adding, subtracting the rotation matrix and/or the angle from the different lightdirections and angles and nothing works.

Now I could rotate just the model and not the world, that would even be a sensible thing to do, but I have no clue how :P So I'm either looking for a good way to rotate the model or a way to 'counter rotate' the spotlight so it seems to stand still.

Edit: my vertexshader:

VertexShaderOutput SimpleVertexShader(VertexShaderInput input)
{
//some other vertexshaderstuff

    float4 lightPoint = {-3, -2, -2, 0};

    output.lightDir = normalize(input.Position3D) - lightPoint;

    output.lambertLightDir = float4(30, 30, 20, 0);

    return output;
}


texts: Should the modelview and projection matrices be calculated in the shader or on the CPU?

texts:
At minimum I would have a camera with rotation and world position; projections parameters such as angle of view and perspective vs. orthographic; and meshes with scale, angle, and world position.

When rendering a mesh I am wondering if I should calculate the final transformation matrix on the CPU and pass it to my shader, or if I should calculate the transformation matrix inside my shader.


texts: How do you implement Libgdx touchDragged?

texts:
I'm a beginner in Java and in Game Development too. I was following some tutorials, but now I'm stuck on implementing a touchDragged listener using libgdx,

Can anyone suggest how to drag the image when the user touches it and then move with the users finger position?

I am using both a stage and an actor. I want to catch a touchDragged event on an actor.

Thanks.

public void create () {
    Texture.setEnforcePotImages(false);

    stage = new Stage();
    Gdx.input.setInputProcessor(stage);
    // create a SpriteBatch with which to render the sprite
    batch = new SpriteBatch();

    // load the sprite's texture. note: usually you have more than
    // one sprite in a texture, see {@see TextureAtlas} and {@see TextureRegion}.
    texture = new Texture(Gdx.files.internal("ball3.png"));
    Skin skin = new Skin();
    skin.add("default", new Label.LabelStyle(new BitmapFont(), Color.WHITE));
    skin.add("ball", texture);
    Image sourceImage = new Image(skin, "ball");
    sourceImage.setBounds(50, 125, 100, 100);
    stage.addActor(sourceImage);

    // create an {@link OrthographicCamera} which is used to transform
    // touch coordinates to world coordinates.
    camera = new OrthographicCamera();

    // we want the camera to setup a viewport with pixels as units, with the
    // y-axis pointing upwards. The origin will be in the lower left corner
    // of the screen.
    camera.setToOrtho(false);
}

public void render () {
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();
    Table.drawDebug(stage);

    // if a finger is down, set the sprite's x/y coordinate.
    if (Gdx.input.isTouched()) {
        // the unproject method takes a Vector3 in window coordinates (origin in
        // upper left corner, y-axis pointing down) and transforms it to world
        // coordinates.
        camera.unproject(spritePosition.set(Gdx.input.getX(), Gdx.input.getY(), 0));
    }
}


texts: Top down 2d orthogonal view with 3D elements (Unity)

texts:
I've decided to give Unity a go with my project. I want to create a 2d RPG perspective world, but with elements of 3D mixed in.
So for instance, I think I might make trees and grass 3D, for this to work, the grass would have to realistically blend with the character (a 2d sprite) as they walk through it.
To be clear, I'm thinking of grass like you would see in a fully 3D game (like this).

As I understand it, the sprite objects (characters and whatnot) would need to maintain their rotation values whatever the rotation of the camera is. I don't plan on rotating the camera, the game would appear like a 2d game (2.5d is perhaps a more appropriate term) but in order to achieve the effect I want they would not be allowed to rotate in the camera's view.

I'm very new to Unity so I'm not quite sure where to start. I should also note I don't plan on making everything 3d, just particular objects like the ones mentioned.

Edit 06.05.16:

I'm not sure why I can't find anybody else with this problem solving it the way I am.
Here's a diagram of what I've implemented and it seems to work well:

The camera's Y axis is set to 45 degrees.
I'm not sure why but the number 1.418 works as the scaleY value for the camera's projection matrix. for making both sides appear as equally proportioned squares.

I don't see any distortion of textures, shadowing looks ok, the whole distorited 2d rpg perspective feels just right.

I'm a bit confused as I've seen some overly complex suggestions and solutions to this problem on google, but this seems to me to be the simplest and most appropriate solution, and I've not found anyone suggest it. Everything appears in proportion.
I assume I'm not aware of an important flaw in the solution because otherwise it would seem absurd other people wouldn't arrive at the same solution.

Regarding billboaridng - billboarding 3D movable sprites doesn't work well in 3d environments IMO, as they often will be tilted at a 45 degree angle and risk intersecting 3d objects:

http://answers.unity3d.com/questions/582680/billboard-issue-in-front-of-3d-object.html

Particularly tall sprites would be very problematic, unless the scenery was also tilted, like this screenshot from a Zelda game demonstrates:


texts: How to search for all uGui scripts in scene in the Unity editor?

texts:
I have many game objects whose properties I need to edit because of a bug/error.

However, this is very time consuming, because I need to check each game object one by one.

Is there any way to search for all game objects that (for example) contain uGui Scripts in a scene?