texts: How could one go about segmented sprite animation in Unity?

texts:
I've been exploring ways of designing characters and I'm interested in this technique. It's used in many retro games, mostly for bosses, like in Gunstar Heroes(Seven Force, that one Block guy from level 1), Castlevania(Talos) and Mischief Makers. It's used for the player character in the case of Yoshi's Story, Paper Mario and more recently Hardcore Mecha.
 Currently I'm aware of the Anima 2D system in Unity, however this is more directly mimicking 3d model functionality by warping the meshes as well, and doesn't seem to support spritesheets per limb.

I'm thinking of using individual quads per limb with their own spritesheets, would it be difficult to code my own sort of skeleton system?

For anyone still curious/confused to what im referring to, This technique was used fairly often in Castlevania games or games by the company Treasure.


texts: glutPostRedisplay() is not redrawing after updating model view matrix

texts:
I am trying to change the rotation of my object with keyboards, when I move the object in the direction of x, y or z it is okay, it is responding correctly. But when I try to change rotation, it does nothing at all.

void keypress(unsigned char key, int x, int y) {
Matrix R;
HomVector a;
switch(key) {
case 'x':
    cam.position.x -= 0.2f;
    break;
case 'X':
    cam.position.x += 0.2f;
    break;
case 'y':
    cam.position.y -= 0.2f;
    break;
case 'Y':
    cam.position.y += 0.2f;
case 'z':
    cam.position.z -= 0.2f;
    break;
case 'Z':
    cam.position.z += 0.2f;
    break;
case 'i':
    cam.rotation.x -=90.0f;
    R = RotationMatrix(-90, X);
    V = MatMatMul(V, R);
    PV = MatMatMul(P, V);
    break;
case 'I':
    cam.rotation.x += 90.0f;
    R = RotationMatrix(90, X);
    V = MatMatMul(V, R);
    PV = MatMatMul(P, V);
    break;
case 'j':
    cam.rotation.y -= 90.0f;
    R = RotationMatrix(-90, Y);
    V = MatMatMul(V, R);
    PV = MatMatMul(P, V);
    break;
case 'J':
    cam.rotation.y += 90.0f;
    R = RotationMatrix(90, Y);
    V = MatMatMul(V, R);
    PV = MatMatMul(P, V);
    break;
case 'k':
    cam.rotation.z -= 90.0f;
    R = RotationMatrix(-90, Z);
    V = MatMatMul(V, R);
    PV = MatMatMul(P, V);
    break;
case 'K':
    cam.rotation.z += 90.0f;
    R = RotationMatrix(90, Z);
    V = MatMatMul(V, R);
    PV = MatMatMul(P, V);
    break;
//case 'Q':
case 'q':
    exit(0);
    break;
}
glutPostRedisplay();

}

This is the code, my matrix is changing after multiplication, but does not respond to glutPostRedisplay() function. If there is a problem, I cannot see it, if anyone can help, that would be great!


texts: Does it make sense to use Lua scripting in a game developed in Python?

texts:
Well for C++ written games using Lua scripts for easy changing ai, quets etc is very reasonable and it's common. However now I'm going to write a game in pure python and I don't know if I should use Lua. Python itself is very high level script language. However, there are things to consider why I could use lua scripts:

Lua is commonly used for game scripting and other people who will work with me know Lua and don't know python
Python module to embed lua code into python uses very fast JIT compiler so the lua code actually would be much faster than python code (big plus for AI)
It would separate the game engine itself (Python) from the scripted logic (Lua)

Do python games use Lua? Is it a resonable thing or I should just stick to pure python? I need some advice because I have no idea.


texts: Light mask map and camera for static lights in XNA Platformer

texts:
Using the example for some basic light maps found here : http://blog.josack.com/2011/07/xna-2d-dynamic-lighting.html, I've managed to create a lightmap texture using individual lightmaps and display it over a 2D tiled world as in the Platformer example.

I'm using the very basic 2D camera example as found here : http://www.david-amador.com/2009/10/xna-camera-2d-with-zoom-and-rotation/, and the problem is that the lightmap texture scrolls with the player sprite. This looks pretty good and would be excellent for lighting the player sprite as it moves. But, I also want to be able to place static lights (or some initial position for the lights) that do not move with the player or camera.

When I turn off the camera or give it a static position, it works as a series of static lights so I believe it's probably caused by the camera transformation matrix following the player around. I'm using RenderTarget2Ds, one for the main game screen after all the backgrounds and tiles are rendered, and one for the "lightmap" which consists of a black background and a bunch of lighting textures which are merged with it using additive blending.

For now, I'm doing all of this in PlatformerGame.cs where the camera transformation and position is set and the level.Draw() call is made. I can't figure out how to separate the drawing of the lightmap and the camera following the player. I was thinking it would be better to render the shadows and lighting directly in the drawing of the level itself, but I'm not sure how to do that either because this technique requires RenderTarget2Ds and calling SpriteBatch.Begin()/End().


texts:
I have two ways of doing frustum culling taken from different web sources. First one takes 200ms to check 10k AABBs, second around 50ms for the same box count.
I read some forum answers, people say 0.5ms for 10k is ok but I'm totally far away from those numbers. So what am I doing wrong ?

Measuring time here:

        auto frustum = camera.getFrustum(); //frustum

        auto n = frustum.pNear;
        auto f = frustum.pFar;
        auto e = frustum.pExtra;

        ArrayList<Pair<vec3, vec3>> planes;
        ArrayList<vec3> v1;
        n.genVertices(v1);

        ArrayList<vec3> v2;
        f.genVertices(v2);

        planes << Pair<vec3,vec3>(v1[0], -n.genNormal());
        planes << Pair<vec3,vec3>(v2[0], n.genNormal());
        for(size_t i = 0; i < 4; i++)
        {
            planes << e[i];
        } //frustum planes array initialization done

        ArrayList<AABB> objs; //10k test aabbs
        for(size_t i = 0; i < 10000; i++)
        {
            objs << AABB(vec3(rand_float()/100,rand_float()/100,rand_float()/100),rand_float()/100);
        }

        auto t1 = timer.getTimeNanoSeconds(); //starting to measure
        for(size_t i = 0; i < 10000; i++)
        {
            rs::CollisionEngine::checkAABBAndFrustumFast(objs[i], planes);
        }
        auto t2 = timer.getTimeNanoSeconds() - t1; //getting time
        println("Collision check of 10k objs: "+ toString(t2/1000000) + " ms"); //printing time

Here is slow and fast collision checks:

 /**
    *
    * @param box
    * @return 0 - inside, 1 - intersects, 2 - outside
    */
    us checkAABBAndFrustumSlow(AABB box, ArrayList<Pair<vec3, vec3>>& planes)
    {
        ArrayList<vec3> vertices;
        box.genVertices(vertices);

        us totalIn = 0;

        for(int i = 0;i<6;i++){ //six planes for every frustum
            Pair<vec3, vec3> plane = planes[i];
            auto n = plane.v2;

            uint inCount = 8;
            uint pIn = 1;

            for(int j= 0;j<8;j++){
                vec3 v = vertices[j];
                vec3 toVertex = (v - plane.v1).normalize();
                float res = n * toVertex;
                if(res < 0){
                    inCount -=1;
                    pIn = 0;
                }
            }

            if(inCount == 0) return 2;
            totalIn += pIn;
        }

        if(totalIn == 6) return 0;

        return 1;
    }

    using namespace rs;
    vec3 getPosForFrustum(AABB b, vec3 n)
    {
            vec3 max = b.center + b.extent;
            vec3 p = b.center - b.extent;
            if (n.x() >= 0)
            p(1) = max.x();
            if (n.y() >=0)
            p(2) = max.y();
            if (n.z() >= 0)
            p(3) = max.z();

            return p;
    }

    vec3 getNegForFrustum(AABB b, vec3 n)
    {
        vec3 min = b.center - b.extent;
        vec3 p = b.center + b.extent;
        if (n.x() >= 0)
            p(1) = min.x();
        if (n.y() >=0)
            p(2) = min.y();
        if (n.z() >= 0)
            p(3) = min.z();

        return p;
    }

    uint checkAABBAndFrustumFast(AABB box, ArrayList<Pair<vec3, vec3>>& planes){

            uint result = 0;
            for(int i = 0;i<6;i++) {

                auto n = planes[i].v2;
                auto p = planes[i].v1;

                if (n * (getPosForFrustum(box, n) - p) < 0)
                    return 2;
                else if (n * (getNegForFrustum(box, n) - p) < 0)
                    result = 1;
            }

            return result;
    }

EDIT:
ArrayList is a custom vector like structure

Pair contains a copy of two objects it takes.


texts: Publishing a game on Google Play with a fake name

texts: I'm almost publishing my game to Google Play, but I wonder if I can use an fake name, I mean, not using a fake name with a real names, just some words like Lazer Dude or anything else, because I don't want to show who am I, I wanna keep my anonymously. There's no problem to use an fake name?


texts: How do I update the version of OpenGL on Windows so that I can use anything newer than the Version 1.1 header file that is included in the Platform SDK?  Even version 7.0A of the SDK for Windows 7 only includes GL.h and GLU.h for version 1.1 of OpenGL.  I've installed the NVidia driver for my board that includes OpenGL 4.1 support, but I don't see header files included in this package.


texts: Sending light data from Vertex Shader to Pixel Shader?

texts:
We have a pixel shader constant buffer that contains the light data for the item that is currently rendered.
To implement tangent space normal mapping, i would need to transform each light into tangent space.
Is it a valid approach to instead bind the light data to the vertex shader and then send the transformed Light Data to the pixel shader since the vertex shader runs less frequently than the pixel shader?
As a side note: I am using forward rendering with a limited light count.
Our pixel shader constant buffer looks like this:
struct RendererLight {
    float3 Position;
    float3 Color;
    float3 Direction;
    float Intensity;
    float In;
    float Out;
    float Range;
};

cbuffer LightsBuffer : register(b2)
{
    RendererLight Lights[8];
    uint NumLights;
};


texts: What are good questions for design interns?

texts:
I've recently been interviewing design interns and been pitching what I consider fairly easy practical design questions to measure their skill level. I've been shocked by poor quality of answers. Now this may be the quality of the applicants.

What questions do you ask an entry level games designer to probe for their skill level?


texts: XNA Deferred Shading, Replace BasicEffect

texts:
I have implemented deferred shading in my XNA 4.0 project, meaning that I need all objects to start out with the same shader "RenderGBuffer.fx". How can I use a custom Content Processor to:

Not load any textures by default (I want to manually do this)
Use "RenderGBuffer.fx" as the default shader instead of BasicEffect

Below is the progress so far

   public class DeferredModelProcessor : ModelProcessor
    {
       EffectMaterialContent deferredShader;

       public DeferredModelProcessor()
       {

       }

       protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context)
       {
           deferredShader = new EffectMaterialContent();
           deferredShader.Effect = new ExternalReference<EffectContent>("DeferredShading/RenderGBuffer.fx");

           return context.Convert<MaterialContent, MaterialContent>(deferredShader, typeof(MaterialProcessor).Name);
       }
    }


texts: Baked lightmap errors in adjacent polygons

texts:
Everything seems to work great, but in some parts of my model I get shadows like this

If I look at the light map, it looks bad:

What is the best approach to solve this issue?
Here my light settings:


texts:
I can't manage to rotate point around another point.

I did some searching around google and found algorithm that should work and it kinda does but it also moves the point I am rotating closer to pivot point.

Here is whole class where the problem is

public class Player {

float rotation;
Vector2 position;
Vector2 center;

public Player() {
    position = new Vector2(Core.WIDTH / 2 - 10, Core.HEIGHT - 50 - 10);
    center = new Vector2(Core.WIDTH / 2, Core.HEIGHT / 2);
    rotation = 0;
}

public void turnRight() {
    rotation += 0.001;

    position.x = (float) (Math.cos(rotation) * (position.x - center.x) - Math.sin(rotation) * (position.y - center.y) + center.x);
    position.y = (float) (Math.sin(rotation) * (position.x - center.x) + Math.cos(rotation) * (position.y - center.y) + center.y);
}

public void render(ShapeRenderer sr) {
    sr.circle(position.x, position.y, 20);
}

}


texts: SDL 2.0 OpenGL not drawing anything except background

texts:
My 'hello triangle' compiles well, no errors, but doesn't drawing anything. Here's my code:

main.cpp

#include "src/App.h"

int main( int argc, char* args[] )
{
    App app(600, 400, false);
    app.Run();
    return 0;
}

App.h

#ifndef APP_H
#define APP_H

#include <SDL.h>

class App
{
public:
    explicit App(size_t win_width, size_t win_height, bool fullscreen_mode)
            : m_window_width(win_width), m_window_height(win_height),
            m_fullscreen(fullscreen_mode) {
        };

     void Run();

private:
    void Draw();
    void Update(double dt);
    void Resize(size_t width, size_t height);
    void ProcessEvents();

private:
    size_t m_window_width;
    size_t m_window_height;
    bool m_fullscreen;
    bool is_done;
    SDL_Window* m_window;
    SDL_GLContext m_glcontext;
};

#endif // APP_H

App.cpp

#include "../App.h"
#include <SDL_opengl.h>
#include <cassert>

void App::Run()
{
    SDL_Init(SDL_INIT_VIDEO);
    m_window = SDL_CreateWindow("Okno gry",
                                SDL_WINDOWPOS_CENTERED,
                                SDL_WINDOWPOS_CENTERED,
                                m_window_width, m_window_height,
                                SDL_WINDOW_OPENGL | (m_fullscreen?SDL_WINDOW_FULLSCREEN:SDL_WINDOW_RESIZABLE));

    m_glcontext = SDL_GL_CreateContext(m_window);
    Resize(m_window_width, m_window_height);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);

    glClearColor(0, 0, 1, 0);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_EQUAL);

    is_done = false;
    size_t last_ticks = SDL_GetTicks();
    while(!is_done)
    {
        ProcessEvents();

        size_t ticks = SDL_GetTicks();
        double delta_time = (ticks - last_ticks) / 1000;
        last_ticks = ticks;

        if (delta_time > 0 )
        {
            Update(delta_time);
        }

        Draw();
    }
    SDL_Quit();
}

void App::Draw()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    glBegin(GL_TRIANGLES);
    {
        glColor3f(1, 1, 0);
        glVertex2f(1, 1);
        glVertex2f(0, 1);
        glVertex2f(0, 0);
    }
    glEnd();
    SDL_GL_SwapWindow(m_window);
}

void App::ProcessEvents()
{
    if (is_done) return;

    SDL_Event event;
    while (SDL_PollEvent(&event))
    {
        if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
        {
            Resize(event.window.data1, event.window.data2);
        }
        else if (event.type == SDL_QUIT)
        {
            is_done = true;
            break;
        }
    }
}

void App::Resize(size_t width, size_t height)
{
    m_window_width = width;
    m_window_height = height;

    glViewport(0, 0, static_cast<int>(width), static_cast<int>(height));
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glOrtho(0, 1, 0, 1, -1, 10);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void App::Update(double dt)
{
    //printf("%d", dt);
}

Can anyone help? I don't know why it's not running.


texts: Movement appears to be frame rate dependent, despite use of Time.deltaTime

texts:
I have the following code to calculate the translation required to move a game object in Unity, which is called in LateUpdate. From what I understand, my use of Time.deltaTime should make the final translation frame rate independent (please note CollisionDetection.Move() is just performing raycasts).

public IMovementModel Move(IMovementModel model) {
    this.model = model;

    targetSpeed = (model.HorizontalInput + model.VerticalInput) * model.Speed;

    model.CurrentSpeed = accelerateSpeed(model.CurrentSpeed, targetSpeed,
        model.Accel);

    if (model.IsJumping) {
        model.AmountToMove = new Vector3(model.AmountToMove.x,
            model.AmountToMove.y);
    } else if (CollisionDetection.OnGround) {
        model.AmountToMove = new Vector3(model.AmountToMove.x, 0);
    }

    model.FlipAnim = flipAnimation(targetSpeed);
    // If we're ignoring gravity, then just use the vertical input.
    // if it's 0, then we'll just float.
    gravity = model.IgnoreGravity ? model.VerticalInput : 40f;

    model.AmountToMove = new Vector3(model.CurrentSpeed, model.AmountToMove.y - gravity * Time.deltaTime);

    model.FinalTransform =
        CollisionDetection.Move(model.AmountToMove * Time.deltaTime,
            model.BoxCollider.gameObject, model.IgnorePlayerLayer);
    // Prevent the entity from moving too fast on the y-axis.
    model.FinalTransform = new Vector3(model.FinalTransform.x,
        Mathf.Clamp(model.FinalTransform.y, -1.0f, 1.0f),
        model.FinalTransform.z);

    return model;
}

private float accelerateSpeed(float currSpeed, float target, float accel) {
    if (currSpeed == target) {
        return currSpeed;
    }
    // Must currSpeed be increased or decreased to get closer to target
    float dir = Mathf.Sign(target - currSpeed);
    currSpeed += accel * Time.deltaTime * dir;
    // If currSpeed has now passed Target then return Target, otherwise return currSpeed
    return (dir == Mathf.Sign(target - currSpeed)) ? currSpeed : target;
}

private void OnMovementCalculated(IMovementModel model) {
    transform.Translate(model.FinalTransform);
}

If I lock the game's framerate to 60FPS, my objects move as expected. However, if I unlock it (Application.targetFrameRate = -1;), some objects will move at a much slower rate then I would expect when achieving ~200FPS on a 144hz monitor. This only seems to happen in a standalone build, and not within the Unity editor.

GIF of object movement within the editor, unlocked FPS

http://gfycat.com/SmugAnnualFugu

GIF of object movement within the standalone build, unlocked FPS

http://gfycat.com/OldAmpleJuliabutterfly


texts: How can I use triangle picking to determine location of a triangle in world space coordinates?

texts:
I am trying to implement point and click movement in my game, but at the moment I am stumped about how I can select parts of a mesh for the player to walk to.

So what I have done is I have got a navigational mesh in my game. I can select points from it but what I want to do is be able to select the navigational mesh in real time and be able to tell the player where to go on the navigational Mesh, how can I achieve this?

I thought triangle-picking might be one way to determine which mesh I am selecting with mouse-unproject but I think I need a bit more accuracy than that, no?

How can I achieve point and click on a navigational mesh in real time?


texts:
Question:

What am i doing wrong in the CalcShadowFactor method? It looks like the depth check is not working correctly.

Body:

I'm using deferred rendering in my engine and i have generated the following shadow map:

Which is draw by the following fragment:

void main()
{
    gl_FragColor = vec4(texture(gColorMap, TexCoord0).x);

}

The position texture is generated like this:

WorldPos0      = (gWorld * vec4(Position, 1.0)).xyz;

Where gWorld is the transformation of the object being draw(translation * rotation* scale)

Finally, in the light pass, i want to generate the shadow produced from this spotlight with the following code:

float CalcShadowFactor(vec3 WorldPos)
{
    vec4 ShadowCoord = gLightWVP  * vec4(WorldPos,1);
    ShadowCoord /= ShadowCoord.w;
    vec2 UVCoords;
    UVCoords.x = 0.5 * ShadowCoord.x + 0.5;
    UVCoords.y = 0.5 * ShadowCoord.y + 0.5;
    float z = 0.5 * ShadowCoord.z + 0.5;
    float Depth = texture(gShadowMap, UVCoords).x;
    if (Depth < z + 0.00001)
        return 0;
    else
        return 1.0;
}

It returns a float which multiplicates the color output. I know, im just returning 0 to set the color to complete transparent, it is intensional. The variables used were:

gLightWVP: It is the ProjectionView of the camare set at the light:

Projection * LightCameraRotation * LightCameraTranslation
WorldPos: It is the position got from the Position Texture:

vec3 WorldPos = texture2D( gPositionMap, TextCoord0 ).xyz;
gShadowMap: It is the shadow map texture sampler.

This is what is displayed(notice how the spotlight looks at the first image):

The engine passes are:

Shadow pass: Render the scene for every light using a alternative camera which is placed in their position with their orientation. It generates the shadow maps for every light. Currently i just have one shadow map for that spot light.
Render pass: It renders all the scene using the main camera. It generates the position map, normal map, diffuse map and a specular map.
Light pass: It uses all the textures generated to place the illumination. Here is where the shadow map is being checked for generate the shadows.

EDIT: I'll also leave here the shadow map texture definition.

glGenTextures(1, &m_shadowMap);
glBindTexture(GL_TEXTURE_2D, m_shadowMap);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, WindowWidth, WindowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

glBindFramebuffer(GL_FRAMEBUFFER, m_fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_shadowMap, 0);


texts:
I have created a platformer which currently has the features listed below. I would greatly appreciate any further ideas which I could implement! (I don't play a lot of games which is why I require help)

Walking/jumping/movement
player can shoot lasers
enemies also walk, fly, and shoot lasers
water (you can swim in this)
mud (slows you down on contact, and stops you from jumping)
ladders
damage when falling from a large height, unless falling into water
moving platforms
springboards (jumping on them shoot you into the air)
growing platforms (allow you to reach new places)
key and door system
gem and coin collection system
teleporting
turrets


texts: OpenVR IPD distance between eyes needed for masking in shaders

texts:
I have a Unity scene with OpenVR and Single Pass Stereo Rendering.

I need to do a fullscreen 3D masking effect in VR, based on reconstructed worldspace position from depth. I'm doing it using Graphics.Blit and a fullscreen quad.

This is what it looks like:

The problem is once you have the reconstructed world pos, you can't just say "everything past wpos.x==300 is black", because each eye will offset the mask and it appears like you're looking at it cross-eyed.

This is because the wpos.x==300 method does not take into account the Interpupillary Distance (IPD) between the two vr "cameras" rendering the scene. According to the unity docs there's a unity_StereoEyeIndex, and I used that to offset the eye ray for each eye by an arbitrary amount in camera space.

I can eyeball this offset using a float, but my question is how do you calculate it exactly? How do you make stereo masking shaders in VR?

[EDIT]

I haven't yet reverse-engineered the problem fully, and am still waiting for a full answer. But I have fixed it for now by avoiding Graphics.Blit() because it's too mysterious in VR, and instead used a sphere in the game world with a special material.

The shader I use is basically what @DMGregory did in this answer for his "Object in World" method. Note that you have to correct the depth sampling with this:

screenUV = UnityStereoTransformScreenSpaceTex(screenUV);
screenUV.y = 1.0f - screenUV.y;


texts: Why aren't the changes to the transform being applied?

texts:
I don't understand why this doesn't work. The code only acts when I press "Horizontal" buttons.
Here's the code:
using UnityEngine;
using Flycer.Helpers;

namespace Flycer.Controllers
{
    public class MovementNew : BaseController
    {
        #region ========== Variables ========

        [SerializeField] [Tooltip("Forward moving speed")] [Range(0, 1f)] float _forSpeed = 0.5f;
        [SerializeField] [Tooltip("Slide speed")] private float speedSlide = 10;
        [SerializeField] [Tooltip("Max slide distance")] private float maxSlide = 4;

        private Vector3 _curPos;
        float slide = 0;
        int i = 1;

        #endregion ========== Variables ========

        #region ========== Unity-time ========

        private void Start()
        {
            base.On();
            _curPos = transform.position;
        }

        private void Update()
        {
            if (!Enabled)
                return;

            if (Input.GetButton(Controls.Horizontal.ToString()))
                Moving();
        }

        private void FixedUpdate()
        {
            _curPos += new Vector3(0, 0, _forSpeed);
        }

        #endregion ========== Unity-time ========

        #region ========== Methods ========

        void Moving()
        {
            slide = Input.GetAxis("Horizontal") * speedSlide;

            _curPos.x += slide * Time.deltaTime;

            _curPos.x = Mathf.Clamp(_curPos.x, -maxSlide, maxSlide);

            transform.position = _curPos;
        }

        #endregion ========== Methods ========
    }
}

It doesn't move in any condition whether it has a RigidBody or not.


texts: Moving panel between two positions smoothly?

texts:
I'm trying to make my panel moving from one position to another one smoothly. What I get is more faster no matter what I did to make it slower never get slow !! Both Vector3.Lerp and Vector3.MoveTowards did not give me a slow movement. Here is my script:

public GameObject gunsWindow;
private Vector3 a, b;
public bool open; // use inspector
void Start()
{
    a = gunsWindow.transform.position;
    b = new Vector3(100.0f, gunsWindow.transform.position.y, gunsWindow.transform.position.z);
}

void Update()
{

    if(open)
    {
        gunsWindow.transform.position = Vector3.MoveTowards(a, b, Time.deltaTime * 1);
        //weaponPlane.transform.position =  Vector3.Lerp(a, b, Time.deltaTime); // panel shaking
    }
    else
    {
        gunsWindow.transform.position = Vector3.MoveTowards(b, a, Time.deltaTime * 1);
        //weaponPlane.transform.position =  Vector3.Lerp(b, a, Time.deltaTime); // shaking
    }

}


texts: How do I do selective water surface rendering?

texts:
I have a shader that renders the "texture" of a very realistic water on a tile in the 3D world using a Frame Buffer.

The problem is that, for example, I only want to render the part that isn't below the terrain, only for optimization. Does it make sense and how do I do that?


texts:
I am rendering bunch of cubes of unit size, but for some reason they look like they are squeezed a bit in the screen-space y axis. Why is this?

My projection matrix:

Projection = Matrix4.CreatePerspectiveFieldOfView (fovy, width / height, zNear, zFar);

My view matrix:

View = Matrix4.LookAt (position, position + Direction, up);

My Model matrix:

Matrix4 modelMatrix = Matrix4.CreateTranslation(new Vector3(chunkPos.X * 32, chunkPos.Y * 32, chunkPos.Z * 32));

Here's how I form the MVP matrix:

ViewProjection = View * Projection;
ModelViewProjection = Model * ViewProjection;

And finally the vertex shader:

gl_Position = mMVP * vertex;

Screenshots displaying the problem:

I tried to fix the problem by adding a y-axis scale of 1.5 to my View matrix, and it seems it helped a bit with the problem. The result:

The question

I want to understand why I have to scale it this way. I thought the aspect ratio I give to the CreatePerspectiveFieldOfView would do this correction for me.


texts: I installed Unity Hub 1.4.0 and it works well. For now I want to update the version of Unity. I need to install hub 2.0.0. But when I download the 2.0.0 hub and intsall it always link to 1.4.0 and I want the version Unity 2019.1.10f1. I can't find some uninstall files. How can I remove Hub 1.4.0?


texts:
I have a simple Sprite called Player that has the follow components (Transform, Sprite Renderer, Box Collider 2D, Rigidbody 2D, Player Controller Script). In my Player Controller script I want to update the player's position when a key is pressed.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    Vector2 playerPos;

    // Use this for initialization
    void Start () {

        playerPos = gameObject.transform.position;

    }

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

        if (Input.GetKey("d")) {

            playerPos = new Vector2(playerPos.x + 0.2f, playerPos.y);

        }

    }
}

This script is attached to my gameobject but whenever I press or hold down the 'd' key, nothing happens to the player. Does anyone know how to fix this?


texts:
I have question about game UI. Im using only one Screen class in my game and for different "screens" Im using gamestates. My question is how to set stage with buttons (play button, pause button, restart button) with custom listeners for each state? for example my play button should have 2 different listeners. First of them start the game if gamestate = menu and second unpause game when gamestate = pause.

What should I do ? make one playButton with "if" operator for different game states? or make two different playButton? and what with table? add all the buttons to one table and clear table each time when game state is changing? or make a few tables?


texts: I have got 2 Points in 3D Space whose TRS Matrix' from 0.0 to there current place is known. Now I want to change the Matrix of the left point so that the matrix of the right point combined with the new Matrix results in the point being at the same position as before. Here a short illustration that I hope helps a little. Sorry for the bad explanation


texts: I have an object(FBX format) in my project, it's a line drawn in 3D max. I want to color the line in XNA so that the color starts from a specific RGB color in both the start and end points of the line and finish in a specific RGB color.(e.x., from (255,255,255) to (128,128,128). Something like gradient coloring of an object. I need to do that programmatically, since later in my code I have to change these two specific colors a lot.


texts:
Noobie here...
I've started learning monogame development and currently working on a simple snake game. I'm having trouble with the snake's movement, I figured I could make it tile-based movement but eventually decided to create turning points everytime the head changes direction, insert those into a list and remove a point when the last body unit have passed through it.

The method that gets keyboard input and creates the turning points:

 protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();
        player.update();
        if (Keyboard.GetState().IsKeyDown(Keys.Up) || Keyboard.GetState().IsKeyDown(Keys.Down))
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Up))
                player.direction.Y = -3f;
            else
                player.direction.Y = 3f;
            player.direction.X = 0;
            /**
             * Creating a turnPoint that will save the change in movement
             * and where it occured.
             * **/
            player.turnPoint.Add(new Player.turningPoint(player.position, player.direction));
            return;
        }
        if (Keyboard.GetState().IsKeyDown(Keys.Left) || Keyboard.GetState().IsKeyDown(Keys.Right))
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Left))
                player.direction.X = -3f;
            else
                player.direction.X = 3f;
            player.direction.Y = 0;

            player.turnPoint.Add(new Player.turningPoint(player.position, player.direction));
        }

        base.Update(gameTime);
    }

GameObject which is used as the snake's tail basically consists of 2 Vectors, one for position, the other for movement direction.

 public struct turningPoint // Used to save the point and specific change in movement
    {
        public Vector2 location { get; }
        public Vector2 velocityChange { get; }

        public turningPoint(Vector2 location, Vector2 velocityChange)
        {
            this.location = location;
            this.velocityChange = velocityChange;
        }
    }
    public List<turningPoint> turnPoint = new List<turningPoint>();
    private List<GameObject> bodyUnits = new List<GameObject>();

And finally, the method in whic I update the body units:

        private void updateBodyUnits()
    {
        for(int i = 0; i < bodyUnits.Count; i++)
        {
            //Update the unit's position using it's current movement direction
            bodyUnits[i].position.X += bodyUnits[i].direction.X;
            bodyUnits[i].position.Y += bodyUnits[i].direction.Y;

            foreach(turningPoint point in turnPoint)
            {
                if(bodyUnits[i].position.X == point.location.X && bodyUnits[i].position.Y == point.location.Y)
                {   //If the unit is currently on a specific turning point, change it's direction
                    bodyUnits[i].direction.X = point.velocityChange.X;
                    bodyUnits[i].direction.Y = point.velocityChange.Y;

                    if (i == bodyUnits.Count - 1) //Remove turn point if the last
                                                  //unit passed through
                        turnPoint.Remove(point);
                    break;
                }
            }
        }
    }

Basically it kinda works, if the movement the snake is low. If I set direction. X\Y to 1, or 2 even it kinda works, but above that it seems as if the units just speed through the turning point, ignoring it (and currently there just the head with 3 units of tail).
So, is my code ridiculously inefficient? Or the method I am using is wrong altogether?


texts: Rotate canvas along its center based on user touch - Android

texts:
I want to rotate the canvas circularly on its center axis based on user touch.

i want to rotate based on center but its rotating based on top left corner .

so i am able to see only 1/4 for rotation of image.

any idea..

Like a old phone dialer .

I have tried like as follows

onDraw(Canvas canvas){
  canvas.save();
  // do my rotation
  canvas.rotate(rotation,0,0);
  canvas.drawBitmap( ((BitmapDrawable)d).getBitmap(),0,0,p );
  canvas.restore();
}

@Override
        public boolean onTouchEvent(MotionEvent e) {
                  float x = e.getX();
              float y = e.getY();
              updateRotation(x,y);
              mPreviousX = x;
              mPreviousY = y;
            invalidate();
        }

  private void updateRotation(float x, float y) {

          double r = Math.atan2(x - centerX, centerY - y);
            rotation = (int) Math.toDegrees(r);
        }


texts: How to avoid singleton pattern for Event Scheduler?

texts:
I want to make an Event scheduler for my Game, I basically want to be able to schedule the triggering of a Game Event. This can be a one time trigger, or a periodic trigger (trigger event "E_BIG_EXPLOSION" on a 5 seconds basis...).

It is tempting to think that this may be a good place to use a Singleton, but singletons can be quite evil and they tend to spread like a disease... so I try to avoid them at all cost.

What design would you propose to avoid the singleton usage in this case?


texts: How can I fix user input for this pong paddle?

texts:
I have been having trouble with my pong paddle - It responds to user input as if it was typing.

  Sometimes, people try to react to KeyPressed events directly to implement smooth movement. Doing so will not produce the expected effect, because when you hold a key you only get a few events (remember, the repeat delay). To achieve smooth movement with events, you must use a boolean that you set on KeyPressed and clear on KeyReleased; you can then move (independently of events) as long as the boolean is set.
  The other (easier) solution to produce smooth movement is to use real-time keyboard input with sf::Keyboard (see the dedicated tutorial). - http://sfml-dev.org/tutorials/2.1/window-events.php

I would like to figure out the 2nd option to keep my code neat. What should I be doing differently to achieve this? I already visited the tutorial, dug around in the docs for a while, and Googled it, but such things seem to be futile (am I missing something obvious?).

My Ball Move code (in the event loop):

float deltaTime = deltaTimer.restart().asMilliseconds();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
            {
                playerPaddle.move(0 , -paddleSpeed * deltaTime);
            }

My full code:

#include <SFML/Graphics.hpp>

int main()
{
 sf::RenderWindow window(sf::VideoMode(600, 400), "Pong");

bool isPlaying = true; //set to true only for debugging
int spacing = 3; // the distance from edge of board to paddle.
int paddleSize = 90;
float paddleSpeed = 0.1;

sf::Clock deltaTimer;
//load the background sprite
sf::Texture backgroundTexture;
backgroundTexture.loadFromFile("assets/images/Background.png");
sf::Sprite background;
background.setTexture(backgroundTexture);

sf::RectangleShape paddle(sf::Vector2f(10,paddleSize)); //10*90 rectangle
paddle.setFillColor(sf::Color(128,128,128));
paddle.setPosition(spacing,0);

sf::RectangleShape playerPaddle(sf::Vector2f(10,paddleSize)); //10*90 rectangle
playerPaddle.setFillColor(sf::Color(128,128,128));
playerPaddle.setPosition(window.getSize().x - playerPaddle.getSize().x - spacing , 0 );

sf::RectangleShape pongBall(sf::Vector2f(10,10));
pongBall.setFillColor(sf::Color(200,200,200));
pongBall.setPosition(20,20);

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

        if (isPlaying)
        {
            float deltaTime = deltaTimer.restart().asMilliseconds();
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) //sf::Keyboard::isKeyPressed(sf::Keyboard::Up)
            {
                playerPaddle.move(0 , -paddleSpeed * deltaTime);
            }
            if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
            {
                playerPaddle.move(0 , paddleSpeed * deltaTime);
            }

            if (playerPaddle.getPosition().y < 0 )
            {
                playerPaddle.setPosition(playerPaddle.getPosition().x , 0);
            }
            else if (playerPaddle.getPosition().y > window.getSize().y - paddle.getSize().y )
            {
                playerPaddle.setPosition(playerPaddle.getPosition().x , window.getSize().y - paddle.getSize().y );
            }
        }
        else
        {

        }
    }

    window.clear(sf::Color::Black);
    //window.draw();
    window.draw(background);
    window.draw(paddle);
    window.draw(playerPaddle);
    window.draw(pongBall);
    window.display();
}

return 0;

}


texts: Unity3D, voxel chunk mesh modification: Further performance improvements

texts:
I've flattened my 3D chunk array(Got nice 20ms speed up), modified my VertexData struct (that I use in Dictionary as a key) to have custom hashcode(another 20ms and -2.7mb GC.alloc data speedup). But I'm not sure what to do next, since 40ms still feels long for such a small chunk(In fact, its twice smaller the size of Minecrafts 16x256x16 and still managing to be slower.).

My biggest bottleneck still seems to be the dictionary.

This is current performance profile:

The code:

public void MakeChunk()
    {

        vertexCount = 0;
        //these are all Lists except verticesDictionary
        vertices.Clear();
        normals.Clear();
        verticesDict.Clear();
        uvs.Clear();
        triangles.Clear();

        int len = 32 * 32 * 32;

        for (int i = 0; i < len; i++)
        {
            int cubeType = data.raw[i];
            if (cubeType != 0)
            {
                int x = i % 32;
                int y = (i / 32) % 32;
                int z = i / (32 * 32);
                MakeCube(x, y, z, cubeType);
                blocksGenerated++;
            }
        }
    }
    void MakeCube(int x, int y, int z, int cubeType)
    {
        for (int i = 0; i < 6; i++)
        {
            Direction dir = (Direction)i;
            if (data.GetNeighbor(x, y, z, dir) == 0)
            {
                MakeFace(dir, x, y, z, cubeType);
            }
        }
    }
    void MakeFace(Direction dir, int x, int y, int z, int cubeType)
    {
        VertexSignature signature;
        signature.normal = dir;

        Vector3[] faceVertices = CubeMeshData.faceVertices((int)dir, x, y, z);
        int[] triangleIndices = new int[4];
        signature.cubeType = cubeType;

        for (int i = 0; i < 4; i++)
        {
            signature.position = faceVertices[i];
            Vector3 uv = CubeMeshData.ProjectPositionToUV(signature.position, dir);
            uv.z = signature.cubeType;

            int vertex = GetVertexIndex(signature);
            triangleIndices[i] = vertex;
        }

        triangles.AddRange(new int[6] {
            triangleIndices[0],
            triangleIndices[1],
            triangleIndices[2],
            triangleIndices[0],
            triangleIndices[2],
            triangleIndices[3]
            }
        );

    }
    void PrepareMeshData()
    {
        foreach (var pair in verticesDict)
        {
            int index = pair.Value;
            vertices.Add(pair.Key.position);
            CubeMeshData.DataCoordinate coord = CubeMeshData.offsets[(int)pair.Key.normal];
            normals.Add(new Vector3(coord.x, coord.y, coord.z));

            Vector3 uv = CubeMeshData.ProjectPositionToUV(pair.Key.position, pair.Key.normal);
            uv.z = pair.Key.cubeType;
            uvs.Add(uv);
        }
    }

Hashing:

 struct VertexSignature
    {
        public Vector3 position;
        public Direction normal;
        public int cubeType;

        public override int GetHashCode()
        {
            uint h = 0x811c9dc5;
            h = (h ^ (uint)position.x) * 0x01000193;
            h = (h ^ (uint)position.y) * 0x01000193;
            h = (h ^ (uint)position.z) * 0x01000193;
            h = (h ^ (uint)normal) * 0x01000193;
            h = (h ^ (uint)cubeType) * 0x01000193;

            return (int)h;
        }
    };

Then I do this:

    Vector3[] vertexArr = vertices.ToArray();
    int[] triArr = triangles.ToArray();
    Vector3[] normalsArr = normals.ToArray();

I've really run out of ideas on how to improve performance further.

Any help is welcome.


texts: Control convention for circular movement?

texts:
I'm currently doing a kind of training project in Unity (still a beginner). It's supposed to be somewhat like Breakout, but instead of just going left and right I want the paddle to circle around the center point. This is all fine and dandy, but the problem I have is: how do you control this with a keyboard or gamepad? For touch and mouse control I could work around the problem by letting the paddle follow the cursor/finger, but with the other control methods I'm a bit stumped.

With a keyboard for example, I could either make it so that the Left arrow always moves the paddle clockwise (it starts at the bottom of the circle), or I could link it to the actual direction - meaning that if the paddle is at the bottom, it goes left and up along the circle or, if it's in the upper hemisphere, it moves left and down, both times toward the outer left point of the circle.

Both feel kind of weird. With the first one, it can be counter intuitive to press Left to move the paddle right when it's in the upper area, while in the second method you'd need to constantly switch buttons to keep moving.

So, long story short: is there any kind of existing standard, convention or accepted example for this type of movement and the corresponding controls? I didn't really know what to google for (control conventions for circular movement was one of the searches I tried, but it didn't give me much), and I also didn't really find anything about this on here. If there is a Question that I simply didn't see, please excuse the duplicate.


texts: Should my game handle collisions in the Player object?

texts:
I'm making a 2D platform game. Right now I'm just working on making a very generic Player class. I'm wondering if it would be more efficient/better practice to have an ActionListener within the Player class to detect collisions with Enemy objects (also have an ActionListener) or to handle all the collisions in the main world.

Furthermore, I'm thinking ahead about how I will handle collisions with the platforms themselves. I've looked into the double boolean arrays to see which tiles players can go to and which they can't. I don't understand how to use this class and the player class at the same time.


texts: Unity - Array of custom class with a superclass using generics does not show in the inspector

texts:
I want to create 2 classes for Scriptable Object: Weapon and Armor. Because both have similar functionality, I made a base class for both of them.

using UnityEngine;

public abstract class Gear<T> : ScriptableObject{

    public int price;
    public int level;
    public Sprite image;

    [Header("Levels List")]
    public T[] levels;

    public T CurrentLevel() {
        return this.levels[this.level];
    }

    public T NextLevel() {
        return this.levels[this.level + 1];
    }

    public bool UpgradesLeft() {
        return this.level + 1 < this.levels.Length;
    }

    public void Reset() {
        this.level = 0;
    }

    public bool Upgrade() {
        if (!this.UpgradesLeft()) return false;
        this.level++;
        return true;
    }
}

[System.Serializable]
public abstract class StatsLevel {
    public int price;
}

Both weapons and armors have the properties in common like they all have a price, they all have a Sprite Image, and so on... and more importantly they all have an array of Stat Levels. Meaning that every armor or weapon can have different levels, and depending on their level, the stats will be different. For that I used Generics.

So when I created the Armor, I did it this way:

using UnityEngine;

public enum ArmorStat { Low, Med, High, Super }

[CreateAssetMenu(fileName = "Armor", menuName = "NARG/Armor", order = 1)]
public class Armor : Gear<ArmorStatsLevel> {
    // Armor custom logic
}

[System.Serializable]
public class ArmorStatsLevel : StatsLevel {
    public int weight;
    public ArmorStat blunt, slash, range;
}

in this class I define the stats unique to an Armor. Up to here everything looks peachy. But the issue comes with the Inspector:

As you can see, the inspector is not showing the array with the list of Stats on different levels, and I after a lot of research, I think it has to do with the Generics. If instead of unifying the common code between Armor and Weapon on the Base, I duplicate it each subclass, the Array is shown without problem.

How could I make it so that the array information is shown in the inspector?


texts: Can I used a NES USB controller with XInput?

texts:
I'm doing a project to graduate from my game design degree and I have to recreate two levels from MegaMan(1987).
I saw that there are usb nes controllers out there that are used for emulators on PC.  Before I purchase them and try out programming my game with them, I'd like to confirm that I can use them with Xinput.

If anyone knows if this is possible, please let me know!

Thank you!


texts: How are the Unreal Development Kit (UDK) and Unreal Engine 4 (UE4) related?

texts:
I'm thinking of learning Unreal Engine 4, but it costs money, and I want to try and keep costs as low as possible while I'm learning. In contrast, the Unreal Development Kit is free.

How similar are the two? If I learn UDK first, how easily can I transition to UE4?


texts:
I'm trying to create a falling word typing game like z-type.

I have used the code provided here — but it's is only for keyboards:

public class WordInput : MonoBehaviour {

    public WordManager wordManager;

    void Update () {

        foreach (char letter in Input.inputString)
        {
            wordManager.TypeLetter(letter);
        }
    }
}

I want to implement this on mobiles as well. So I have created a mobile keypad using a canvas and buttons for alphabets but I'm unable to link it to words shown on the screen.


texts: Is it a good idea to develop non-trivial 2d game in python?

texts:
I am planning to develop 2D space RPG and i am facing the choice: what is the best language to write it in? My candidates are C++, Java and Python. Obviously, I want to write game in Python because of its expressiveness, speed of development and simplicity of adding scripting support. But I am worried:

Won't Python be too slow? The game will be not trivial (like Tetris for example), it may be needed to calculate tasks for thousands of ships in universe (though their AI can be heavily simplified if those ships are not seen to the player). Of course I can write some critical parts in C, but it will instantly complicate building and deploying.
Let's suppose that game became popular, and I became a superstar. Windows users rarely have Python at all (fortunately we have py2exe). Python on Mac OS X can be outdated and game may crash with obscure exception. Wouldn't it be hard to deploy game in Python?
Because of lack of libraries for Python 3 I'll have to write game in Python 2. Wouldn't transition to Python 3 in couple of years be too painful and time consuming?


texts: Positioning a texture inside a 3D object with GLSL

texts:
I have a 3D object in my scene and a texture that is the same size of the screen (a render to texture). Is there a way to make the object act like a "mask" for the texture(using glsl), so the texture is aligned with the screen 2D space but only shows what is "inside" the mask object?

What I'm trying to achieve here is this: I have a 3D scene made of cubic tiles, some of these tiles are going to be water and I want to distort whatever is behind them. My idea was to pass the render to texture and then distort it to make a refraction effect. Is this going to work? Am I even suposed to do refraction like this?


texts:
I'm doing a android game project that has a character that can do basic movements like step, turn left, turn right, raise left arm etc. When combining those moves together, the character can do some complicated movements like a dance routine or so.

I'm banging my head to figure out what to do about the graphics. I can do a 3D model with animation then export it to the format of Bones library that displays the character movements. Like shows in this video. I wish to have different characters with different characteristics like height, clothes colour and such. However, that means I have to stock pile more 3D models that have different settings.

Alternatively, I can attempt to code from scratch that have bones system, meshes, skinning, animation. More control and flexibility but the appearance won't be as good as 3D model and it takes alot more afford (as it appears to me). The character will be in 2D if I go down this route. I will use Android OpenGL library for this.

I thought of 2D but then I realize that it's pretty similar to 3D option.

My question is that what can I do here? What else I can do to make the best of this situation?

Edit: thanks for the comments and answer but I have sorted my "dilemma" now. Im using jpct-ae and bones library for my project. The downside is that I need to use a 3D model to make use of those library. They are actually very good and suitable for my need when working with a 3D model. Cheers.


texts: Efficient modification of Texture2D at runtime for a 2D painting game in Unity3D

texts:
I have spent some time looking for different solutions to be implemented in a mobile painting game I'm creating.  At this time, everything is working but I have some serious performance problems on large screens and slow devices because I massively use setPixel / setPixels and apply on Texture2D.

I have come across 2 ways to speed things up:

1) Tile the image in small chunks, every chunk would be a Texture2D, and just upload (calling Texture2D.Apply()) the modified chunks.

2) Another trick I could apply on top of the tiling solution is to catch changes in an array and write them down to the needed Texture2D chunk and apply it every X miliseconds if modified.

I would like to know what other optimizations I could apply to this subject.  Perhaps I should throw setPixel away and go with another more efficient way?

Cheers.


texts: Detecting a 3 x 3 grid and extracting its coordinates using Kinect

texts:
I'm interested in creating a DDR (dance dance revolution) game using unity3D and Kinect. However I need to do this without actually using a pressure sensor pad, just a mat with grids and numbers on it.

Here is what the Grid is supposed to look like:

I need to be able to track where the Mat is placed on the floor and a way to check which number is the user stepping on. The user feet coordinates can be tracked via skeletal tracking, however the grid coordinates and boundaries need to be extracted.

Is there a way to do this without using openCv and can opencv be used with Kinect and unity3d?


texts:
We have two main subclasses of GameInfo for the two game types we have. I'm wondering if it's possible to get one of these to read a different .ini file because we'd like to move a few of the controls to different buttons for that mode.

It looks to me like it's just going to read Input.ini for this, regardless of the game type.


texts:
I am making a simple 3D game with plane in space.
With c++ (win32).
But the plane rotation is not realistic.
The code I am using for the rotation is the following:

point3D AxisRotation(point3D point,point3D Rotation){
float sx = Sin(Rotation.x*PI/180);
float cx = Cos(Rotation.x*PI/180);
float sy = Sin(Rotation.y*PI/180);
float cy = Cos(Rotation.y*PI/180);
float sz = Sin(Rotation.z*PI/180);
float cz = Cos(Rotation.z*PI/180);
float xy,xz, yx,yz, zx,zy;
xy = cx*point.y - sx*point.z;
xz = sx*point.y + cx*point.z;
yz = cy*xz - sy*point.x;
yx = sy*xz + cy*point.x;
zx = cz*yx - sz*xy;
zy = sz*yx + cz*xy;
point.x = zx;
point.y = zy;
point.z = yz;
return point;}

The axis of the rotation needs to be (Roll,Yaw,Pitch).
Does anyone know the code or the math for it ?
Thank you. Dave


texts: How can I cleanly and elegantly handle data and dependancies between classes

texts:
I'm working on 2d topdown game in SFML 2, and need to find an elegant way in which everything will work and fit together.

Allow me to explain. I have a number of classes that inherit from an abstract base that provides a draw method and an update method to all the classes.

In the game loop, I call update and then draw on each class, I imagine this is a pretty common approach. I have classes for tiles, collisions, the player and a resource manager that contains all the tiles/images/textures. Due to the way input works in SFML I decided to have each class handle input (if required) in its update call.

Up until now I have been passing in dependencies as needed, for example, in the player class when a movement key is pressed, I call a method on the collision class to check if the position the player wants to move to will be a collision, and only move the player if there is no collision.

This works fine for the most part, but I believe it can be done better, I'm just not sure how.

I now have more complex things I need to implement, eg: a player is able to walk up to an object on the ground, press a key to pick it up/loot it and it will then show up in inventory. This means that a few things need to happen:

Check if the player is in range of a lootable item on keypress, else do not proceed.
Find the item.
Update the sprite texture on the item from its default texture to a "looted" texture.
Update the collision for the item: it might have changed shape or been removed completely.
Inventory needs to be updated with the added item.

How do I make everything communicate? With my current system I will end up with my classes going out of scope, and method calls to each other all over the place. I could tie up all the classes in one big manager and give each one a reference to the parent manager class, but this seems only slightly better.

Any help/advice would be greatly appreciated! If anything is unclear, I'm happy to expand on things.


texts: I'm working on a particle system using transform feedback, and I would like to know if it is possible to render to anything other than floats, like halfs, using Transform Feedback (OpenGL 3.3)? It would save some bytes and possibly speed up the process a little bit.


texts: Programmatically creating billboards in unity

texts:
What is the most efficient way to render a billboard in Unity?

In order to apply a texture to something must it be a GameObject with a Mesh component?  In which case, is my best bet to create a prefab of a Plane with the given texture and Instantiate(...) it at runtime? Or is there some sort of "billboard" primitive I should use instead?


texts: How can I read the color of a specific pixel in XNA?

texts: I want a way to find out if, for example, the pixel at Vector2(2, 5) on the game window is color Color.Red, or some other color or set of coordinates. How can I do this?


texts: Problem displaying drawing of a path in camera/viewport

texts:
I have an adm object, which draws the path in the room like this (Object ADM - Draw Event):

draw_set_color(c_black);

repeat(5){
    repeat(5){
        draw_path(circuito_australia,684+i,568+j,false);
        j+=1;
    }
    i+=1;
    j=0;
}

i=0;
j=0;

Result:

I created 2 viewports, to more closely display specific cars:

And this problem happens, parts of the circuit in the view of these cameras are wrong/bugged:

The reason I know (or at least I imagine) is because I'm taking a part of the room and doubling its display.

Any ideas on how to get around this?


texts: "DirectX will only draw polygons with an [X,Y] from [-1,-1] to [1,1] and with a Z from 0 to 1.", What does this mean and how to work around it?

texts:
I've been following the D3D11 tutorials on Rastertek to expand my knowledge on rendering which I will need as I want to build my own engine, as a hobby.

After finally getting a model to be rendered to the screen in 3D space, and being able to move and rotate both the camera and the model, I wanted to import custom FBX models instead, which isn't included in the tutorial. I found this tutorial online on just that, which I followed alongside the fbx SDK's documentation.

It now works to load and render FBX models, however, the vertices are quite messed up on some models, and on some, it works perfectly, then I read in the tutorial, and I quote:

"Finally, if you don’t use the shitty-bell FBX attached up at the top of this post, take note. In its default state, DirectX will only draw polygons with an [X,Y] from [-1,-1] to [1,1] and with a Z from 0 to 1. Look through the vertices in your FBX and make sure everything is in that range!"

As you can guess, that "shitty bell" works perfectly to draw. Anyway, what does it mean that it'll draw polygons within that range, also, how do I work around that when modeling?


texts:
I am trying to do some post processing on my 3d scene. When I render directly to the screen edges are sharp, however when I render my scene to an offscreen FBO then render that to a texture that is then drawn to the screen I get strange Z-fighting around object edges. Any Idea how this can be resolved?

The resolution of the FBO image seems to be worse in some places too, however the FBO size is set to the window width and height.

Thanks!

Direct Rendering

FBO rendering

Depth Buffer Code

private int createDepthBufferAttachment(){
    depthTexture = Game.textureManager.genTexture();//call to GL11.glGenTextures()
    GL11.glBindTexture(GL11.GL_TEXTURE_2D, depthTexture);
    GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL14.GL_DEPTH_COMPONENT16, Game.WIDTH, Game.HEIGHT, 0, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, (ByteBuffer) null);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
    GL32.glFramebufferTexture(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, depthTexture, 0);

    return depthTexture;
}


texts:
When simulating an airplane and a missile, to get them moving in the air we apply a force in one direction. Now an airplane has wings that keeps it afloat while a missile can have fins to stabilize it. In both cases when the force is no longer strong enough, the velocity reduces and the projectiles are bound to succumb to gravity. When that happens, the projectiles naturally don't fall directly to the ground disregarding rotation and other spins based on air resistance and whatever momentum there is left.

My question is, to simulate such behavior how would the Bullet, Nvidia PhysX and Havok physics libraries compare against each other especially with emphasis to the following?

Gravitational pull and momentum acting on the projectiles.
Air resistance acting on the projectiles.
Both 1 and 2 above's behavior can be based on varied levels of a central forward force applied on the projectiles.


texts:
So I have set up a Swept test for AABB vs Line Collision that works fine, now the problem is that I have to deal with acute corners, where this happens:

As you can see the AABB just falls through the bottom Line, when it should stop.

I have been trying to do this for a month now, and I can't find any solution at all.

Why does this happen and how do I fix it?

Project: http://murplyx.net/sss - Move with WAD and draw lines with mouse

Source Code: http://murplyx.net/sss/js/main.js and http://murplyx.net/sss/js/vec.js


texts:
I'm new to libgdx and especially to using OrthographicCameras. I'm trying to understand how useful they are.

The question is, suppose I have a game map 500 units wide. I have an OrtographicCamera vith a viewport of 50x50. Now If I use SpriteBatch to draw texture of my game map as 500 units (I set projection matrix to cameras combined matrix) and move the camera around as the character moves, is this a right practice to do? If that map is 20000 pixels wide (an entire level for a platformer for example), is this really the way to go? Or should I make my camera and render logic myself (render only part of the map according to current coordinates of the character)? If I need to do this myself, what's moving the camera useful for?


texts: Filter game data according to player unlocks

texts:
I'm currently developing an online "empire management" style game in HTML and Node. Along the game, the player will be able to raise resources (by creating farms, mines, raiding) to unlock new structures and rare items, etc. The same old drill.

All game data is in a server-side file which gets called and processed before sending to the player.

Now, when I serve the game data (containing information on building costs, paths to all imagery, etc) over to the client, I took a good care to filter it accordingly to the player's unlocked features (so to avoid people fiddling in the client-side code and getting access to the whole game data). I didn't really think about it when I made this, it just seemed "natural" to hide locked content. But now it is becoming a bit hard to keep data synced when the player starts to unlock stuff. I just regret this a bit and I'm starting to think it's not worth the hassle.

Now some questions arose in my mind: what is the usual approach to this? Do this kind of games usually send everything (which increases sightly bandwidth usage) or pre-process like I did (which increases server load)? Would it hurt the game experience somehow, especially considering many games have their own wikis nowadays?

(note that this is more of a concept question rather than technical)


texts: How do I create a 3D model based on 2D drawings?

texts:
I'm a programmer. I have a great draftsman, but I don't know how to take his drawings to 3D.

My gut feeling is to have him draw different view angles, then work based on those, adding each dimension to the model turn. But really I'm just guessing here.

How do I do this methodically and correctly?


texts: How to use a KeyListener and an input handler together?

texts:
The following class implements a KeyListener, and handleInput() method gets called in an endless loop.

public final class PlayerInput implements KeyboardInputHandler{

  public static final int INVERTED_AXIS = 0;
  public static final int NORMAL_AXIS = 1;

  private Sprite sprite;

  private int axisMode_x=NORMAL_AXIS;
  private int axisMode_y=NORMAL_AXIS;

  private boolean left;
  private boolean right;
  private boolean down;
  private boolean jumping;
  private boolean doubleJump;

  private int jumpCounter=0;
  private boolean stopLeft;
  private boolean stopRight;
  private boolean stopJumping;
  private boolean stopDoubleJump;

  public PlayerInput(Sprite sprite){

    this.sprite=sprite;
  }

  public void setAxisMode_x(int axisMode_x) {

    this.axisMode_x = axisMode_x;
  }

  public void setAxisMode_y(int axisMode_y) {

    this.axisMode_y = axisMode_y;
  }

  public void handleInput(){

    if (left){

      if (axisMode_x==INVERTED_AXIS) sprite.setPos_x(sprite.getPos_x()+sprite.getSpeed_x());
      else sprite.setPos_x(sprite.getPos_x()-sprite.getSpeed_x());
    }
    else if (right){

      if (axisMode_x==INVERTED_AXIS) sprite.setPos_x(sprite.getPos_x()-sprite.getSpeed_x());
      else sprite.setPos_x(sprite.getPos_x()+sprite.getSpeed_x());
    }
    else{

      sprite.goingLeft(false);
      sprite.goingRight(false);
    }

    if (jumping && sprite.collidedDown){

      sprite.addAction(new JumpingAction());
    }
    else sprite.goingUp(false);
  }

  public void keyTyped(KeyEvent e) {}

  public void keyPressed(KeyEvent e) {

    switch (e.getKeyCode()){

    case KeyEvent.VK_LEFT:

      right=false;
      left=true;
      e.consume();
    break;

    case KeyEvent.VK_RIGHT:

      left=false;
      right=true;
      e.consume();
    break;

    case KeyEvent.VK_SPACE:
      jumping=true;
      e.consume();
    break;
    }
  }

  public void keyReleased(KeyEvent e) {

    switch (e.getKeyCode()){

    case KeyEvent.VK_LEFT:

      left=false;
      e.consume();
    break;

    case KeyEvent.VK_RIGHT:

      right=false;
      e.consume();
    break;

    case KeyEvent.VK_SPACE:
      jumping=false;
    break;
    }
  }
}

If I want the player to jump, I need to press Space and then release it... But what if my "jumping" variable checking comes right after my keyReleased method?

Is there a way to synchronize these two pieces of code?

Thank you for your answer.


texts: Ogre3d 2.1 - How to apply texture on mesh?

texts:
I have searched forums and tried to read the Ogre 2.1 samples, but I still have no clue how to apply texture on mesh  :(

Here what I've done so far.

I use Easy Ogre Exporter to export the scene (actually I just need the model and texture). I got the following files:

modelRoot.mesh
modelRoot.skeleton
model.material
model.tga

Note: I also use OgreMeshTool_d.exe to upgrade the mesh from v1 to v2.

I render this model into Ogre:

In the file resources2.cfg:

[Essential]
Zip=../Data/DebugPack.zip

I add the model files (4 files I got from Easy Ogre Exporter at step 1 above) into DebugPack.zip file.

And I use this code to add the model into the Ogre scene

void MeshHelper::CreateMesh(Ogre::String szFileName, Ogre::Vector3* scale)
{
    /*Bring the mesh to scene*/
    m_meshItem = m_sceneManager->createItem(szFileName,
        Ogre::ResourceGroupManager::
        AUTODETECT_RESOURCE_GROUP_NAME,
        Ogre::SCENE_DYNAMIC);
    m_meshSceneNode = m_sceneManager->getRootSceneNode(Ogre::SCENE_DYNAMIC)->
        createChildSceneNode(Ogre::SCENE_DYNAMIC);
    m_meshSceneNode->attachObject(m_meshItem);
    if (nullptr != scale)
        m_meshSceneNode->scale(scale->x, scale->y, scale->z);
}
...
meshHelper.CreateMesh("modelRoot.mesh", &meshScale);

But I can only render the model without texture  :(

Please help me to apply these texture into my model

model.material
model.tga

Thanks for reading :)


texts: Do I still need limit FPS when I have a variable timestep?

texts:
Lets say I have a simple game loop (variable timestep - but it applies also for other timesteps):

double lastTime = SDL_GetTicks();

while(isRunning){

    double currentTime = SDL_GetTicks();
    double elapsed = currentTime - lastTime;

    processInput();
    updateGameWorld(elapsed);
    render();

    lastTime = currentTime;
}

My FPS increases drastically to 4k+ and CPU to 80%+ (actually it was very simple app) and I had to limit the FPS anyway (which I think is destroying the timestep). My question is: is locking FPS necessary or I'm doing it wrong?


texts: How can I make an object's hitbox rotate with its texture?

texts:
In XNA, when you have a rectangular sprite that doesnt rotate, it's easy to get its four corners to make a hitbox. However, when you do a rotation, the points get moved and I assume there is some kind of math that I can use to aquire them.

I am using the four points to draw a rectangle that visually represents the hitboxes.


texts: Pygame making Snake, need help with generating fruit with a random color

texts:
This is my function for generating an apple, I want it to generate a random color each time the snake eats it.

    def AppleGenerator():
        fruit_colors = [crimson,powderblue,yellow,hotpink,orange,darkorchid,lime]
        x = random.randrange(1,6)
        return fruit_colors[x]

This is when I call it, AppleX, AppleY, and size are just the dimensions of the rectangle. The problem is that the 'apple' just flashes random different colors from the list and doesn't stick to one color.

 pygame.draw.rect(gameScreen,AppleGenerator(),[AppleX,AppleY,size,size])

By the way, the reason why I didn't just simply do

def AppleGenerator():
   fruit_colors = [crimson,powderblue,yellow,hotpink,orange,darkorchid,lime]
   return random.randrange(fruit_colors[0],fruit_colors[6])

is because the colors are tuples, and randrange() only accepts integers.


texts: What is the purpose of inertial space and what are its uses?

texts: I'm currently reading about left-handed and right-handed coordinate systems when working with 3D and it's all very fascinating. These systems are made up of world space, object space, and inertial space. I believe I have a firm grip on world space and object space, however I'm not entirely sure what inertial space is used for? If my understanding is correct - it is simply a way to convert local space to world space, and vice versa? Is inertial reference frame the same as inertial space?


texts:
I'm about to start writing an iOS game and I'm going to use mainly C++/C for the core gameplay logic.

I really like pre-allocating everything in the game and try to avoid any dynamic allocations as much as possible. With my own C++/C code it's not a big deal. However there are some ObjC libraries which I'd like to re-use and I'm not sure how to inject my custom memory allocator to Cocoa based classes.

Is there any central 'inject point' in Cocoa where I can do that?


texts: Switch scenes and continue to receive bluetooth stream from Update

texts:
I have a scene where I'm connected to a BLE device and receive data in bytes. I want to switch scenes from the current Update and continue to receive the data without disconnecting. How should I do this. Here is my current code in Update:

            case States.Subscribe:
                HM10_Status.text = "Subscribing to HM10";

                BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress (_hm10, ServiceUUID, Characteristic, null, (address, characteristicUUID, bytes) => {

                    float floatprint = EnterDataQueue(bytes);
                    Debug.Log("floatprint" + floatprint.ToString());
                    HM10_Status.text = "Received Serial: " + floatprint.ToString();
                    //HM10_Status.text = "Received Serial: " + Encoding.UTF8.GetString (bytes);
                });

And the method outside:

static float EnterDataQueue(byte[] bytes)
    {
        ArduinoHM10Test aTest = new ArduinoHM10Test();
        //always load the data byte array in full
        for (int i = 0; i < bytes.Length; i++)
        {
            aTest.myQueue.Enqueue(bytes[i]);
        }

        //Dequeue the queue and check if 4 bytes have been dequeued
        if (aTest.myQueue.Count >= 4)
        {

            byte[] byteArray = new byte[4];
            for (int i = 0; i < byteArray.Length; i++)
            {
                byteArray[i] = aTest.myQueue.Dequeue();
                if (i == 3)
                {
                    break;
                }
            }

            aTest.floatnum = BitConverter.ToSingle(byteArray, 0);
        }

        Debug.Log("floatnum: " + aTest.floatnum.ToString());
        return aTest.floatnum;
        //throw new NotImplementedException();
    }


texts: How to prevent an object with high velocity from passing through a collider?

texts:
Consider a simple 2D platformer. I have a BoxCollider2D on the player object and a TilemapCollider on the ground below(grid). I created a "jump" script for the player through which the player object jumps and comes back to the ground, clean. But when the player object goes relatively high and comes down with a high velocity, it doesn't collide with the ground(grid) instead it goes right through the tilemap collider and into the void.
How can this behaviour be prevented?


texts:
I want to get the angle between the rotation (euler Angles) of the camera (V1 : Vector3) and the collision point of my character, when it hits a wall, to determin, if it was left, right, or in front of it.I tried to use Vector2.Angle with V1 and V2 (ControllerColliderHit.moveDirection as a Vector2) to get the difference between them.

However I get a different value (0, 90, 180) when running into the wall depending on the world direction. (left wall, right wall, etc.)

How can I get the angle of the collision point relative to the direction the camera is facing?


texts: Cocos2dx- how to box2d cannot move through each other?

texts:
player box2d

auto playerbody = PhysicsBody::createBox(sp->getContentSize());
        playerbody->setGravityEnable(false);
        //playerbody->setDynamic(false);
        sp->setPhysicsBody(playerbody);

item box2d

auto ItemBody = PhysicsBody::createBox(item->getContentSize());
            ItemBody ->setGravityEnable(false);
            ItemBody ->setDynamic(false);
            item->setPhysicsBody(ItemBody );

When moving, these 2 boxes can go through each other.How does this not happen?
sorry my bad english. many thank


texts: How do I check if one square is overlapping another in HTML5 canvas

texts:
I have a little program that goes like this:

Whenever somebody presses space, a blue square appears. The blue square shouldn't overlap with any other blue square.

But the function that is checking the overlap is not working! Can somebody please help?

window.onload = function() { //Starts the program when the page is loaded.

  var canvas = document.getElementById("paper");
  var background = canvas.getContext("2d");
  var squareDisplay = canvas.getContext("2d");

  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  var xAndYvaluesOfSquares = [];

  //Makes a randint() function.
  function randint(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  function checkForOccupiedAlready(testXPos, testYPos) {
    if (xAndYvaluesOfSquares.length != 0) {
      for (valuePair in xAndYvaluesOfSquares) {
        if (
          ( valuePair[0] + 20 ) < testXPos &&
          ( valuePair[0] - 20 ) > testXPos &&
          ( valuePair[1] + 20 ) < testYPos &&
          ( valuePair[1] - 20 ) > testYPos){ //If in the same area
          return false;
        }
      }
    }
    return true;
  }

  //Makes a new square
  function makeNewsquare() {

    var checkingIfRepeatCords = true;
    //DO loop that checks if there is a repeat.
    do {
      //Makes the square x/y positions
      var squareRandomXPos = randint(50, canvas.width - 50);
      var squareRandomYPos = randint(50, canvas.height - 50);

      //Tests if that area is already occupied
      if (checkForOccupiedAlready(squareRandomXPos, squareRandomYPos) == true) {
        xAndYvaluesOfSquares.push([squareRandomXPos, squareRandomYPos]);
        checkingIfRepeatCords = false;
      }
    }
    while (checkingIfRepeatCords == true);
  }

  function resetBoard() {
    for (i = 0; i < xAndYvaluesOfSquares.length; i++) {
      var XYvalue = xAndYvaluesOfSquares[i];

      squareDisplay.beginPath();
      squareDisplay.fillStyle = "rgb(50, 50, 125)";
      squareDisplay.rect(XYvalue[0], XYvalue[1], 50, 50);
      squareDisplay.fill();

    }
  }

  document.addEventListener("keydown", function (event) {
    if (event.keyCode == 32) { //Space key
      makeNewsquare();
      resetBoard();
    }
  })
}


texts: Need help with sorting layers on a 2D game made in Unity

texts:
I'm busy with my full blown project in unity, it's a 2D game as I thought this would make a good starting point.

So to the problem, I've got 3 elements in the game. The ground, an object and a beam. The ground is set to layer 2 and the object to 3. This gives the effect that the object is on top of the group which I need. Now the beam is what I'm having the problem with. I need the beam to be ontop of the object so on layer 4 for example, but I also need it to be behind the ground so layer 0 or 1.

If anyone can point me in the direction that may help or give me any tips i'd be grateful.

As requested I uploaded a screenshot.

So here the object(the cow) is on top of the ground layer. The beam is ontop of the object but it's also ontop of the group, I need it to be beneath the ground.


texts: Unity2D Sprite gone / not visible when flipped using Vector3.x

texts:
I have create game object with code

using UnityEngine;
using System.Collections;

public class CharacterBehaviour : MonoBehaviour {

private bool facingRight = true;
private float moveDirection = 0;
private Rigidbody2D theRigidbody2D = null;

void Start ()
{
    theRigidbody2D = GetComponent<Rigidbody2D>();
}

void Update ()
{
    moveDirection = Input.GetAxis("Horizontal");
}

void FixedUpdate()
{
    theRigidbody2D.velocity = new Vector2(moveDirection * 5, theRigidbody2D.velocity.y);

    if (moveDirection > 0 && !facingRight)
        Flip();
    else if (moveDirection < 0 && facingRight)
        Flip();

}

void Flip()
{
    facingRight = !facingRight;
    Vector3 scale = transform.localScale;
    scale.x *= -1;
    transform.localScale = scale;
}
}

and using the material as shown below

In game while not facing left / while the game object is facing right :

But while the game object is not facing right / while the game object is facing left :

*The camera is follow the game object, so that's why i surround the camera with yellow rectangle

the question is, how can i fix this ? how can i fix the sprite to not gone even facing left state, or maybe any suggestion / method to do this ?

EDIT [ HOW TO SOLVE THIS ]

From the answer below, Fuzzy Logic told me to create 2-sided mesh / rectangle, or in this case maybe the sprite, but i have a problem there, then i try to create 2-sided shader from the orignal "Legacy Shaders/Transparent/Bumped Specular" and rename to "Legacy Shaders/Transparent/Bumped Specular 2 sided" with just adding a line of code:

Cull Off

after

SubShader {
    LOD 400

If you need full of shader code, you can download it here.


texts: Import Blender files to SharpGL (openGL for c#)

texts:
please i have problem with import 3D models to SharpGL (openGL in c#).
Have you got pls any project where is this problem solved?
I need create any models in for example blender, and then import to sharpGL.
I try this 4 days, and without result. Please can you post me any project with loading (obj,3ds,...) files with texturing? I do big school project and without this i never completed this project.
Thank you for answer.

Sorry for my english.


texts:
Relevant background information

I'm developing a game for a high school computer science performance task in python & pygame. I'm using objects and all the code is working well for me.

The game consists of a top down (bird's eye view) 2D shooter of a player that rotates and shoots at zombies that spawn and make their way to him. Kind of like dead ops arcade from the original black ops.

Though I'm developing the levels using a list string type designer (there's probably a name for the common technique I'm unaware of), than I load it and I have an array of rects. Here is some background code.

            x = 0 # Start X at 0
                    y = 0 # Start Y at 0
                    for row in levelData: # run a for loop for all the rows in level data
        for col in row: # run a for loop for all the colums in the row
            if col == "1": # check if the column section is labeled 1
                self.Rects.append(pygame.Rect((x, y),(self.tileWidth, self.tileHeight))) # append a rectangle
            if col == "2": # check if the column section is labeled 2
                self.Rects.append(pygame.Rect((x, y),(self.tileWidth, self.tileHeight))) # append a rectangle
            if col == "3": # check if the column section is labeled 3
                self.zombieSpawners.append(ZombieSpawner(x, y, self.zombieManager, int(self.maxZombies / self.levelDesigns.getSpawnerAmount(self.level)), self.zombieSpawnTimeMin, self.zombieSpawnTimeMax, self.zombieVelMin, self.zombieVelMax, self.zombieHealth)) # Initalize a zombie spawner with given data
            x += 64 # adjust x
        y += 64 # adjust y
        x = 0 # reset row
    self.levelLoaded = True

            def draw(self, canvas, playerRect):
    canvas.blit(self.backgroundImage, (0, 0)) # draw background image
    for rect in range(len(self.Rects)): # for loop to run all rects
        canvas.blit(self.blockImage, (self.Rects[rect].x, self.Rects[rect].y)) # draw a block
    for spawner in range(len(self.zombieSpawners)):
        canvas.blit(self.spawnerImage, (self.zombieSpawners[spawner].getX(), self.zombieSpawners[spawner].getY()))

The indenting is all screwed up but you should understand what I'm doing.

The problem

The code above works perfectly. The game ran really smooth with just the player and zombies. Though when I run the background image above, it becomes a huge performance decrease, the fps becomes a solid 3-5. Drawing the blocks and the spawners cause some performance issue's as well, not as bad as the background image but still unplayable.

I think the background image does so much performance damage because it's an actual picture and not a little cartoon like the blocks and spawer's.

What I'm trying to do

Is there anything I'm doing wrong or something I should do that can get my performance back? Like some sort of spritebatch for pygame or something. I can't figure out anything online other than pygame doesn't have that good of a performance.


texts: Z-Value of clip-space position is always 1.0

texts:
I render a lot of quads on the screen into z direction (20 x 2000). I want to get the depth value in a final render target. But it looks like z is always 1.0f. I checked the result with the OpenGL debugger. Any advice?

Vertex shader:

#version 410

layout(row_major) uniform UView
{
    mat4 m_View;
    mat4 m_Projection;
};

layout(row_major) uniform UModelMatrix
{
    mat4 m_ModelMatrix;
};

layout(location=0) in vec2 VertexPosition;

out vec3 PSVSPosition;

void main(void)
{
    vec4 VSPosition = m_View * m_ModelMatrix * vec4(VertexPosition.xy, 0.0f, 1.0f);

    PSVSPosition = VSPosition.xyz;

    gl_Position = m_Projection * VSPosition;
}

Fragment shader:

#version 410

layout(row_major) uniform USettings
{
   mat4  m_ProjectionMatrix;
};

layout(location = 0) out vec4 PSColor;

in vec3 PSVSPosition;

void main(void)
{
    // Calculate depth
    vec4 CSPosition = m_ProjectionMatrix * vec4(PSVSPosition, 1.0f);

    CSPosition.xyz /= CSPosition.w;

    PSColor = vec4(vec3(CSPosition.z * 0.5f + 0.5f), 1.0f);
}

Result:

Closer result:

view-space position result:

clip-space position result:


texts:
I just started playing around with c++ and some SFML. I'm going to create a 2D game with top view to test my ability and I came across a very big problem: collision detection and physics. So I see at least 4 scenarios:

An object collides with a solid object (that cannot move) so the first object must stop. (Example: a player hitting a wall)
An object collides with a movable object (that is not alive so does not move unless pushed) so the first object push that object. (Example: a player that moves a box)
Two object (that has proper move) moves and collide frontally so they push each other with the same force so they must stay still.
Two object (that has proper move) and one push the other which is going in the same direction: so the second object must move faster or must have more power. This implies also that if more object push themself one back to the other we have that the first gains a lot of push power. (Example: a crowd that push to to get inside a door and that door with x pushing power gets destroyed)

The collision problem is not a problem at all: you just check the player x and y and width and height against the object that is colliding with. The problem is instead: who is supposed to take care of the collision? Let's say that it's the movable object that is pushing that has to take care of it: (1 scenario), it's ok, the one that pushes just reset its x and y to where it was before colliding; (2 scenario) here things start to get a bit tricky: the pushing object must take care also of the object that gets pushed so it has to move that object too; (3 scenario) here we have two pushing object, which one should deal with the collision? (4 scenario) how do we store the pushing power of the object?

Is there general guidelines for that, considering also that the player is not the only mob and that there might be computer guided mobs?

Thanks.


texts: Possible bottlenecks when rendering sprites programmatically in Unity using Graphics.DrawMesh()?

texts:
I'm currently trying to render sprites in Unity without using a sprite renderer component.

So far using Graphics.DrawMesh() I have this:

public void Draw(Sprite sprite, Vector3 pos) {
    Material mat = new Material(spriteMaterial) {
        mainTexture = sprite.texture
    };
    Mesh mesh = new Mesh() {
        vertices = Array.ConvertAll(sprite.vertices, x => (Vector3)x),
        triangles = Array.ConvertAll(sprite.triangles, x => (int)x),
        uv = sprite.uv
    };
    Graphics.DrawMesh(mesh, Matrix4x4.TRS(pos, Quaternion.identity, sprite.bounds.size), mat, 0);
    }

Everything was working fine except after doing a test with a about hundred or so sprites my fps went down to around 30.

So the question is, is this normal? If not, what potential bottlenecks could there be?


texts: How do you determine where the user wants to place a block in a 3d scene?

texts:
I am still in the think-ahead-and-plan stage of a project where I'll want the player to be able to drag-out blocks - tiles but a minecraft-like 3D block-world.

So my question is: how can you determine where the user wants to place a block?

Here's a random minecraft screenshot I found on the internet:

My game will not be first-person camera; the user will be able to click anywhere to place a block.

If the user clicks on the centre of that green cross I've marked, which just misses the stonework to its right, where should the block be placed?

Technically determining the ray under the mouse cursor is trivial.

Given a ray and computing its distance / intersection with all existing block faces, and knowing the blocks that have previously been placed e.g. the last placed block, how can you 'do the right thing' with regards ambiguous movement?  What rule set can you use?


texts: Black Box Functionality Testing Methods that apply to an MMO

texts:
I've been interesed in a career in Video Game QA for a long time now. I've participated in roughly a dozen+ public/closed betas for different games, everything from FPS, MMO, MOBA and RTS, as well as a lot of early access Indie Games recently.

I'm not some 12 year old kid who thinks playing video games every day will be fun. I know it's tedius work with strict deadlines and a lot of pressure. I enjoy the analytical side of the process and I would like to make this passion a career.

I currently have a few upcoming closed beta weekends scheduled that I'm going to be participating in.

What are some ways I can use these to really improve as a tester?

Anyone in this line of work that would be willing to share some pointers for what type of experience people hiring for a QA job would be looking for, besides the obvious; analytical, attention to detail, communication, etc

Additional information: Feel like I should also mention that I have a lot of programming experience as well. I'm currently a Software Engineering major in my final year, but what I'm really interesting in is QA.

Thank you

EDIT:: I'd like to get this back opened so let me see if I can word this more appropriately.

What are some professional Game Functionality/UX Testing methodologies that I could apply to an upcoming Closed Beta Weekend event for WildStars or Elder Scrolls Online.

I'm looking for information that I could use to provide a thourough evaluation of game aspects that I could then include in a Resume or Testing Profile/Portfolio to show a potential employer "This is how I planned my session out, this is how I executed it and this is what I found."

I hope this is less open ended then my original post.


texts: Call code on interrupting Unity animator sub-FSM

texts:
I'm trying to find a way to execute a code when one of two outcomes happens in Unity animator controller:

When animator's sub-FSM finishes or
When animator's sub-FSM is "interrupted" by a transition originating from "Any state" node at the parent FSM.

The concrete setup is next (but that is probably not super important):

The parent FSM have a transition from "Any state" to Damaged state and that can "interrupt" an attack sub-FSM: Parent FSM

The attack sub-FSM consists of three states that run in succession PreAttack -> Attack -> PostAttack: Attack sub-FSM

At the end of the attack sub-FSM a method is called. It can be through:

Animation even at the end of PostAttack animation in the sub-FSM, or
StateMachineBehaviour.OnStateExit() at the PostAttack state , or
StateMachineBehaviour.OnStateMachineExit() at the sub-FSM.

The problem is that none of these 3 is called when the sub-FSM is "interrupted" by the "Any state" transition in the parent. Is there any way to call code when a sub-FSM is "interrupted" by "Any state" transition in the parent FSM?


texts: What is the average team size for mobile games like these?

texts:
I know that it is maybe too broad question but please give me at least some guidance.
What is the average team size for mobile games like in
https://play.google.com/store/apps/category/BRAIN?feature=category-nav

There are quite different by size and complexity games but I just need examples like: Game X was developed by N programmers for M months (or at least "It seems to me that game X will need N programmers for 5 months to be completed").

By "Team size" I mean mostly programmers (but I will really appreciate more info about other specialists that are needed for such project).

To put some context:
I am freelance Android and PHP developer working mainly on intranet and b2b systems that are consisted by both android app(s) and server back end. Although I really like this area sometimes it is hard to find new projects. At the same time, every now and then, I receive inquires like "Can you create clone of game X and how long will it take" or "I have this idea for a board/puzzle game, how long it will take?". So far I stay away from such projects but I am really tempted to start/join such project and I will appreciate any helpful information.


texts:
I've been following some game tutorials on youtube and developed a custom engine using Java (Graphics2D, BufferStrategy and such).

I have a class "Surface", which represents any 2D object (image, animation, sprite, text, graph, tiled map, height map, etc). All surfaces have some generic properties and a BufferedImage where the current state is drawn, and passed to the renderer when needed.

Everything works fine, but i wanted to try something "better" so now i have a new project using LWJGL 3 and... i'm totally lost.
I know OpenGL and Graphics2D are parallel universes, but at this moment i just want to adapt the existing code to the new libraries.

How can i create a target surface for 2D drawing, which can receive pixels from different sources and drawing methods, using modern OpenGL/LWJGL?


texts: How many shadow casting lights are in modern games?

texts: I'd like to know how many shadow casting lights are supported in modern games, such as Uncharted 2, Crysis 2, Modern Warfare 2, Halo: Reach, etc. Do they all limit themselves to just a couple of shadow casting lights, or do the numbers vary wildly?


texts: The most correct/efficient way to update millions of entities that change over time in an mmo?

texts:
We have a server and a database in the cloud. We have a game where each player can grow a farm on a massive x,y grid. Each hour is a grow cycle. All players can harvest anyone's plants.  Player A plants some seeds and logs off. Player B logs in five hours later and harvests Player A's plants. At 3:00 PM there is a global rain on the x,y grid that gives plants a bonus grow cycle.

scenario 1: The server timestamps each players actions and the global rain adds a counter to global effects, which is read when the player logs in and applied to the area they see, this effect can only happen once per day and removed by nightly maintenance.

Player A: Plants seeds 1:00 PM. (Server timestamps plant entities with 1:00 PM) and logs off.
Player B: Logs on harvests seeds at 6:00 PM (Plants grow cycle is 5 + 1 (rain)) = 6. (the grow cycle is calculated when Player B sees the plants in his view area)

scenario 2: The server does global updates on all entities.

Player A: plants seeds 1:00 PM. (no time stamp). Logs off
grow cycles occur each hour: 2:00 PM +1, 3:00 PM (rain) +2 etc.
Player B: Logs on and harvests the plants.

Scenario one seems like the best case, with also checking the view area around the player and updating plants on the hour or after a rain so the player that is staying logged in will see the plants grow.

I feel like I am missing something, such as a global save on server shutdown.

Are both scenarios useful for different functions?


texts: How to get window size from within another class?

texts:
I have found this post explaining about how to get the size of the Window, but for whatever reason I'm having issues getting it to work inside of a Singleton class that I'm made to manage a set of Objects.  Anyone have any examples of getting these values from inside of a singleton?

EDIT:  Just in case the question gets asked.  I'm using the values for when the Manager instantiate the objects it's managing...  So that they don't all start at the same spot and to ensure they start on the screen.


texts: How to implement dither in pixel shader?

texts:
I've seen this talk about INSIDE's rendering (thanks to DMGregory).
It says that we should dither everything.
What I wonder however is how to dither in a simple fragment shader?
In a Pixel Shader I don't have access to neighbouring pixels, how do I dither for example the vertex colors?
Imagine a single quad with a gradient going from white to black.
I can multiply the Vertex Colour with the noise texture, but this will only darken/brighten the actual color.
My Noise texture looks like this:

My Pixel Shader works like this:
float blueNoise(uniform SamplerState noiseSampler, uniform Texture2D noiseTex, in float2 uv, int frame) {
    switch (frame%4) {
    case 1:
        return noiseTex.Sample(noiseSampler, uv).y;
        break;
    case 2:
        return noiseTex.Sample(noiseSampler, uv).z;
        break;
    case 3:
        return noiseTex.Sample(noiseSampler, uv).w;
        break;
    default:
        return noiseTex.Sample(noiseSampler, uv).x;
        break;
    }

}

float remap_tri(float value) {
    float orig = value * 2.0 - 1.0;
    value = max(-1.0, orig / sqrt(abs(orig)));
    return value - sign(orig) + 0.5;
}

float4 PS(PixelShaderInput input) : SV_TARGET {
    float4 output = Texture.Sample(Sampler, input.UV);
    float3 lighting = input.Color.xyz;
    float noise = remap_tri(blueNoise(NoiseSampler, BlueNoise, (input.Position.xy)/512,Frame))/255;
    output.xyz = output.xyz * lighting + noise;
    return output;
}

The shader makes the image look way too noisy:

What I want is more like an actual dither, i.e. I have two vertex colors and I'd like to remove the banding with dithering (i.e. only dither where banding occurs)


texts:
What type of integrator is used in the PhysX engine? Euler? Runge-Kutta?

I tried to look through the comments in the SDK header and source files. But, could not find any information about this.