texts:
I've been trying to get a simple client server relation using udp for about a week now, And I think it's time for me to stop trying and ask for help... I understand how TCP works and UDP too. The thing is, when I use UDP, there's no way for me to know the client is still connected, and same thing for the client. I tried using two connections, one TCP for sending important data such as login information, but I don't know how to keep a stable connection in UDP!

Here's how I work:

The server starts a new thread for listening on port X with TCP
The client connects to the server in TCP using the port X
The server sends a confirmation for connection on the UDP part of the server
The client starts sending information (location of the player) via udp and opens a thread for that client (tcp and udp).
When the server hasn't received data for 15 seconds, it sends a "ping"
If the server hasn't received "pong" in the next 5 seconds, it closes the connection + thread for this client.
When a client is disconnected or sends a disconnect packet, it closes the connection + thread for this client.

The main problem with this is that I don't know how to receive data(server side) from a certain address via udp. At the moment, I can only receive data from every address...

Is there a way I could ensure I only receive data from a single remote computer (on the listening thread of that particular client)? Am I doing something wrong? Should work differently (seems it's making lots of connections and threads for a server that would have lots of clients)?

I'm working in C# with console applications at the moment, but I'll be using forms in the future, and the game is going to be in Java (C# XNA 4.0 for testing the connection first).

And most important of all, Thanks you!


texts: Time.fixedDeltaTime & Time.deltaTime in Unity

texts:
The old Unity 5.3 documentation said:

Time.fixedDeltaTime
The interval in seconds at which physics and other fixed frame rate
updates (like MonoBehaviour's FixedUpdate) are performed.
For reading the delta time it is recommended to use Time.deltaTime
instead because it automatically returns the right delta time if you
are inside a FixedUpdate function or Update function.
Note that the fixedDeltaTime interval is with respect to the in-game
time affected by timeScale.

So, it was said (paraphrased as I get it) that Time.fixedDeltaTime returns the interval at which the FixedUpdate method should be called with respect to the timeScale. But the real interval could differ (for technical reasons) and that's why Time.deltaTime should be used instead to return a real time elapsed since the previous FixedUpdate call.
The latest docs don't say that anymore: https://docs.unity3d.com/ScriptReference/Time-fixedDeltaTime.html
Does it mean that now FixedUpdate is called exactly at Time.fixedDeltaTime rate?
Now it also says:

Unity does not adjust fixedDeltaTime based on Time.timeScale. The
fixedDeltaTime interval is always relative to the in-game time which
Time.timeScale affects.

Don't these two sentences contradict each other?


texts: Parsing Blender exported collada file in c++

texts:
Since I could not find any libraries that can help me parse collada files in my c++/opengl project, I decided to write my own. (I did find assimp, but binaries for Visual Studio 2013 were't available, and I don't know enough to build it myself from the source; Can anyone build it and share it please? )

I read up a little about the structure of .dae files, figured I could do it, and exported Suzanne from Blender in a .dae file. Fine. Now I open up the .dae file in Notepad++ just to make sure I got the basic understanding right, and I found something weird.

So the tags [float_array id="Suzanne-mesh-positions-array" count="1521"] and [/float_array] contain the huge list of vertex positions right?

And the tags [p] and [/p] inside [polylist count = "968"] and [/polylist] should contain vertex indices in triangular order right?
But that doesn't make sense, cause then the first triangle is going to be vertex[46], vertex[0] and vertex[0].. But how is that possible? Any help please? If I've got it wrong, can someone direct me to some place where i can learn how to parse collada files. Thanks a lot.

EDIT: I finally managed to build Assimp for VS 2013 (YAAYYYY!!)after getting awesome instructions at http://www.learnopengl.com/#!Model-Loading/Assimp

But my confusion regarding the vertex indices remain.


texts: Is there is IO text files in actionscript2 or 3?

texts:
i tried actionscript recently,am little scared
i want to make a game that input a word from about 3000 randomly,
do actionscript support that,or
should i try another language?


texts: Processing periodical operations on the database

texts:
I program MMO strategy game (C# monogame) like Goodgame Empire or Travian for Windows Phone.

The server part of the game will run on Windows Server and MS SQL database.

I'm trying to figure out a way to perform periodical operations over players' data. My point is that, for example farm will produce one piece of food every minute and I need store it to database in real time.

I thought about that when registering a new player would cause the database start new job, but for example at 2000 players on the server I'm not sure if I do not
kill performance. I want to find optimal solution and I wanted to ask your opinions on what you think would be the best solution.


texts:
I would like to draw reference frame to see how my camera moves around scene. I want these arrows to always be on the top of other geometry. How can I achieve it?

I think I need to disable depth test for this draw calls. Should I use just another PSO with changed DepthStencilState?

EDIT: Well, it works for me like that.

// opaquePsoDesc defined somewhere above
D3D12_GRAPHICS_PIPELINE_STATE_DESC opaqueHudPsoDesc = opaquePsoDesc;
opaqueHudPsoDesc.DepthStencilState.DepthEnable = false;
THROW_IF_FAILED(g_device->CreateGraphicsPipelineState(&opaqueHudPsoDesc, IID_PPV_ARGS(&psos_["opaque_HUD"])));

And then before drawing your HUD you can:

commandList->SetPipelineState(psos_["opaque_HUD"].Get());

I'll leave this answer here, in case someone will need it.

Well, that works fine if you don't want depth test for the HUD objects.


texts: Shooting projectiles towards mouse position in Unity 2D

texts:
I'm currently creating a scrip that handles the projectile movement and it's almost where I want it to be. Currently the script correctly instantiates the projectiles, moves the projectiles towards the mouse and deletes them off screen, but the speed of the projectile is not constant (faster or slower depending on how close the mouse is to the player) and after the projectile is fired, it follows the position of the mouse until it flies off screen.

public class LetterController : MonoBehaviour {
    private List<GameObject> letters = new List<GameObject>();
    public GameObject letterPrefab;
    public float letterVelocity;
    Vector3 direction;
    void Update()
    {
        direction = Input.mousePosition;
        direction.z = 0.0f;
        direction = Camera.main.ScreenToWorldPoint(direction);
        direction = direction - transform.position;
        if (Input.GetMouseButtonDown(0))
        {
            GameObject letter = (GameObject)Instantiate(letterPrefab, transform.position,Quaternion.identity);
            letters.Add(letter);
        }
        for (int i = 0; i < letters.Count; i++)
        {
            GameObject goLetter = letters[i];
            if (goLetter != null)
            {
                goLetter.transform.Translate(direction * Time.deltaTime * letterVelocity);
                Vector3 letterScreenPosition = Camera.main.WorldToScreenPoint(goLetter.transform.position);
                if (letterScreenPosition.y >= Screen.height || letterScreenPosition.y <= 0 || letterScreenPosition.x >= Screen.width - 20 || letterScreenPosition.x <= -20)
                {
                    DestroyObject(goLetter);
                    letters.Remove(goLetter);
                }
             }
          }
       }
   }

I tried moving everything from Update() into a separate function called Shoot() and called that from Update(). I tried putting Vector3 direction in its own Vector3 function and calling it in goLetter.transform.Translate. I also tried using LateUpdate(). Nothing I've tired has made any significant changes to how the projectile interacts in Unity. I'd like to have the projectiles move at a constant speed and not follow the cursor but rather travel in a straight line anyone got any clues?


texts:
I'm writing some code to check intersection between all of a rectangles segments and a ray. It will sometimes use the Left and Right side of the rectangle as the closest face hit (face DA & BC) even when it is clearly on the top of the rectangle (face AB).

This is what the Rectangle v Ray collision looks like.

    // Ray intersections
    static public IntersectData IntersectRectRay(Rectanglef rect, Vector2 origin, float dir)
    {
        IntersectData data = new IntersectData();

        // Create segments for all the sides of a rectangle
        Segment topLeftRight = new Segment(rect.TopLeft, rect.TopRight);
        Segment leftTopBottom = new Segment(rect.TopLeft, rect.BottomLeft);
        Segment bottomLeftRight = new Segment(rect.BottomLeft, rect.BottomRight);
        Segment rightTopBottom = new Segment(rect.TopRight, rect.BottomRight);

        // Check collision with all the faces and use the closet one
        float smallestDepth = float.PositiveInfinity;

        IntersectData topLeftRightData = IntersectSegmentRay(topLeftRight, origin, dir);
        if (topLeftRightData.intersecting && topLeftRightData.depth.Length() < smallestDepth)
        {
            smallestDepth = topLeftRightData.depth.Length();
            data = topLeftRightData;
            data.face = "AB";
            data.dir = MathHelper.PI / 2f;
        }

        IntersectData leftTopBottomData = IntersectSegmentRay(leftTopBottom, origin, dir);
        if (leftTopBottomData.intersecting && leftTopBottomData.depth.Length() < smallestDepth)
        {
            smallestDepth = leftTopBottomData.depth.Length();
            data = leftTopBottomData;
            data.face = "DA";
            data.dir = 0f;
        }

        IntersectData bottomLeftRightData = IntersectSegmentRay(bottomLeftRight, origin, dir);
        if (bottomLeftRightData.intersecting && bottomLeftRightData.depth.Length() < smallestDepth)
        {
            smallestDepth = bottomLeftRightData.depth.Length();
            data = bottomLeftRightData;
            data.face = "CD";
            data.dir = MathHelper.PI / 2f;
        }

        IntersectData rightTopBottomData = IntersectSegmentRay(rightTopBottom, origin, dir);
        if (rightTopBottomData.intersecting && rightTopBottomData.depth.Length() < smallestDepth)
        {
            data = rightTopBottomData;
            data.face = "BC";
            data.dir = 0f;
        }

        return data;
    }

and this is the ray v Segment intersection

    static public IntersectData IntersectSegmentRay(Segment seg, Vector2 origin, float dir)
    {
        IntersectData data = new IntersectData();

        // Get vector between p1 and p2
        Vector2 q = seg.p1;
        Vector2 s = seg.p2 - seg.p1;
        Vector2 p = origin;
        Vector2 r = new Vector2((float)Math.Cos(dir), (float)Math.Sin(dir)) * 100000f;

        float t = MathHelper.Vec2CrossProduct(q - p, s) / MathHelper.Vec2CrossProduct(r, s);
        float u = MathHelper.Vec2CrossProduct(q - p, r) / MathHelper.Vec2CrossProduct(r, s);

        if (MathHelper.Vec2CrossProduct(r, s) != 0 && t <= 1 && t >= 0 && u <= 1 && u >= 0)
        {
            data.intersecting = true;
            data.depth = p + t * r;//q + u * s;
            data.dir = dir;
        }

        return data;
    }

Extra Info: My Vec2CrossProduct is V × W to be Vx Wy − Vy Wx

I imagine there is something wrong with the ray segment intersection because if I tried to replace that 100000f with float.PositiveInfinity() it won't work.


texts:
In OpenGL, what is the difference between GL_DEPTH_COMPONENT and GL_DEPTH_STENCIL?
I have looked around and have been unable to find a clear explanation.

Information on their usage with GLSL would also be appreciated (mainly DEPTH_STENCIL).

Thanks for any help.


texts: Is there a way to run Unity without rendering the scene on the monitor (headless)?

texts:
I am doing some machine learning and I get my environment from Unity in the form of images but the training is taking too long and it keeps me from doing anything else on my system. Is there a way to hide the simulation rendering?
Any help will be highly appreciated.


texts: Traffic estimation for a multiplayer flash game

texts:
hey, i want to know if my rough traffic estimations are right, it would be for a pretty simple realtime flashgame in the style of haxball (but not as a soccer game) heres a video of it http://www.youtube.com/watch?v=z_xBdFg1RcI

So here comes my estimation, i dont know if they are realistic! i hope someone can help me.

consider the packet attached as a typical one sent every 200ms, its 148bytes + 64 bytes of header will make around a 200bytes packet. The server will receive 200bytes x 6 players x 5 times a sec=6000bytes/s=5.85Kbytes/s=46.9kbit/s plus he has to send all back to the players, so at this point are 94Kbit/s.The server received all the information, perform the definitive calculation and send the new position to all players, in a bigger packet of around 900bytes that have to be delivered to the others 6, which makes 900bytes x 6 players x 5 times a sec=27000bytes/s=26Kbytes/s=210kbit/s. overall that would be 26kbyte per second. thats like 130mb traffic per hour for a 6player room. but somehow i think the numbers are too high? that would be really much traffic for such a simple game.

did i calculate something wrong?


texts: What makes a game responsive to user input?

texts:
Many games, like "Super Meat Boy" and "Shank", have been praised for their responsive game play, where each user action input corresponds to a quick and precise character movement.

What makes a game responsive, and what prevents other games from achieving the same? How much of it is due to the game framework used to queue input events, and update the game, and how much is attributed to better coding?


texts:
I'm relatively new to programming velocity and such as I used to use Unity so it was already implemented. Right now, I'm using MonoGame and have an issue with my velocity code. Whenever I decelerate, my "velocity.X" never becomes 0 it just keeps going down to numbers like "-8.775121E-10". I tried to check if it's less than or equal to 0.05 but that just causes issues.

Movement Code:

currentState = Keyboard.GetState();

        deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;

        bounds.X = (int)position.X;
        bounds.Y = (int)position.Y;

        position.X += velocity.X;
        position.Y += velocity.Y;

        if (velocity.X >= MAX_ACCELERATION)
            velocity.X = MAX_ACCELERATION;
        if (velocity.X <= -MAX_ACCELERATION)
            velocity.X = -MAX_ACCELERATION;

        if (currentState.IsKeyDown(Keys.A))
        {
            if (velocity.X > -MAX_ACCELERATION)
                velocity.X -= acceleration * deltaTime;
        }
        else if (currentState.IsKeyDown(Keys.D))
        {
            if (velocity.X < MAX_ACCELERATION)
                velocity.X += acceleration * deltaTime;
        }

        Console.WriteLine("Velocity: " + velocity);
        Console.WriteLine("Current KeyState: " + currentState.IsKeyUp(Keys.A));

        prevState = currentState;

        Console.WriteLine("Prev KeyState: " + prevState.IsKeyDown(Keys.A));

        SlowDown();

SlowDown Method:

            /*if (!prevState.IsKeyUp(Keys.A) && currentState.IsKeyUp(Keys.A))
        {
            if (velocity.X >= -0.5f)
                velocity.X = 0;
        }*/

        velocity.X *= FRICTION;


texts: Fastest way to create a simple particle effect

texts:
I am looking to the fastest way to create really simple particle effect that will be spammed like hell on the game...

Basically, my game looks like a vectrex game, made mostly of lines... I want to make some small explosions that will be really common.

There are something faster than just moving around some points and rendering with GL_Point?


texts: Overriding CoRoutine doesn't execute base code

texts:
I want to have a CoRoutine declared as virtual in parent class and then overridden in child classes.

protected override IEnumerator f(Vector3 to)
{
...
    yield return base.f(to);
...
}

What happens (or doesn't happen) is that the base code doesn't get executed. Debuggin it I step into the base.f(to) and the cursor just stand on function name. If I press step next control returns to the child.

I really have no clue how to handle this situation. Any clue?


texts: Bezier Curves for visual programming node connectors

texts:
Probably everyone is familiar with all kinds of visual node based programming tools like HLSL editor in Visual Studio 2011 or UDK engine Kismet/Material editors. My point of interest are the connectors between the nodes. Basically those are implementation of Bezier Curve algorithms. Those are not hard to put into code.

How I make each connector line bend into right direction and with the right angle when it is being connected between two points not laying on the same line?


texts: How do I teach my artist to do art for games?

texts:
So my girlfriend is an artist and I'm a programmer and we often talk about joining talents and doing some small games or other fun stuff for the different popular platforms currently out.

But because I haven't really done any serious game development yet, I have a hard time explaining to her how she should create or package the assets she'd make, so we always end up not doing anything about it.

What I'm mostly thinking about here is when doing frame by frame animation. I know sprite sheets are used for this kind of thing, but then come questions like frames per second and stuff like that. Not program wise but art wise.

How should we tackle this?


texts:
I'm trying to get a "windowed" look for the GUI game menu screen, like the one in this image:

I believe I've found the code where the change would be made, but am unsure what to adjust.
style game_menu_outer_frame is empty
style game_menu_navigation_frame is empty
style game_menu_content_frame is empty
style game_menu_viewport is gui_viewport
style game_menu_side is gui_side
style game_menu_scrollbar is gui_vscrollbar
style game_menu_label is gui_label
style game_menu_label_text is gui_label_text
style return_button is navigation_button
style return_button_text is navigation_button_text
style game_menu_outer_frame:
    bottom_padding 30
    top_padding 120
    background "gui/overlay/game_menu.png"
style game_menu_navigation_frame:
    xsize 280
    yfill True
style game_menu_content_frame:
    left_margin 40
    right_margin 20
    top_margin 10
style game_menu_viewport:
    xsize 920
style game_menu_vscrollbar:
    unscrollable gui.unscrollable
style game_menu_side:
    spacing 10
style game_menu_label:
    xpos 50
    ysize 120
style game_menu_label_text:
    size gui.title_text_size
    color gui.accent_color
    yalign 0.5
style return_button:
    xpos gui.navigation_xpos
    yalign 1.0
    yoffset -30

Any ideas would be much appreciated!


texts: How can I refactor "attack cooldown" into "attack speed"?

texts:
I'm building a game where the player's character can attack bad guys and vice versa. I built this with the concept of an "attack cooldown" because I don't want units to be able to attack each other every single frame.  I want there to be some delay between attacks.  Here's roughly how it works:

if unit.ticksUntilAttack <= 0
  unit.attack(target)
  unit.ticksUntilAttack = unit.attackCooldown
unit.ticksUntilAttack = unit.ticksUntilAttack - 1

I also have a page where I show the character's stats and list this as "Attack Cooldown".  I was showing my friend and he said, "Why don't you rename that to 'Attack Speed'"?  I explained that it's not really the speed at which you attack because "smaller is better".  We both agreed that "attack speed" is a more standard way to show this concept and that I should change things the way he suggests.

The problem for me is that "attack cooldown" is a much more intuitive way for me to program the solution.  I'm wondering if there's some "trick" to refactoring the current code I've got.  I'm thinking something like this:

if unit.attackSpeedAccumulator >= SUM_NEEDED_TO_ATTACK //a constant that's the same for every unit
  unit.attack(target)
  unit.attackSpeedAccumulator = 0
unit.attackSpeedAccumulator = unit.attackSpeedAccumulator + unit.attackSpeed

Is there a smarter way to do this?


texts:
My goal here is simple. I am making a top down shooter kind of game, and I want the player to simply rotate in one axis, towards where the mouse is on the screen. I got it working, but it rotates so fast that everything is out of control. The following method is called in Update() on my player's game object

void RotatePlayer()
{

    var targetPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 100);

    targetPosition = Camera.main.ScreenToWorldPoint(targetPosition);

    targetPosition.y = transform.position.y * Time.deltaTime;

    transform.LookAt(targetPosition);

}

That rotates in the direction of the mouse, but like I said it rotates so fast that you cannot control it.

As you can see I tried to multiply by delta time, but that did not seem to do anything. Also, changing that last parameter of "100" to a lower number also does not do anything.

Any help is greatly appreciated.


texts: is there a way to alternate between two state machines?

texts:
I'm programming an enemy on Unity that has two state machines, one controlling the "normal" behaviour of the enemy (that consists in three states: idle, patrol and chase) and another one controlling the battle behaviour of the enemy (that consists in three more states: attack, dodge and run away). I'm doing these state machines by using enums, like the following code
public enum StateMachines { NORMAL, BATTLE }
public enum NormalStates { IDLE, PATROL, CHASE }
public enum BattleStates { ATTACK, DODGE, RUNAWAY }

I want to loop between the Normal and Battle state machines but I have one problem that is they always get executed at the same time. Is there a way I can alternate between state machines through code in a single script (by conditions)? Thank you!


texts: deferred rendering and a few shading functions

texts:
How to use a few shading functions together with deferred rendering (for example some objects are shaded based on a lighting equation,
other get a fixed color) ? I draw a full screen quad when shading (later I want to add optimizations for point lights). I have some idea how to
solve that problem: during a gbuffer stage a shading function id should be saved in one of the render targets. Then we can do something like this:

if(id == 0)
{
    fragColor = shadingFun0(...);
}
else
{
    fragColor = shadingFun1(...);
}

What do you think about that ?


texts: Is it really more efficient to have a local variable for transform here or is Rider being over-zealous?

texts:
I'm just going through a quick C# / Unity crash course (coming from Java) and I recieved a warning about "Repeated property access of a built-in component is inefficient" while working in Jetbrains Rider for the following code snippet.

if (Mathf.Abs(horizontalMovement) > Mathf.Epsilon) {
        horizontalMovement += horizontalMovement * Time.deltaTime;
        var position = transform.position;
        horizontalMovement += position.x;

        position = new Vector2(horizontalMovement, position.y);
        //warning is for this line
        transform.position = position;
    }

It was already complaining about using transform.position.x and transform.position.y which seemed fair enough so I created the position var but would declaring var cachedTransform = transform; ...; cachedTransform.position = position really be more performant here or is the overhead of creating the local variable just going to negate it?

I'm not asking if this is a valid warning in general, it seems to be. I'm asking if it's valid when you're literally just reassigning in the same statement as I am in the last line of my code above

For reference here's what I would end up with if I followed the warning -

 if (Mathf.Abs(horizontalMovement) > Mathf.Epsilon) {
            horizontalMovement += horizontalMovement * Time.deltaTime;
            var cachedTransform = transform;
            var position = cachedTransform.position;
            horizontalMovement += position.x;

            position = new Vector2(horizontalMovement, position.y);
            cachedTransform.position = position;
        }


texts:
I am writing a small multiplayer game in C++. But I am confused about how to send info about gun shots to achieve best performance. I am thinking of different ways to do that:
Let's say we have a gun that can shoot 10 times per second (when left mouse button is held).

When user presses LMB game sends TCP packet telling that shooting has started.
When user releases LMB game send TCP packet telling that shooting has stopped.
When LMB is held game send UDP packet every (1/10) sec telling about one shot.
When LMB is held game send TCP packet every (1/10) sec telling about one shot.

I think that the last one is the best because it allows to check hits on the server side, not on the client side (cause this way it can be easily hacked). But I am not sure if TCP can handle 10 packets per second. What do you suggest?


texts:
How can I create water drops on camera something like we see in Ripitude GP,

I tried using Unity's default GlassStainedBumpDistort shader though its performance heavy on mobile plus it do not let animate water drops.


texts: Access violation executing location 0x00000000

texts:
When I try to debug my program, this Exception is being thrown in a call to glGenBuffers. I'm  using OpenGL and SDL. Here is my code:

It consists of two classes:
m and sprite

s is var of sprite class

class  m  is like this:

void run()
{
    init();
    s.init(-1.0f,-1.0f,1.0f,1.0f);
    loop();
}

void  init()
{
    SDL_Init(SDL_INIT_EVERYTHING);
    glewExperimental = GL_TRUE;
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    window = SDL_CreateWindow("mine", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1024, 768, SDL_WINDOW_OPENGL);
    if (window == nullptr) {

        fatalerror("cant create (open) window");
    }

    SDL_GLContext context = SDL_GL_CreateContext(window);
    if (context == nullptr) {

        fatalerror("context cant be created ");

    }
    GLenum cerror = glewInit();
    if (cerror != GLEW_OK)
    {
        fatalerror("cant init glew:(");
    }
    std::cout << "ok";

    glClearColor(1.0f, 0.0f, 0.0f, 1.0f);

}

void looploop()
{
    while (state != gamestate::exit)
    {

        input();
        draw();
    }

}
void M::input()
{
    while (SDL_PollEvent(&events)) {

        switch (events.type)
        {
        case SDL_QUIT:
            state = gamestate::exit;
            SDL_DestroyWindow(window);
            break;
        case SDL_MOUSEMOTION:
            std::cout << events.motion.x << ',' << events.motion.y << "\n";
            break;
        }

    }

}

void draw()
{
    glClearDepth(1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnableClientState(GL_COLOR_ARRAY);
    s.draw();

    SDL_GL_SwapWindow(window);

}

class sprite:

void init(float x, float y, float w, float h)
{
    _x = x;
    _y = y;
    _w = w;
    _h = h;

    if (vboid == 0) {

        glGenBuffers(1, &vboid);
    }

    float vertexdata[12];
    //first triangle
    vertexdata[0] = x + w;
    vertexdata[1] = y + w;
    vertexdata[2] = x;
    vertexdata[3] = y + h;
    vertexdata[4] = x;
    vertexdata[5] = y;
    //second triangle
    vertexdata[6] = x;
    vertexdata[7] = y ;
    vertexdata[8] = x+h;
    vertexdata[9] =  y;
    vertexdata[10] = x+w;
    vertexdata[11] = y+h;
    glBindBuffer(GL_ARRAY_BUFFER,vboid);
    glBufferData(GL_ARRAY_BUFFER,sizeof(vertexdata),vertexdata,GL_STATIC_DRAW)
        ;

}

void draw()
{

    glBindBuffer(GL_ARRAY_BUFFER,vboid);
    glEnableVertexAttribArray(0);
    glVertexAttribLPointer(0,2,GL_FLOAT,GL_FALSE,0);
    glDrawArrays(GL_TRIANGLES,0,6);
    glDisableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, vboid);

}


texts: What available multiplatform languages are there available for 2D games

texts:
I was wondering what multi-platform languages are available that could be used to create and deploy 2D games, please note that im not asking which is the best as I do not want to cause arguments over which people believe to be the best.

Ideally I would like to be able to deploy to as many different platforms as I can (PC, Mac, iPhone, Android, etc..)

I do apologies if this has been bought up, but I could not find anything from the searches that I tried.


texts: I want to start writing games using ogre in combination with the CodeBlocks compiler but am struggling with the installation. I got the latest version of the compiler as well as the ogre engine from their respective websites. I have installed the compiler but cannot find my way in the integration of ogre though I read their installation guide, which I found confusing.I need clear step by step guide please.


texts: Better way to handle ordering and visibility of renderable objects?

texts:
I'm just wondering whether there is a more effective way to handle the ordering and visibility of renderable components that fits into the design of my already existing engine.

How I do it now:

In each update in my SceneHandler, do this:
Retrieve all renderable components that currently are in the current scene
Send these components to the RenderManager
Call RenderManager.Update
In each update in RenderManager, do this:
Iterate over the given list and perform an occlusion test
If the object is visible, put it in a new list of visible items
Sort the list of visible items in the order of their layer depth
When RenderManager.Draw() is called the RenderManager iterates over the list of visible items and draws them

Is there any way that is obviously better than this or is this how you usually do? Maybe I could keep a sorted list of all the current scene objects and then just perform occlusion testing and thus not having the need to sort each update?

Pros and cons of the suggested method are greatly appreciated.


texts: I'm working on a networked game for a while. I'm aware of client-side prediction and lag compensation (shooting) but I'm not sure about entity interpolation client-side. I'm sending update/sync packets at 10fps from server and client interpolates from current position to newly received position. Interpolation takes 100ms (because of 10fps) to reach target position but what if new position arrives late or 2-3 packets drop? There will be no target position and sync'd (client-side) entity will be idle until new position packet but entity continuously moving forward server-side. Basically, I don't know what to do in this situation.


texts: Unity : How to detect if a UI button is pressed down?

texts:
I want a UI up arrow button to be able to detect if it is pressing down. It is a child of a canvas in a 3D scene. My target platform is webGL for both desktops and mobiles.
I coded not only the control of the up arrow UI button but also the control of keyboard arrow button for desktops.

The keyboard control worked fine in PC but the UI arrow button didn't work as expected both in desktop and mobile.

I tried the OnPointerDown() function attaching to the UI up arrow button and the logged it. The log didn't even show up when the UI button is pressed down both in desktop and mobile.

It seems the OnPointerDown() needs the image of the button to receive raycast so its image component Raycast target option is on.

Isn't the onPointerDown() supposed to be used in detecting press down of UI component by both mouse in desktop and touch in mobile?

How to get the UI button to be notified when it is pressed down?
Any approach other than onPointerDown() which can do the same thing?

My scripts are here:

the one attached to the car object to be controlled

using UnityEngine;

public class CarPlayerControl : MonoBehaviour {

public float speed = 40;
private bool touchCtrl = false;
private float xInput = 0f;
private float zInput = 0f;

void Awake(){
    //if (Input.touchSupported && Application.platform
         //     != RuntimePlatform.WebGLPlayer){
        //touchCtrl = true;
        //}
        }

void FixedUpdate(){

    xInput = 0f;
    zInput = 0f;

    if (touchCtrl)
    {

    }
    else //keyboard control in desktop
    {
        xInput = Input.GetAxis("Horizontal");
        zInput = Input.GetAxis("Vertical");
    }

    Move(xInput, zInput);
}

public void Move(float xInput, float zInput)
{
    float xMove = xInput * speed * Time.deltaTime;
    float zMove = zInput * speed * Time.deltaTime;

    float x = KeepXWithinRange(xMove);
    float y = transform.position.y;
    float z = KeepZWithinRange(zMove);

    transform.position = new Vector3(x, y, z);
}

private float KeepXWithinRange(float xMove){
    float x = transform.position.x + xMove;
    return Mathf.Clamp(x, 0, 900);
}

private float KeepZWithinRange(float zMove)
{
    float z = transform.position.z + zMove;
    return Mathf.Clamp(z, -470, 500);
}
}

and the one attached to the UI Up arrow button

using UnityEngine;

public class ButtonUpControl : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
public GameObject car;
private CarPlayerControl carPlayerControl;
private bool mouseDown;
private float xInput;

void Awake()
{
    carPlayerControl = car.GetComponent<CarPlayerControl>();
    mouseDown = false;
}
void Start()
{

}

void FixedUpdate()
{
    if (mouseDown) {
        xInput = 1.0f;
    }
    else {
        xInput = 0f;
    }

    carPlayerControl.Move(xInput, 0f);
}

public void OnPointerDown(PointerEventData eventData)
{
    mouseDown = true;
    Debug.Log("on ptr down btn up ");
}

public void OnPointerUp(PointerEventData eventData)
{
    mouseDown = false;
    Debug.Log("on ptr up btn up ");
}
}


texts: Shadow-casting through time acting in "reverse" before next notciable shadowmap update

texts:
question was re-written to better explain the problem

I have a scene of big thin parallelepiped, small cube, and a light source, all aligned on Y axis, like so:

 _
| |
| |----[ ]----Light
|_|

Both objects are static and light is sliding on Y axis only.

Also, a tiny (32x32) depth texture from Light's PointOfView is being rendered off-screen and then applied to both cube and parallelepiped on on-screen rendering stage, making effect of a shadow being casted by a small cube on a big parallelepiped.

The problem i am experiencing is that when light moves away from cube, such low-res depth texture is getting updated only 6-7 times, but it's projection on surfaces updates constantly and wrongly: while shadow is supposed to shrink when lightsource moves away and grow when lightsource moves closer, it is in fact doing the reverse between updates of texture projection! In other words, between two updates of texture, it's projection on a parallelepiped grows when light moves away and shrinks when light moves closer and then "jumps" when texture updates, which is looking very wrong.

To better show the problem, i've made this video: http://www.youtube.com/watch?v=XOraTZimmUU (the square in right-upper corner is the depth texture, made from light's POV).
As you can see, at first i am moving light out (decresing negative Y) and you can notice projection growing between "jumps" of texture updates. Then i am moving light in and you can notice projection shrinking between the same "jumps".

My question is: how to reverse this shrinking-growing behavior without increasing shadowmap texture resolution (which only make problem less noticable, but not completly solved)?

Shaders used to map texture on:

Vertex:

#version 120
struct light_t {
  vec3 spot_dir;
  vec3 position;
  mat4 MVP;
  mat4 V;
  mat4 P;
};
attribute vec4 in_position;
uniform mat4 MVP;
uniform mat4 M;
uniform mat4 V;
uniform mat4 P;
uniform light_t light;
varying vec4 shadowcoord;
void main() {
  gl_Position = MVP * in_position;
  mat4 bias = mat4(0.5, 0.0, 0.0, 0.0,
                   0.0, 0.5, 0.0, 0.0,
                   0.0, 0.0, 0.5, 0.0,
                   0.5, 0.5, 0.5, 1.0);
  shadowcoord = bias * light.MVP * in_position;
}

Fragment:

#version 120
varying vec4 shadowcoord;
uniform sampler2D shadowmap;
void main() {
  vec4 color = vec4(0.5);
  float factor = 1.0;
  float z = texture2DProj(shadowmap, shadowcoord.xyw).z;
  if (z < (shadowcoord.z-0.0005)/shadowcoord.w) factor = 0.2;
  gl_FragColor = factor * color;
}

The full self-contained source of minimal (~900 lines, meh) example (extracted from full-scale project) is here (glm math library, C++ compiler and glut is needed):

Compile line:

g++ -g -o example main.cpp  -lGL -lGLU -lglut -lGLEW

Actual source:
http://paste.eientei.org/show/287/

WebGL playground: webglplayground.net/saved/NAfoKmQqJb


texts: Present fails randomly on mixed C++ Direct3D9 app

texts:
I have a mixed .NET application (managed and unmanaged code bridged by C++/CLI wrappers) which uses unmanaged Direct3D9 9.0c to do rendering inside a control which is wrapped inside a C++/CLI class which extends System.WIndows.Forns.UserControl.

Everything has been working fine for years now, but I recently put another instance of this Direct3D9 control inside a new Windows Form. That is, I have two concurrent instances of the control. I had done that before and it worked, but now I have issues. Perhaps the problem was always there, but because it's related to a race condition, it started happening now...

Ok, the details: When I try to render an image over a texture on the new instance of the control, sometimes it works, sometimes it doesn't. And when it doesn't, nothing is rendered, and from that point onwards, all Present calls fail (I log those failures). If I close the form and open it again, it might work or not. Nasty.

If I use DXGetErrorString and DXGetErrorDescription, all I get is something like:

  EFAILED Undetermined error

Not really helpful... To make matters worse, I can't reproduce the issue in my development environment; I only see it in a production box.

As far as I know, the main reason Present fails like this is a Lost Device. But I implemented the usual scheme to handle that (I can post the code if necessary), and it seems like the device is not being lost... What else can I try?


texts: Java Reversi/Othello - Checking if Valid move

texts:
I've written a gameBoard class for a Reversi/Othello which is the following:

import java.io.Serializable;

public class GameBoard implements Serializable {

private static final long serialVersionUID = 1034285059488509251L;
public char[][] board;

public GameBoard(){
    board = new char[8][8];
    setUpBoard();
}

  public void printBoard() {

      //prints numbers at the top of the board
        System.out.print("  ");
        for(int i = 0; i < board.length; ++i){
            System.out.print(i +  "   ");
        }

        //prints column icons and numbers and side of board
        System.out.println();
        for (int i = 0; i < board.length; i++) {
            System.out.print("| ");
            for (int j = 0; j < board.length; j++) {

                System.out.print(board[i][j] + " | ");
            }
                System.out.print(i);
                System.out.println();
        }

    }

public void setUpBoard(){

      // Loop through rows
    for (int i = 0; i < 8; i++) {

        // Loop through columns
        for (int j = 0; j < 8; j++) {
            board[i][j] = '-';
            System.out.println();
        }
    }

    //sets the default piece positions;
    board[3][3] = 'W';
    board[3][4] =  'B';
    board[4][3] = 'B';
    board[4][4] = 'W';

}

public String toString(){
    StringBuilder b = new StringBuilder();
    for(int i = 0; i < board.length; ++i){
        b.append(i +  "   ");
    }

    b.append("\r\n");
    for (int i = 0; i < board.length; i++) {
        b.append("| ");
        for (int j = 0; j < board.length; j++) {

            b.append(board[i][j] + " | ");
        }
        b.append(i);
        b.append("\r\n");
    }
    return b.toString();
 }
}

This class as you can see handles basics of the game board. Such as printing the board and setting up the default positions. It is also serializable and I have a saving and loading method to store the game state and an overriden toString method so that I can print the board again.

I have another class called boardLogic and I've been messing around in this class for about 4 hours now trying to figure out how to check what is a valid move in Reversi/Othello or not.

The simple rules are:
-You cannot place a piece on any random place
-If you are to place a piece it must me adjacent to another piece of your color Horizontally, vertically or diagonally and it doesn't matter how many pieces are in between.

So, can anyone help me out on how I would go about checking if the player had made a valid move or not.


texts: Game Maker: How to check overlapping instances of the same object?

texts:
I want to make sure that no two instances of obj_A are overlapping, but can't seem to figure anything out, because instance_position, instance_nearest and the like will include the instance running it, so if I had something like:

if instance_position(x,y,obj_A)!=noone
{
    with(instance_position(x,y,obj_A))
    {
        instance_destroy()
    }
}

All instances of obj_A will destroy themselves because they think they are overlapping with themselves.


texts: Stuck in Wall after rectangle bounding box collision

texts: Using XNA's built in Intersects() on two Rectangles, I can detect a collision and set my velocity to zero. However, the object is stuck there and can't get out! How can I resolve this collision properly?


texts: Unity 5 light reflection on the water surface

texts:
How to adjust reflection in Unity 5 to show up it on the water surface. So I have few light elements in the scene. So I want my water pro to reflect this lights.

As example you can see red and yellow lights from the Shanghai's build on the water, that's what I am trying to achieve:

I've added water pro and setup flare:

Looks liker here some small reflection on the rect I market as red. But if comparing with real reflection it's more vertical reflection I've marked it as red well:

If you can see it unity example does not look natural. So if we compare distance from sun to the beach border on real photo, there is a huge sun line over the water surface, but there is not the same line on water pro in unity.

Here is a video link with what I did:
http://screencast.com/t/bq8Ocl24ZAJH


texts: SFML Trying to shoot bullets but it moves with the gun

texts:
I'm pretty new to SFML and C++ and I'm trying to figure out how to shoot bullets. I've done the shooting part and it's origin is from a moving shape controlled by the user called Player.

The problem is when I move, the origin moves as well which is why the bullets move with the origin. I feel like it's something really basic but I cannot for the life of me figure this out. Can anyone help?

This is the part of the code that creates and moves the shapes:

        //creates a new bullet when pressed
            else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {
            rects.push_back(sf::RectangleShape(sf::Vector2f(40, 10)));

        }
    }

    // clear the window with black color
    window.clear(sf::Color::Black);

    sf::Vector2f pl = player.getPosition();

    //draw active shapes in the vector and move them to the right
    for (int x = 0; x < rects.size(); x++)
    {
        rects[x].setOrigin(-pl.x,-(pl.y + 10));
        window.draw(rects[x]);
        rects[x].move(10, 0);
    }


texts: How do you programmatically generate a sphere?

texts:
Could someone please explain how it would be possible to create a sphere vertices, indices and texture coordinates? There is a surprising lack of documentation on how to do so and it is something that I am interested in learning.

I have tried the obvious, googling, looking on gamedev.net, etc. However, nothing covers the generations of spherical points, indexing them, and texturing.


texts: Using Unity/Unreal as graphic engine while programming the game externally

texts:
My favorite language is C++ and I feel most comfortable to stick to it.

I made a game in C++ primarily using the console output as a graphical interface: somewhat like that of dwarf fortress.

However I wish to connect my game to either Unity or Unreal so that I can take advantage of their graphic rendering.

Is it possible? Running a game on other program while separately running an application on Unreal or Unity for rendering purpose? Or should I just make a game from ground up on Unreal or Unity?


texts: Variable not set before reading it error in GameMaker Studio 2

texts:
I am following along with a guide. I'm trying to reference code from an instance in my room, but whenever I try to run the script I get this error:

ERROR in action number 1 of Create Event for object objSmileyFace:
Variable objHealth.(100004, -2147483648) not set before reading it.
at gml_Object_objSmileyFace_Create_0 (line 4) - objHealth.playerHealth = objHealth.playerHealth + 10;
gml_Object_objSmileyFace_Create_0 (line 4)

It says objHealth is not set, which is not true. What am I doing wrong?


texts:
I implemented ParallaxScrolling for my SideScroller project, everything is working but the tiled map (the most important part!). I've been trying out everything but it doesn't work (see the code below).

I'm using  ParallaxCamera from GdxTests, it's working perfectly for the background layers.

I can't explain myself properly in english, so I recorded 2 videos:

Before parallaxScrolling

After parallaxScrolling

As you can see, now the platforms appear in the middle of the Y-axis.

I've got a Map class with 2 tiled maps, so I need two renderers too:

private TiledMapRenderer renderer1;
private TiledMapRenderer renderer2;

public void update(GameCamera camera) {
renderer1.setView(camera.calculateParallaxMatrix(1f, 0f), camera.position.x - camera.viewportWidth / 2,
           **camera.position.y - camera.viewportHeight/2**, camera.viewportWidth, camera.viewportHeight);
renderer2.setView(camera.calculateParallaxMatrix(1f, 0f), camera.position.x - camera.viewportWidth / 2,
           **camera.position.y - camera.viewportHeight/2**, camera.viewportWidth, camera.viewportHeight);
}

In bold, the code I think I should change. I've tried changing parameters, even adding hardcoded values, etc, but one of two:
1. Nothing happens.
2. Platforms disappear.

Here is some aditional code. The render method:

     world.update(delta);
    parallaxBackground.update(camera);

    clear(0.5f, 0.7f, 1.0f, 1);

    batch.setProjectionMatrix(camera.calculateParallaxMatrix(0, 0));
    batch.disableBlending();
    batch.begin();
    batch.draw(background, -(int)background.getRegionWidth()/2, -(int)background.getRegionHeight()/2);
    batch.end();
    batch.enableBlending();

    parallaxBackground.draw(batch, camera);
    renderer.render(batch);


texts: Game Networking: Client request or Server Sending

texts:
I'm trying to implement a basic client-server setup for my game. But what confused me was how I would approach sending updates.

Would I do:

Server has a tickrate, let's say at 20ms. Each tick would sends an UDP package to EVERY connection with the current game state and it's entities.

OR

Client request an update from the server and the server respond with the update. When the client receives it, it asks for another update and so on.

Pro-cons:

Con: Sends a package every tickrate and in this case 20ms. What if a clients broadband connection has a triptime at 300ms? Wouldn't that overload that client and his broadband?
Pro: Consistent and fast?

Con: Requesting is done via TCP which is slower because the client has to wait before sending the next request.
Pro: no overload?

So my question would be, what I'm I missing and how would I approach sending updates about the current game state?

Cheers!


texts: Mobile screen resolution and canvas size

texts:
I'm making a HTML5 game using the canvas. I was building it for my iPhone 6 which state a resolution of 1334x750 pixels but also a resolution of 667x375 points. I notice that my canvas need to match the size in points or else it would go beyond the screen.

<canvas width="667" height="375" />

Is it possible for my canvas to actually be 1334x750? Or am I stuck at 667x375?


texts: Can I use fonts under C:\Windows\Fonts for text in my game?

texts:
I'm using Unreal Engine and their UMG system which comes with only one font by default ("Roboto").

The engine allows importing new fonts so I'm wondering whether I can use the fonts already available with Windows 10 under C:\Windows\Fonts. I know I can't redistribute these fonts but does merely including text (which uses the font) in a game and distributing the game count as distributing the font? I mean it's not like the TTF file is being given away with the game in its raw form.

I've read these two related questions but I'm still not 100% sure so I thought I'd ask this forum.

Main menu fonts and logos are all I care about right now, so I could just create these as images in Photoshop and bring them into the engine (that sounds perfectly safe, right?)

All in all, I never imagined getting a nice looking font for one's game could be so time-consuming!


texts: How is it possible that I make my player die in unity

texts:
So what I have is a 2 platform game where I want my player to die when it hits a trap and go back to the last checkpoint it when past
Currently I use this script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Respawn : MonoBehaviour
{
    public Transform PlayerPrefab;
    public Transform SpawnPoint;

    void OnCollisionEnter2D(Collision col)
     {
         if (col.gameObject.tag == "Trap")
         {
             respawn();
         }
    }

    void respawn()
    {
        Instantiate(PlayerPrefab, SpawnPoint.position, SpawnPoint.rotation);
    }
}

but When i hit the trap I go through it
The trap does have a 2 collider on it with ontrigger Selected
How could I implement a checkpoint system and then death


texts:
So, forgive me if some of the terminology is wrong, I am just getting started with Unity again and I can't remember the proper names. I'm also on my phone, so I didn't have unity in front of me when I posted this question.

I am beginning work on a voxel based game. Everything in the game will be models constructed of 64 by 64 cubes. I would like to, with the code given, say, a 4096 bit array, be able to construct a model in the game with those cubes. I know that you can programmatically add models that you have imported into unity, but I want to make contiguous meshes programmatically, with highest performance being the goal. I do not want a certain amount of little 1x1 cube meshes positioned right next to each other, but specifically one model.

Is this possible?


texts: How do I measure a string that will be drawn with SpriteBatch?

texts: Is there a way to measure width and height of an ever-changing string (a player's score, specifically)?


texts: Handling creation of enemy sprites in a level

texts:
I am trying to build an RPG tile-map based game. Currently I am going to set enemy sprites that will be repeating their motion in fixed path. Suppose that I have a level map, which has got width 3 times greater than actual applet visible to user.

Now my question is that how should I handle creation of enemy sprites? I have got two options in my mind:

1) Create all enemies at a time on level load (I don't want to follow this approach as it will take up extra memory).

2) Create enemies till the level map is visible to user. Load new enemies as user goes further. I want to follow this one but I don't have any idea.

Can someone give me hints to follow this step and tell me approach usually followed by game developers?


texts: Projecting texture from an arbitrary position

texts:
I'm trying to write a surface shader (not a projector) to project a texture to a surface in a very similar way of what projectors do.

Currently I can easily obtain a shader that uses screenspace as UV:

        float2 screenUV = IN.screenPos.xy / IN.screenPos.w;

What I'm trying to achieve is to have an arbitrary plane to project the texture over the mesh that uses the shader.

I'm checking some resource online like https://en.wikibooks.org/wiki/Cg_Programming/Unity/Cookies but this is strongly related to light space.

My main doubt is how can I generate the UV coordinates from another plane? should I define somehow plane sizes or is it enough to define its position?


texts: Texture won't appear using a vector of unique pointers of an Object

texts:
I am working on a top down 2d shooter game. I have a player Sprite and a Bullet class. I made a vector of pointers to Bullet to store the bullets. Here is the code of the vector and the functions I’m using:

    std::vector<std::unique_ptr<Bullet>> b;

    while(win.isOpen)
    {
    //Getting Key Press
    if (Keyboard::isKeyPressed(Keyboard::Space))
    {
        space = true;
    }
    else
    {
        space = false;
    }
    if (space)
    {
        Bullet b1;
        b1.setPos(player.getPosition());
        b.push_back(std::make_unique<Bullet>(b1));
    }

    for (auto& it : b)
    {
        //Keep Updating
        it->update();
    }

    //Bullet out of Screen
    for (int i = 0; i < b.size(); i++)
    {
        if (b[i]->getPos().y < 0.0f)
        {
            b.erase(b.begin() + i);
            i--;
        }
    }

    //Drawing Bullet
    for (auto& i : b)
    {
        win.draw(i->getSprite());
    }
     }

The game runs fine but the bullet’s texture won’t load. I’m assuming it has something to do with the vector but I don’t know how to solve it.
Here is the Bullet class:
Header:

 #pragma once
 #include <SFML/Graphics.hpp>

 using namespace sf;

 class Bullet
 {
private:
Texture t;
Sprite bullet;
Vector2f pos;
public:
Bullet();
void setPos(Vector2f pos);
void update();
Sprite& getSprite();
Vector2f getPos();
};

Cpp File:
     #include "pch.h"
     #include "Bullet.h"
     #include

Bullet::Bullet()
{
//Setting Texture
if (!t.loadFromFile("Graphics/bullet.png"))
{
    std::cout << "Bullet Texture Failed to Load\n";
}
else
{
    t.loadFromFile("Graphics/bullet.png");
    bullet.setTexture(t);
}

}

void Bullet::setPos(Vector2f pos)
{
//Setting Position
this->pos = pos;
bullet.setPosition(this->pos);
}

void Bullet::update()
{
pos = bullet.getPosition();

bullet.move(0.0f, -4.0f);

}

Sprite& Bullet::getSprite()
{
return bullet;
}

Vector2f Bullet::getPos()
{
return pos;
}


texts:
I have a question about using Box2D (engine for LibGDX used to make realistic physics). I observed on the code that I've made for the physics here below:

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button)
{
      // TODO Touch Up Event

     if(is_Next_Fruit_Touched)
     {
             BodyEditorLoader Fruit_Loader = new BodyEditorLoader(Gdx.files.internal("Shape_Physics/Fruity Physics.json"));

             Fruit_BD.type = BodyType.DynamicBody;
             Fruit_BD.position.set(x, y);

             FixtureDef Fruit_FD = new FixtureDef(); // --> Allows you to make the object's physics.
             Fruit_FD.density = 1.0f;
             Fruit_FD.friction = 0.7f;
             Fruit_FD.restitution = 0.2f;

             MassData mass = new MassData();
             mass.mass = 5f;

             Fruit_Body[n] = world.createBody(Fruit_BD);
             Fruit_Body[n].setActive(true); // --> Let your dragon fall.
             Fruit_Body[n].setMassData(mass);
             Fruit_Body[n].setGravityScale(1.0f);

             System.out.println("Eggs... " + n);

             Fruit_Loader.attachFixture(Fruit_Body[n], Body, Fruit_FD, Fruit_IMG.getWidth());
             Fruit_Origin = Fruit_Loader.getOrigin(Body, Fruit_IMG.getWidth()).cpy();

             is_Next_Fruit_Touched = false;
             up = y;
             Gdx.app.log("Initial Y-coordinate", "Y at " + up);

             //Once it's touched, the next fruit will set to drag.
             if(n < 50)
             {
                 n++;

             }else{

                 System.exit(0);

             }
     }

         return true;

}

Now, I'm thinking which part o line should I implement for the sound effects. My objectives to make SFX played once for every collision (Or should I say "SFX played once per collision"?) on the following:

SFX played once if they hit on the objects of its kind. (e.g. apple vs. apple)
SFX played once on a different sound when it hit on the ground. (e.g. apple land on the mud)

Take note that I'm using Box2D for the Java programming version thanks to LibGDX via Box2D engine and I edited the physics body using Physics Body Editor before I implement it to code.

I tried to check every available methods for body, fixture definition, or body definition to code for the SFX when hit but it seems only for the gravity and weight. Is there possibly available on the document for SFX played when collision happens if possible?


texts: Performance problems with many entities in AndEngine

texts:
I'm developing a rolling scene based game. I'm loading all the entities from a XML file and create them in the Loading Scene.

I recently increased the game width, and, by doing so, I now have about 300 entities (instead of about 100) in the whole level. This causes a performance problem: the game is "Lagging" \ "jumping" and everything moves slowly.

I'm loading the entities with the "LevelLoader".

I tried to add:

levelObject.setCullingEnabled(true);

before returning the object in :

public IEntity onLoadEntity(final String pEntityName, final Attributes pAttributes){...}

and also set Dithering in the engineOptions:

engineOptions.getRenderOptions().setDithering(true);

but it didn't help...

I'm implementing the sprite created from XML as Matin does in his tutorial:

http://www.matim-dev.com/full-game-tutorial---part-11.html

Is there a better way to handle such a high number of entities? Or is there another way to improve the performance?


texts: What do game developers do when they have to port their DirectX games to PS4/Switch?

texts: I'm not a game developer (hope to be one day though!) and was wondering how devs handle porting their games that use DirectX to PS4/Switch? From what I know neither supports DirectX, only OpenGL, and Vulkan. Do the devs just have to recreate their game with OpenGL or Vulkan? That seems like a lot of work. I'd imagine it would probably be a fairly common scenario, especially with AAA games so I'd assume that there would be something somebody has made to make it easier?


texts: Term for coordinating design elements to produce larger possibility spaces?

texts:
The concept is when content elements work together in such a way to produce more possibilities, playable content, or engagement than the relative amount of added content.

Mathematically:

A content gives you x units of gameplay

B content gives you y units of gameplay

(units of gameplay are however you'd like to measure them, hours of play, total items, actions/discussion branches, etc.)

A = x
B = y
A + B = x*y*?

So that when the game includes both:

A + B

The gameplay unit increase could be:

x * y
(x + y) * c
x ^ y

This concept of expressing it mathematically leads me to want to call this Content Multiplication. But I haven't been able to find much on a specific term for this (most of my attempts have lead me to math games).

Example:

In a game like Minecraft, there's a mechanics and dynamics that define crafting.  By themselves they produce a set of craftable items. Once a player crafts them there's less or no desire/need to craft them again.

Then a relatively small mechanic is added that causes loss, perhaps on death or through durability. The impact on player motivation and time played is much larger. Forcing players to either recraft items, or to craft extras preemptively.  No new items have to be added to the crafting system, and having players lose items isn't a big change (not a lot of work).

Specifically if we look at just these two mechanics, and the expected impact they have together.  Perhaps we're talking about Minecraft 0.1, and only crafting exists, and a decision needs to be made on what next feature to add, that provides us with the most benefit in gameplay content for development effort.

Conclusion

Is there a term to describe the intentional design of coordinated mechanics and system to produce larger sets of content with minimal effort?

Edit: Emergence

Emergence typically refers to unforeseen and unintended results rising from a rise in complexity. Emergent results are frequently hard to quantify, or to ascribe cause to specific elements.

What I'm looking for is an explicit, deliberate, and predictable outcome from the addition of a single element to an existing system.

Contrasting Example:

An example of emergence can be found in the original Deus Ex. Being able to place mines on walls and jump off of them. This effect was (likely) unintended, caused by the interaction of complex systems, and in cases where it could be used to skip content, actually reduced the amount of gameplay. Emergent Gameplay

While designing for emergence can be intended, the outcome is less certain or planned.


texts:
I'm trying to structure my game object classes similar to how it is done in this article.  One way to implement this strategy is discussed in this StackOverflow question.

Following the strategy proposed in the linked question above, how would I control how objects are handled based on their implementations?

For example: suppose I have a base class Item and two subclasses ItemPhys and ItemStatic. These two subclasses both extend Item. ItemPhys implements the interface Moveable, but ItemStatic does not.

If all of the Item's in my game world are stored in a single ArrayList of Item objects, how do I make it so Item::update() will only try to call Item::updateMovable() if the Item in question implements Moveable?


texts:
I have a 2D game I'm making with Unity, and I want the player to be able to collect coins that I place all over the game. I used the coin prefab with a 2D circle collider and an animation to make it spin. The problem is that only the first coin I put into the scene shows up in the game, and when I collect that one coin, the counter shows that all the others have been collected as well. Here's the script I attached to the player for the coins:

private uint tokens = 0;

void OnGUI(){
    GUILayout.Label ("Tokens= " + tokens);
}

void CollectToken(Collider2D tokenCollider){
    tokens++;
    Destroy (tokenCollider.gameObject);
}

void OnTriggerEnter2D(Collider2D col){
    if (col.gameObject.CompareTag ("token")) {
        CollectToken(col);
    }
}

This is my current setup for the object properties:

Thank you for any help!


texts: Have the character automatically slide around obstacle corners

texts:
Like this:

The player is only holding right, however the character still moves up a bit to go around an obstacle.

My current collision system has access to:

The entity's previous position
The entity's current position
The entity's (axis-aligned) bounding box
All the obstacles and their (also axis-aligned) bounding boxes

Also it proccesses each axis separatelly.

How can I implement this?


texts: Loading external file data into Scriptable Object in Unity

texts:
I've been at this for two long days, trying to figure out a way to handle saving and loading data for a mobile puzzle game I'm working on. The game has level packs and each level pack has multiple levels. Level packs can be purchased via IAP.
I need access to the fixed data and an easy way to add new data, so I used Scriptable Objects to store my Level Pack and Level data:
LevelPack

id
type (paid, free)
IAPproductId
levels (list of levels)

Level

id
totalTime (total time to solve puzzle)
warningTime (give a warning during level)
levels (list of levels)

I also need to store the following dynamic data, which can change during runtime:

completedTime for each level
isPurchased for each level pack

I tried adding these to the scriptable objects and it's really easy to maintain and work with. But I can't figure out a way to persist that data between sessions or game updates.
I created a save system that saves just the completed levels to an external file using binary formatter. So every time a level is completed, I change Level.completedTime to the new time on the scriptable object, then do GameState.Instance.UpdateLevelProgress(levelPack.id, levelId, time); to save the file that contains a dictionary with all the completed times.
 public void UpdateLevelProgress(int levelPackId, int levelId, float time)
     {
         if (!levelProgress.ContainsKey(levelPackId))
         {
             levelProgress.Add(levelPackId, new Dictionary<int, float>());
         }

         // set time
         levelProgress[levelPackId][levelId] = time;

         // save to file
         SaveGame();
     }

Even though I figured out how to save, I don't know how to load the data from the file into each Level scriptable object. There is an onEnable function for ScriptableObject, but that runs way before my GameState.LoadGame() function that runs inside a preload scene. So GameState.Instance.levelProgress is empty at that point.
Is there a better, cleaner way to do this?
PS:
Here's my GameState file:
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

[System.Serializable]
public class GameStateData
{
    public Dictionary<int, Dictionary<int, float>> levelProgress;

    public GameStateData(GameState gameState)
    {
        levelProgress = gameState.levelProgress;
    }
}

public class GameState : Singleton<GameState>
{

    // Prevent non-singleton constructor use
    protected GameState() {  }

    // declare variables
    public Dictionary<int, Dictionary<int, float>> levelProgress = new Dictionary<int, Dictionary<int, float>>();

    #region Load / Save Methods
    public void LoadGame()
    {

        string path = Path.Combine(Application.persistentDataPath, "game.save");

        if (File.Exists(path))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = new FileStream(path, FileMode.Open);

            GameStateData data = formatter.Deserialize(stream) as GameStateData;
            stream.Close();

            // overwrite current data with loaded data
            levelProgress = data.levelProgress;
        }
    }

    public void SaveGame()
    {
        BinaryFormatter formatter = new BinaryFormatter();

        string path = Path.Combine(Application.persistentDataPath, "game.save");
        FileStream stream = new FileStream(path, FileMode.Create);

        GameStateData data = new GameStateData(this);

        formatter.Serialize(stream, data);
        stream.Close();
    }
    #endregion

    public void UpdateLevelProgress(int levelPackId, int levelId, float time)
    {
        if (!levelProgress.ContainsKey(levelPackId))
        {
            levelProgress.Add(levelPackId, new Dictionary<int, float>());
        }

        // set time
        levelProgress[levelPackId][levelId] = time;

        // save to file
        SaveGame();
    }

}

```


texts:
Here is a Pastebin of my OBJ file created using Solidworks 3D
https://pastebin.com/6MgQBF8J
I don't understand how the number of vertices (645) can be larger than the number of normals (306)
I understand that some vertices have the same exact coordinates, but how is a programmer supposed to know which normals correspond to which vertices?
Since there are no indexes to map normals to vertices, do I need to get rid of the duplicates first until the number of normals and vertices is equal?
But then why are the duplicates there in the first place?
Or do I need to create normals equal to zero for the remaining vertices?
Thanks,


texts: I have made a game that was supposed to be for mobile but now I need to build it for PC. I want the aspect-ratio to be 2:3 but as you can see on the image that doesn't exist. How do I add a custom aspect-ratio for the build?


texts: Component based game design and sharing mesh data

texts:
Lets say you make a game engine, and you have several GameObjects and every GameObject have a list of components that you can add or remove.

Lets say there is a MeshComponent who has vertices, normals etc. If several GameObjects have the same MeshComponent, there will be a lot of memory waste. Of course there are many ways to implements this but I want some good advice how to solve this? How do components share data that is not going to be modified?


texts: I want to make a .stl file to be 3d printed through blender, but I don't know how I would see the real size. Does anyone have any solutions? Also, if you turn on smooth shading, will it actually be smooth IRL or just the shading?


texts: Using XNA to create an isometric tileset?

texts:
In XNA, how can I take any given texture, then render it so that it fits completely into a 64x31 (or 32x15) isometric tile such that it tessellates perfectly? My goal is to give various textures to my game, then have it generate an isometric tileset from the given textures, thus requiring pixel-perfect accuracy.

I have tried to use an orthogonal projection, which has good (but imperfect) results, but always ends up making odd-width textures instead, such as 61x29; no amount of adjusting the camera position or target or orthagonal settings seems to correct this, textures always end up with 1, 3, or 5 pixels on the top or bottom of the tile:

How can I correct this behavior, or is there a better way I can create multiple isometric tiles easily?

Edit: Before anyone asks, I'm not trying to clip or mask anything when I render it. I'm trying to preserve as much of the texture as possible and push it cleanly into a specific space.


texts: I have seen a lot of questions about making a game using Google app engine. I have run into a problem that I cant seem to find any answers to. What can I actually use to draw my game? Are there any libraries that GAE supports? Any feedback is appreciated.


texts: Hardcode per-instance properties into the shader in unity

texts:
I am using one of the packages from the asset store and using its Polyline feature for wire rendering. There are thousands of wires and its taking much fps/Batch counts. The reason of the lack of support for static batching. Now there is a workaround suggested by the author of the package.

if you don't use polylines for anything other than that, and all your
shaders use the same properties, you could hardcode all per-instance
properties into the shader

Due to a lack of shader knowledge(I am developing the knowledge currently and it will take time) I am unable to hard code the above properties: I tried and here is the current scenario:
#define int _ScaleMode = 1
#define half4 _Color = (0,0,0,0)
#define float4 _PointStart = (0,0,0,0)
#define float4 _PointEnd = (0,0,0,0)
#define half _Thickness = 0.5
#define int _ThicknessSpace = 1
#define half _DashSize = 1
#define half _DashOffset =1
#define int _Alignment =1

HOw do i correctly hard code above values?


texts:
So after finishing a 2d game for my school project, I decided to dive into 3d world by using raylib instead of Unity. Raylib does provide a simple implementation of 3d camera without you doing maths, but instead I want to challenge myself to understand trigonometry in 3d.Here, I am trying to make the camera rotate upside down and left right(like it's orbiting). After implementing the math, it seems like it only works when the target is at Vector3{0.0f, 0.0f, 0.0f} position. If the target position gets further and further, the rotation gets weird. Here is the demonstration video that I uploaded to youtube.

https://www.youtube.com/watch?v=MpXkhGy60HA&feature=youtu.be

And below is my code for math:

Vector3 cubePosition = { 0.0f, 0.5f, 0.0f };

Camera3D camera = { 0 };

camera.position = { 0.0f, 10.0f, 10.0f }; // Camera position

camera.target = { 0.0f, 0.0f, 0.0f }; // Camera looking at point

camera.up = { 0.0f,2.0f, 0.0f }; // Camera up vector (rotation towards target)

camera.fovy = 45.0f; // Camera field-of-view Y

float distance = 15.0f; // Set the distance from camera.target to camera.position

float verticalAngle = 45.0f; // The Y/XZ angle

float horizontalAngle = 90.0f; // The X/Z angle, y is considered as 0

float horizontalDistance = distance * cosf(verticalAngle * PI / 180.0f); // Horizontal distance, the magnitude

camera.position.x = horizontalDistance * cosf(horizontalAngle * PI / 180.0f); // Calculate the position of camera.position x based on distance etc..

camera.position.z = horizontalDistance * sinf(horizontalAngle * PI / 180.0f);

camera.position.y = distance * sinf(verticalAngle * PI / 180.0f);

Vector3 selectedTarget = cubePosition;

And for the main loop :

if (IsKeyDown(KEY_A))

{

camera.position.x = horizontalDistance * cosf(horizontalAngle * PI / 180.0f);

camera.position.z = horizontalDistance * sinf(horizontalAngle * PI / 180.0f);

horizontalAngle -= 1.0f;

}

else if (IsKeyDown(KEY_D))

{

camera.position.x = horizontalDistance * cosf(horizontalAngle * PI / 180.0f);

camera.position.z = horizontalDistance * sinf(horizontalAngle * PI / 180.0f);

horizontalAngle += 1.0f;

}

else if (IsKeyDown(KEY_W) && verticalAngle < 88.0f)

{

horizontalDistance = distance * cosf(verticalAngle * PI / 180.0f);

camera.position.x = horizontalDistance * cosf(horizontalAngle * PI / 180.0f);

camera.position.z = horizontalDistance * sinf(horizontalAngle * PI / 180.0f);

camera.position.y = distance * sinf(verticalAngle * PI / 180.0f);

verticalAngle += 1.0f;

}

else if (IsKeyDown(KEY_S) && verticalAngle > 2.0f)

{

horizontalDistance = distance * cosf(verticalAngle * PI / 180.0f);

camera.position.x = horizontalDistance * cosf(horizontalAngle * PI / 180.0f);

camera.position.z = horizontalDistance * sinf(horizontalAngle * PI / 180.0f);

camera.position.y = distance * sinf(verticalAngle * PI / 180.0f);

verticalAngle -= 1.0f;

}

if (IsKeyPressed(KEY_RIGHT))

{

camera.position.x += 1.0f;

selectedTarget.x += 1.0f;

}

else if (IsKeyPressed(KEY_LEFT))

{

camera.position.x -= 1.0f;

selectedTarget.x -= 1.0f;

}

if (IsKeyPressed(KEY_UP))

{

camera.position.z -= 1.0f;

selectedTarget.z -= 1.0f;

}

else if (IsKeyPressed(KEY_DOWN))

{

camera.position.z += 1.0f;

selectedTarget.z += 1.0f;

}

if (IsKeyPressed(KEY_SPACE))

{

cubeList.push_back(selectedTarget);

}

camera.target = selectedTarget;

Since raylib is using opengl so i tried to use the following link and picture to understand the camera system.
https://learnopengl.com/Getting-started/Camera

This is the picture I used to calculate my camera position.
https://uploads.disquscdn.com/images/58fa1f1a3dd8d736a9345b3b168dd55caf0f14d485e9dae7e06b8e185348a42a.png

Any help would be appreciated. Thank you..


texts: How to increase vertical Nav Mesh detection for AI Actors? Using Default Query Extent?

texts:
For my swimming AI, I wish to use a Nav Mesh, so they may avoid obstacles and swim up and down - preferably.

I figured I should try to solve this with a nav mesh, since UE4 has kindly implemented it for us.

To avoid having the Enemy Fish stick to the "ground" of the map, I would have to increase the Query Extent, which is testable with a Navigation Testing Actor (see images below).

So what I did:

Add Nav Mesh Bounds volume;
Add AI Actor with Character Movement Component;
Increase Default Query Extent in Project Settings (Engine > Navigation System).
No Profit?

Increasing the Default Query Extent, under Agents, increases it along the positive and negative Z-Axis, which is unfortunate, since I would like the AI to prioritize the bottom Nav Mesh surface.

I have attached two screenshots showcasing the "bad" behaviour, which I would like to circumvent.

The blue Bounding Box, showcases the Extent, which is scaled in both directions, vertically. Preferably, I would like to move it down, relative to the Nav Agent.

To hit the point home, here is what happens when the enemy swims underneath some platform (For simplicity, being the cube):

So my question to you good people is: how would I lower the Nav Mesh detection, without increasing the actor size, or something rather silly. Is there a clean way of having the "Enemy Fish" ignore the top platform as much as possible, without using a Nav Modifier Volume ?


texts: OnRoomConnected always fail (Google play service unity3d)

texts:
OnRoomConnected always return false, Im stuck...(Authenticate is success).
Thank you for attention.

private List<Participant> participants;

public void Authenticate()
{
    PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
        .Build();

    PlayGamesPlatform.InitializeInstance(config);
    // recommended for debugging:
    // PlayGamesPlatform.DebugLogEnabled = true;
    // Activate the Google Play Games platform
    PlayGamesPlatform.Activate();

    Social.localUser.Authenticate((bool success) =>
    {
        if (success)
        {
            Debug.Log("Authentication succeeded");
            //CreateQuickGame();
        }
        else
        {
            Debug.Log("Authentication failed");
        }
    });
}

public void CreateQuickGame()
{
    const int MinOpponents = 2, MaxOpponents = 2;
    const int GameVariant = 0;
    PlayGamesPlatform.Instance.RealTime.CreateWithInvitationScreen(MinOpponents, MaxOpponents, GameVariant, this);
}

#region RealTimeMultiplayerListener implementation

public void OnLeftRoom()
{
    SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex);
}

public void OnParticipantLeft(Participant participant)
{
    SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex);
}

public void OnPeersConnected(string[] participantIds)
{
    Debug.Log("OnPeersConnected");
    byte[] message = Encoding.ASCII.GetBytes("Test"); // build your message
    bool reliable = true;
    PlayGamesPlatform.Instance.RealTime.SendMessageToAll(reliable, message);
}

public void OnPeersDisconnected(string[] participantIds)
{
    //SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex);
}

public void OnRealTimeMessageReceived(bool isReliable, string senderId, byte[] data)
{
}

public void OnRoomConnected(bool success)
{
    if (success)
    {
        Debug.Log("Room Connected success");

        MainScene ms = new MainScene();
        ms.Waithing_sprite.SetActive(true);
        // Successfully connected to room!
        // ...start playing game...
        //PlayersNames[0] = participants[0].DisplayName;
        //PlayersNames[1] = participants[1].DisplayName;
        //PlayersNames[2] = participants[2].DisplayName;
        //GenerateBoard();
        //bool reliability = true;
        //string data = "Instantiate:0:1:2";
        //byte[] bytedata = System.Text.ASCIIEncoding.Default.GetBytes(data);
        //PlayGamesPlatform.Instance.RealTime.SendMessageToAll(reliability, bytedata);
    }
    else
    {
        Debug.Log("Room Connected FAIL");
        PlayGamesPlatform.Instance.RealTime.LeaveRoom();
        //Loading.text = "Error!";
        //Back.SetActive(true);
        // Error!
        // ...show error message to user...
    }
}

public void OnInvitation(Invitation invitation, bool shouldAutoAccept)
{
    // handle the invitation
    if (shouldAutoAccept)
    {
        PlayGamesPlatform.Instance.RealTime.AcceptInvitation(invitation.InvitationId, this);
    }
    else
    {
        // do some other stuff.
    }
}

public void OnRoomSetupProgress(float progress)
{
    Debug.Log("Room Progress Waithing players");
    List<Participant> participants = PlayGamesPlatform.Instance.RealTime.GetConnectedParticipants();
    // show the default waiting room.
    if (participants.Count != 3)
    {
        PlayGamesPlatform.Instance.RealTime.ShowWaitingRoomUI();
        Debug.Log("Room Progress Waithing players");
    }
    else
    {
        Debug.Log("Room Progress 100");

        MainScene ms = new MainScene();
        ms.MoveToGame();
        PlayersNames[0] = participants[0].DisplayName;
        PlayersNames[1] = participants[1].DisplayName;
        PlayersNames[2] = participants[2].DisplayName;
    }
}


texts: How can SpriteBatch use a single texture/asset as multiple independent objects/instances

texts:
I'm using LibGDX to create a game, but I'm encountering a problem with SpriteBatch. Whenever two objects that use the same image for their sprite come onto the screen, the new object replaces the old object. So, for example, one ship will come onto the screen, and when a ship with the same sprite comes onto the screen, the old ship will disappear and the new ship will have all the damage and other characteristics of the old ship.

I could always make multiple copies of the same image and put them in the assets folder, but that seems unnecessary. Does anyone have any ideas? Am I using SpriteBatch incorrectly?

Edit: Here's a couple of examples of rendering methods in the game loop.

The method for rendering ships:

private void renderDoodad(Doodad doodad) {
    if (!doodad.isDisabled()) {

        batch.begin();
        if (doodad instanceof Enemy) {
            batch.draw(doodad.getSprite(), doodad.getX(), doodad.getY());

Followed by some code about what to do if the ship is the player's ship. But the player's ship is rendering fine, so I left that out.

Then there's the method for rendering shots:

    private void renderShot(Shot shot) {
    if (!shot.isDisabled()) {
        batch.begin();

        batch.draw(
                shot.getSprite(),
                shot.getX(),
                moveDoodadY(shot, shot.getDirection().getVal()
                        * getApp().getGraphics().getDeltaTime()));
        batch.end();
    }
}


texts:
So i have some procedurally generated mesh data and i want to reduce it down to its minimum number of verts. In case it matters this is a unity project.

Working on the basis of a simple example, lets assume a typical flat surface of points 2 by 3.

The point / vertex at [1,1] is used in many triangles.

I've generated mesh for a voxel type engine that adds verts to a list based on face visiblility and now I want to remove all the duplicates.

Can anyone come up with an efficient way of doing this because what i have is sooo bad its not even funny (and i don't even think it's logically correct) ...

private void Optimize()
{
    Vector3 v;
    Vector3 v2;
    for (int i = 0; i < Vertices.Count; i++)
    {
        v = Vertices[i];
        for (int j = i+1; j < Vertices.Count; j++)
        {
            v2 = Vertices[j];
            if (v.x == v2.x && v.y == v2.y && v.z == v2.z)
            {
                for (int ind = 0; ind < Indices.Count; ind++)
                {
                    if (Indices[ind] == j)
                    {
                        Indices[ind] = i;
                    }
                    else if (Indices[ind] > j && Indices[ind] > 0)
                        Indices[ind]--;
                }

                Vertices.RemoveAt(j);
                Uvs.RemoveAt(j);
                Normals.RemoveAt(j);
            }
        }
    }
}

EDIT:
Ok i managed to get this (code sample above updated) to render an "optimised" set of verts but the UV data is all wrong now, which would make sense because i'm basically just removing any UV Vector that represents a UV coord for a removed vert and not actually considering what I need to do to "fix the tri" so to speak.

The code now seemingly does work but its quite time consuming, still looking to further optimise.


texts: In behavior trees, how do you retain your place in a sequence?

texts:
For context, I am coding a naive implementation of behavior trees myself, in C#. Let's say I have two scenarios that I want to create behaviors for. Both AI's will traverse/patrol four specific locations (markers), in order, and then repeat the path.

AI 1) Upon seeing the player, freeze. Once the player is out of sight, begin patrolling again, but from the very first marker (i.e. restart).

AI 2) Upon seeing the player, freeze. Once the player is out of sight, begin patrolling again, but from whatever marker it was previously on before being interrupted by the player (i.e. carry on).

I would expect both of these behaviors to be modeled by first checking for the player, and if that fails proceeding further down to a Sequence node that contains four children, each being a "traverse to maker" behavior.

In other words -> after a behavior is interrupted by a node higher up the tree, how do I retain the current place in a sequence and carry on when we finally make it back down the tree again?


texts: Designing client-server to mitigate hosting advantage?

texts:
My game will be client-server, and I'd like to prevent the hosting player from enjoying the usual benefits you'd associate with playing on a server.  For example, the advantage of the server running ahead of time compared to clients.

Are there simple ways of mitigating host advantage?  Or do I have to make something complicated?  My naive solution would be having the host run a "ghost" state, and a client state, on the same map.

The ghost state is an authoritative server simulation, it doesn't render the simulation which remains invisible, but does run ahead of time making calculations and decisions as usual.  The host also plays a client on the same map, in which their input is regarded as any other client across the network, and like any other client is required to wait for the server simulation to make and transmit outputs.  And so the host doesn't enjoy an advantage because they aren't playing the simulation which is making executive decisions on the game state ahead of client time.

Has this solution been done by any other games, or is there a better way of handling the problem?


texts: How to rotate a rigidbody with a Pid controller

texts:
I would like someone to describe me how to use a PID controller to rotate a rigidbody with AddTorque to a specific position. (like a spacecraft that rotates the Y axis of rotation towards Camera.forward for example). Can anyone show it to me with a script?

Actually I already use this script to rotate with AddTorque but the object almost never stops at the precise point.

Vector3 camForward = Camera.main.transform.forward;
Vector3 rbForward = rb.transform.forward;
Vector3 torqueY = Vector3.Project(torque, Vector3.up);
Vector3 torque = Vector3.Cross(camForward, rbForward);
rb.AddTorque(torque);
rb.AddTorque(-rb.angularVelocity);


texts: I want to test the Animator component of a gameobject using nunit, but I am having issues

texts:
I made a Blender 3D model with animations. Then I used the Animator Controller, and attached it to the model. The Animator Controller has a few Boolean parameter variables like isWaving, isDoing, and isIdle and more variables like that. If, say, a non-idle action is true, then the animation of my model transitions to the next one. I am into test-driven development, but I have never done it with Unity.

I tried writing the following code to test my project:

[SetUp]
public void SetUp()
{
    Crystal = GameObject.FindGameObjectWithTag("CrystalModel");
    CrystalScript = Crystal.GetComponent<CrystalChanPlayer>();
    CrystalAnimator = Crystal.GetComponent<Animator>(); // unity game animator
}

[Test]
public void ifSetAnimationIstodoThenToDoAnimationIsPlayed()
{
    CrystalScript.setAnimationStrategy("todo"); // set strategy
    CrystalScript.playAnimation(); // sets todo boolean to true and idle to false

    // first debug output
    Debug.LogError("todo is " + CrystalAnimator.GetBool("isDoing") +
        " idle is " + CrystalAnimator.GetBool("isIdle"));

    //second output
    Debug.LogError("current state is " +
        CrystalAnimator.GetCurrentAnimatorStateInfo(0).IsName("idle"));

    Assert.True(CrystalAnimator.GetCurrentAnimatorStateInfo(0).IsName("todoAnimation"));
}

I received the following output:

  "todo is true and idle is false"
  "true"

I think this is because Unity isn't really running, and my Animator doesn't get to update based on the variable changes. The first output assures me that todo is set to true and idle is false, hence the Animator should transition that animation to the todoAnimation. Yet, I can't seem to show that, in my tests.

Is there any way to test the Animator class? Are there any design patterns I can use?


texts: Updating a game without the player having to start a new world

texts:
So im building a game in GameMaker(A engine im good with), the development is going great and im making good progress. (Not going to go into detail about the game, its unrelated) but the problem i have is that when i do an update the player is required to start a new game as you cant load an old world into the new version (Not sure why, although i think i know) and i want a system that will just update the players current world with the new items, creatures etc. i have tried making the game use older versions of the save file, but it just loads the save file without the new items and creatures.

Edit i think i cant load a old world into the updated game because of it only having the save for the old items etc.(Not sure if this is correct though)
Edit 2.0 the version is the games version, say if i tried to update to version 2 and the save is version 1, it wont load version 1 with the updated stuff in version 2.


texts: Revamping my GUI to be more efficient and less brute

texts:
I am building a Java game from scratch right now. So far, it runs fine, but the issue is with my GUI and how it works. Basically, it's a tile-based game. Each time the person moves a different image is displayed (basically I check to see what terrain they are on, and in what direction they moved then update that tile's Imageicon). I feel like it is a lot of brute force graphic work and I was wondering if anyone here could help me find a simpler method or class to preform the action. I use ImageIcons to basically make the game's GUI function right now. I was thinking about finding a way to have "layers", so I could have the terrain in the background and my person could just walk over it. Unless someone has a better idea.

Another long-term goal is to make the walk movement an animation. Right now, the person just pops over 1 tile, I want to implement some basic walking animation for that movement of tile to tile. I feel like that would be easier to do if I had a way make the person be a separate object compared to the terrain/map.

Any suggestions on how to do this would be very helpful! :)

IMAGE REQUEST:
Here is an older and later dated image of one region. Basically, I have a tile (ImageIcon) for each possible instance of where the hero is, and which way he is facing. But as stated, I want to get rid of that because it requires soooo much. There has to be an easier way to overlap the person and allow animation to each tile.


texts:
I'm making an engine in C++ with Lua for its scripting language (using LuaBridge as the binding).
I have a lot of entities and those entities have components. One of the components on those entities is a script component. Every time I want to call a different function from a Lua script, I always have to call luaL_dofile. If I call this with more than 20 scripts, my game takes too much time per frame reducing it to 5 FPS on my machine. Every script has an Init, FixedUpdate, Update, and Shutdown function. For every script, I call all of these functions in order.
Is there a way to reduce the latency introduced in each frame from using Lua?

Some pseudo code of my usage of LuaBridge:

    // In Update function:
    for (int i = 0; i < scripts.size(); i++)
    {
        luabridge::LuaRef func = luabridge::getGlobal(L, "Update");
        if(func.isFunction())
          func(dt);
    }


texts:
I have a class TileChunk which at it's most basic contains a rectangle that surrounds the chunk,  and four bools isLeftLoaded, isTopLoaded,  etc. Using the rectangle I can determine which chunk the player is in.

What I want to do is create some kind of method which checks the current chunk the player is in, and if nothing is loaded then create new chunks that surround the sides that haven't been loaded.  The problem I'm coming across is that using the four bool variables doesn't seem to work correctly. At initialization, I create 9 chunks to make a 3x3 starting area but some of the bool variables aren't being set correctly.

My question is how should I write a method which determines what chunks have loaded chunks adjacent to them? Every chunk is stored in a List, but other than using the bool variables I'm not sure what is the best way to do this.


texts: Rendering model with multiple tiling textures

texts:
See edit:

How would I go about rendering a model with multiple tiling textures? I have a few ideas, but all of them have drawbacks, here are a few (by the way this is for an opengl game):

-Use a huge texture, but this comes at the cost of the texture being expensive

-Render diffrent objects for each textured object (eg: one model could be bricks for a house, another could by the roof, each with their own tiled texture), but this would become very messy, very quickly.

Here is an (amazing) image to help demonstrate what I'm trying to do.

The repeating "R" on the red area represents perhaps a repeating brick texture, while the green one represents a roof, maybe roof shingles. To add on to that, I've added a window texture.

My question is, how do most games deal with this? I can't seem to wrap my head around how I could fit this in one texture, but yet I see many other games do exactly what I want.

EDIT:

This should give a better visual demo. I want a large mesh (not very large in the demo) using one texture atlas. (Please keep in mind not all textures in the atlas will be the same size!)

Lets say this is my object, it uses each texture on the atlas, but not the same amount of repeats (brick repeats 3 times, when the smiley face repeats 9 or so times)

How do most games achieve something like this? Without using some huge file with repeating textures.

Example (from BOTW)
I assume they didn't just repeat this texture on the atlas, considering how large that would be (and expensive).


texts: I've been wondering about this issue for a while. How to find the bottleneck of the graphical pipeline. Recently I've been using a program to draw massive amount of polygons in a simple scene with alpha blending (AKA grass scene). I've used two programs, one uses static coordinates and another uses rotation and translation. Both run at 60 FPS with no other heavy processes running. But when I use them together (Two windows each having same amount of grasses and grass positions) the one that uses translation and rotation runs at 10 FPS but the other one is about 55 FPS. My question is why are both running @ 60 FPS and when such thing happens why does the second one(Rotation and translation of each grass) drop about 50 FPS but the second is still 55? Sounds like a bottle-neck to me. Please let me know if you have any idea, or in a more general answer if you have an idea or paper about finding bottleneck of GPU(or GPGPU), or optimizing the graphical code for running on GPU?


texts: How to make a fade effect on the Unity's scrollView?

texts:
I have a basic ScrollView, with some additional scripts so it snaps to the nearest element (focusing on it).

When I perform the scroll, it looks like this:

What I need to achieve is to fade the part which is currently going off the screen.

Like when I'm scrolling left, the right panel is coming in, and the left one - fading out:

Is there any built-in option for this? I'm opened for any ideas!


texts:
Problem

Player obtains 5 points per level up to level 80 with a maximum of 400.
There are 5 stats to be distributed to and no maximum limit to how much you can add to a stat.

Strength
Endurance
Intelligence
Agility
Luck - Grants critical chance and critical damage

I would like to implement a diminishing return equation on let's say Luck. For critical chance, I do not wish for the player to be able to hit 100% critical chance.

There will be a ceiling to which it will reach as the increasingly decreasing growth reaches towards 0 per point added.

Example if the maximum critical chance I want the player to have is 40%, Each point into luck will increase critical chance lesser and lesser, until the critical chance reaches around 40%. By which 1 luck will give a very very miniscule amount.

Any solutions? Thank you and your help is greatly appreciated!


texts: Do I need to delete a texture after calling SDL_DestroyTexture()?

texts:
Let's suppose I have this texture:

SDL_Texture* txt = IMG_LoadTexture(renderer, "path");
/* various code */
SDL_DestroyTexture(txt);
delete txt; // <- Is this part really necessary? Doesn't SDL_DestroyTexture() does it already?

Since there's not a lot of documentation about SDL, I haven't found an answer to my question on my own.


texts: UGUI canvas and NGUI panel overlap- set sorting order

texts: I have a NGUI dropdown panel and a UGUI (Unity UI) panel. All are working fine but there is a small problem. When I open the NGUI dropdown panel meanwhile my GUI panel is also open, then NGUI dropdown panel appears behind the UGUI. Is there any way available that I combine both GUIs sorting order so that i should display the NGUI panel on top of UGUI panel?


texts: How can I allow player-created content to add morphs to Daz Genesis 8 characters(UE4)?

texts:
We use Daz Genesis 8 characters in our project. Content creators would load their morphs from Daz to our game. We would like to add these morphs to our characters so they can be modded, edited and stuff. The problem is we already have morphs on our chars, and we don't want to lose them! I simply would like to add morphs to the list of morphtargets so I can expose them to the player!
Can anyone direct me to the right c++ classes, blueprints, git repos, assets or anything to look at?
Thanks


texts: Tile Based A* Pathfinding, but with a bomb

texts:
I've written a simple A* path finding algorithm to quickly find a way through a tile based dungeon in which the tiles contain the information of walls.

An example of a dungeon (only 1 path for simplicity):

However now I'd like to add a variable amount of "Bombs" to the algorithm which would allow the path-finding to ignore 1 wall. However now it doesn't find the best paths anymore,

for example with use of only 1 bomb it generates paths like these:

While the correct shortest path would be this one:

The problem is that "Closed Nodes" now interfere with possible paths. Any ideas of how to tackle this problem would be greatly appreciated!