texts:
I am trying to implement shadow mapping, and currently I have 2 point lights and 1 global ambient light source and my rendering loop looks roughly like this (the details are not relevant):

void OpenGLRenderer::DrawRenderables(const uint32_t windowWidth, const uint32_t windowHeight, const RenderQueue& renderQueue, const RenderableLighting& lighting)
{
    GLCALL(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));

    for (uint32_t lightIndex = 0; lightIndex < lighting.mUsedLights; lightIndex++)
    {
        if (lighting.mLights[lightIndex].mLightType == LightType::LIGHT_TYPE_POINT)
        {
            GLCALL(glUseProgram(mShadowMapProgram.mProgramHandle));
            GLCALL(glBindFramebuffer(GL_FRAMEBUFFER, mFrameBuffer));
            GLCALL(glViewport(0, 0, mShadowTextureWidth, mShadowTextureHeight));
            for (uint32_t faceNum = 0; faceNum < CUBEMAP_NUM_FACES; faceNum++)
            {
                GLCALL(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_CUBE_MAP_POSITIVE_X + faceNum, mShadowMapTexture, 0));
                GLCALL(glClear(GL_DEPTH_BUFFER_BIT));

                ShadowPass();
            }
            GLCALL(glBindFramebuffer(GL_FRAMEBUFFER, 0));

        }

        // final pass
        GLCALL(glUseProgram(mDefaultProgram.mProgramHandle));
        GLCALL(glViewport(0, 0, (GLsizei)windowWidth, (GLsizei)windowHeight));

        // enable blending, how?

        ShadingPass();
    }

    GLCALL(glUseProgram(0));
}

The problem is the screen will only be shown with last light in the light list, for example the ambient light and therefore ignoring the effects of the point lights. I assume I somehow needs to do blending but I was wondering how and where is this done?

Thanks


texts: Retain Position and Scale Values of Render Texture Canvas Elements to another Canvas

texts:
Now the title might not be able to express the entirety of the question but here's my problem. In my main scene I have a camera and a canvas in overlay mode, let's call this "View A". In this view is a crosshair which position and size I want to manipulate depending on elements inside the canvas of "View B". "View B" is located in the main scene as a render texture it contains a camera and a canvas in camera space with another crosshair. Now what I want to do is the following: I'm trying to set the position and size of the crosshair in "View A" to practically overlap with the values of the crosshair in "View B", i.e. if the crosshair in "View B" is in the lower left corner of its screen I'd like the crosshair in "View A" to be in the same position with the same size but in the canvas of "View A".

What I'm currently capable of is setting the crosshair in "View A" to the same location as the crosshair in "View B" but only if the crosshair in "View B" is in its origin, as all I have to do in that case is to get the origin of the render texture quad in the screen space of "View A" canvas. I do this in the following way:
RectTransformUtility.ScreenPointToLocalPointInRectangle(CanvasTransform, CameraComponent.WorldToScreenPoint(RenderTextureQuadTransform.position), null, out Vector2 localPoint);
CursorTransform.localPosition = localPoint;

But now I'm stuck in figuring out how to get a scale factor that makes the crosshair in "View A" and "View B" look the same size and how to adjust the position of the crosshair in "View A" depending on the position of the crosshair in "View B".


texts: Elements of uniform array are always zero?

texts:
I'm building a shader program to render a simple bitmap font in GLSL.

My programming environment is C# so I'm using OpenTK to encapsulate OpenGL 4.0, but the syntax is very similar to any examples in C and C++.

My issue is that I'm trying to pass an array of integers to the fragment shader, but whenever I do, all the array elements end up being zero. The integers should range between 0 and 255 and I've checked the values before and after sending them. It's infuriating.

Currently I'm binding my program, then attempting to send the int[] array to the shader using the following instructions:

int[] ints = new int[] { 33, 34, 35, 36, 37, 38, 39, 40 };
GL.UseProgram(programLocation);
GL.Uniform1(arrayLocation, ints.Length, ints);

My fragment shader takes the array and uses a couple of functions to determine which part of the quad to place which characters. I've tested these functions with static numbers and arrays I build manually in the shader and they work just as I'd expect them to. For some reason the syntax above simply doesn't actually end up sending any data - all elements evaluate to 0.

In my shader, the array is denoted and used like this:

uniform int characters[8];
....
gl_FragColor = texture2D(bitmapFontTex, GetBitmapFontStart(characters[0...8etc]));

The rest of my code seems to work when tested in isolation - it only falls apart when it comes together, and the above code blocks are where it comes together. Have I made some silly rookie mistake, or is there something more screwy happening? Any help greatly appreciated.


texts: Texture rebind on android cause potential memory leak?

texts:
After context lost, I have to rebind all my textures. I want to it the correct way, so I check each handle for availability. It's done by calling unloadFromVram(), and then loadToVram()

first unload:

public final void unloadFromVram()
{
    GLContextState.forgetTexture(handle); // invalidate cache

    if (glIsTexture(handle)) // check whether handle is still a texture instance.
    {
        glDeleteTexture(handle); // delete handle if it is a texture instance.
        handle = GL_NONE;
    }
}

upload again:

public final void loadToVram()
{
    handle = glGenTexture();

    GLESContextState.activateTextureInSlot(0, handle); // GL.glActiveTexture(glSlot) and GL.glBindTexture(GL.GL_TEXTURE_2D, texture);

    if (owner.isCompressed())
    {
        glCompressedTexImage2D(GL_TEXTURE_2D, 0, format, textureData.getWidth(), textureData.getHeight(), 0, textureData.bytes);
    }
    else
    {
        glTexImage2D(GL_TEXTURE_2D, 0, format,textureData.getWidth(), textureData.getHeight(), 0, format, type, textureData.bytes);
    }
}

What have I investigated:

After doing so, most of my textures appears black or have invalid content (perhaps from other textures, or content which was bound to this handle before suspend).
If glIsTexture(handle) fails, and the handle has not to be deleted - the texture behaves just fine.
If I comment the whole check and deletion in unloadFromVram() - everything works just fine.

I suppose, if I won't delete bound handle - it will cause a memory leak, due to texture's data is still in memory, so I have to avoid it. What do I have to do with this?


texts: Help choosing a collision prediction method?

texts:
This takes a little backstory, bear with me.

This is also a very general question, and I'm aware that without greater specifics the best answer might be "it depends."

So the context is that we're doing a real-time two-player iPhone game, with one iPhone acting as host and the other as client.

One of the things that's happening in the game, that needs to sync properly across devices, is similar to a Break-Out style situation: multiple rows of bricks at the top of the screen and a ball that bounces up and destroys them.

The wrinkle is that the projectile is more like a bullet than a ball. It takes out all the bricks in its path.

So to sync this across devices, what we're doing is calculating all the bricks that will be hit as soon as the bullet launches along a given trajectory. We have to do this because due to the physics model we're using, if we just launch the bullet at the identical angle and identical velocity on each of the two devices, the bullet ends up taking out slightly different bricks on each device.

So that's the task at hand: we need a calculation of all the bricks that will be taken out by a given bullet. Once we have that, we can send that array to the client, and then (ideally) the clients knows what bricks to take out before the bullet actually hits them, and the games sync infinitely better than if the collisions were reported in real time.

The last important element to consider is that there can be lots of bullets shooting at once. Anywhere from 4-40+ of these arrays need to be calculated as rapidly as possible.

So what's the best way to do it? We've thought of two ways:

1) Drawing an imaginary line along the path of the bullet and detecting all the bricks it intersects.

2) Shooting a separate invisible bullet along the normal bullet's path at something like 20x faster velocity. This "phantom bullet" doesn't cause any reaction upon contact with the bricks, it just passes right through them. But when it passes through a brick, that brick gets added to an array, and it ends up creating the array we need.

I should note that we've actually implemented option 1, and it works really well. The only problem is that when we get upwards of ten or twenty bullets it seems to cause massive slowdown. We're considering option 2 to try to boost framerate because we think it would be easier on the processor.

So, we're looking for a way to figure out if that's true.

I know that different physics simulators are different, and everything is different and difference is different and etc. etc. different, but I guess I was wondering if anyone has a general idea whether or not, in general, one of these methods should perform better than the other.

I'm hoping there's some knowledgeable individual here that can provide insight--or even suggest a simple test we could do to find out for ourselves.


texts:
I started reading about game development design patterns and from my experience there are 2 options for update methods. The first one receive from the game loop and delta time of this update and multiple everything by it, for example position += speed * delta_time. And this will happen in the game loop without delay.

The second option is too set constant frame delay and use it. In the end of the loop function you use sleep(last_frame_time + frame_length - current_time).

Does it matter what do I use? What's more common? I know unity use the delta time technique but it's the only one I saw that use it. I would like to hear your opinions on what to use for both options.

Should I always use the first option? always the second?

Thank you for your time.


texts: VBO and shaders confusion, what's their connection?

texts:
Considering OpenGL 2.1 VBOs and 1.20 GLSL shaders:

When creating an entity like "Zombie", is it good to initialize just the VBO buffer with the data once and do N glDrawArrays() calls per each N zombies? Is there a more efficient way? (With a single call we cannot pass different uniforms to the shader to calculate an offset, see point 3)
When dealing with logical object (player, tree, cube etc), should I always use the same shader or should I customize (or be able to customize) the shaders per each object?
Considering an entity class, should I create and define the shader at object initialization?
When having a movable object such as a human, is there any more powerful way to deal with its coordinates than to initialize its VBO object at 0,0 and define an uniform offset to pass to the shader to calculate its real position?


texts: What is the most serious limitation of Unity?

texts:
Having read this heated question about Unity vs. UDK vs. ID something, I'm curious to know: what the repeatedly-hit, most crippling limitation(s) of Unity?

In order to keep this question non-subjective, again, I'm talking about the top repeated offender(s) of Unity are. This is something that, as a Unity user, you really wish someone had told you about before you started using it.

I have heard from someone that Unity does not deal well with version control, since it generates a lot of binary files (which are un-diffable). This, to me, is not really crippling as I work alone.

Thoughts?


texts: Additive, Alpha Blended, Unlit, Lit differences?

texts:
Short question, what's the difference between the shaders used for particle, and how they affect the visual.

Additive
Alpha Blended
Unlit
Lit


texts: Having problems exporting Genesis + Supersuit in .fbx format from Daz 3D

texts:
I created a new scene. Loaded the Michael 5 Hero character. Added the Supersuit. Then posed the M5 character using "M5 Walking 1" pose from the "M5 General Poses" collection.

My problem is that whenever I import the fbx file into another software (like Maya or Unity), my genesis figure appears to be in that pose (M5 Walking 1), but the supersuit still remains in the default T-pose!

Please tell me how to rectify this.


texts: Problematic cameraposition (Eye = (0,0,0), at=(0,-2,0) and up = (0,1,0))?

texts:
I am taking a course in computergraphics and we talk a lot about OpenGL and the math you need to do everything OpenGL does "by hand". A Question which was asked in an old exam (I am preparing at the moment) was:

Why is the following Cameraposition considered problematic?
eye = (0,0,0), at=(0,-2,0) and up = (0,1,0)

Is it because the eye-at = (0,2,0) and therefore the cross product of up x (eye-at) = (0,0,0) and that means, that no real transformation matrix can be constructed?

I found a post where someone asked a similiar question ( https://gamedev.stackexchange.com/a/45328/50476 ), but the explanation is somehow strange for me, because he says that he wants to calculate the cross product of the eye vector and the up vector. But there is no need for that, if you want to be able to calculate the transformation matrix?


texts: Ensuring linear velocity remains constant even when turning

texts:
I am using Ackermann steering to rotate a vehicle. The code is as follows:

    if (turningLeft || turningRight) {
        // Rotate around a dummy pivot point
        float turnDir = turningLeft ? -1 : 1;
        Vector3 turningPivotPoint =
            dummyPivot.transform.TransformPoint(
                new Vector3(turningCenterDistance * turnDir, 0, 0));
        dummyPivot.transform.RotateAround(
                    turningPivotPoint,
                    Vector3.up * gasDir * turnDir,
                    angleVel * Time.deltaTime);
    }

    // The player is pressing the gas
    if (isGas) {
        angleVel = Mathf.Lerp (angleVel, maxAngleVel,Time.deltaTime);
    }

    if (angleVel == 0) {
        turningLeft = turningRight = false;
    }

    gasVel = Mathf.Lerp(gasVel, angleVel * Mathf.Deg2Rad * turningCenterDistance, Time.deltaTime);

    dummyPivot.transform.position =
        dummyPivot.transform.position + dummyPivot.transform.forward * Time.deltaTime * gasVel * gasDir;

The issue is that the speed of the vehicle when it is turning does not match its speed when driving straight. Driving the vehicle in circles will be slower than driving the vehicle forward.

How do I fix this?


texts: Randomly generating the hallways between a network of rooms

texts:
So here's my base map:

(It won't necessarily be 5x5, just using this as an example.)

It's kinda boring the way it is with all the rooms connected. I want it to be more of a randomly generated labyrinth, where every room is accessible like so:

I've tried setting the hallways randomly:

foreach(Room r)
{
    r.northWall = randomBoolean();
    r.southWall = randomBoolean();
    r.eastWall = randomBoolean();
    r.westWall = randomBoolean();
}

But that almost always ends up with rooms that you're unable to go to, like this:

And often some rooms have no hallways at all. I tried saying each room must have a minimum of 2 hallways, but it still doesn't fix the problem that sometimes there an inaccessible areas.

How should I go about doing this? I'm not too worried about the speed, as long as it's not ridiculously slow (Some levels will have 100+ rooms).


texts: Is chess-like AI really inapplicable in turn-based strategy games?

texts:
Obviously, trying to apply the min-max algorithm on the complete tree of moves works only for small games (I apologize to all chess enthusiasts, by "small" I do not mean "simplistic").
For typical turn-based strategy games where the board is often wider than 100 tiles and all pieces in a side can move simultaneously, the min-max algorithm is inapplicable.

I was wondering if a partial min-max algorithm which limits itself to N board configurations at each depth couldn't be good enough? Using a genetic algorithm, it might be possible to find a number of board configurations that are good wrt to the evaluation function. Hopefully, these configurations might also be good wrt to long-term goals.

I would be surprised if this hasn't been thought of before and tried. Has it? How does it work?


texts: How to give a value to all elements of an array?

texts:
This problem is encountered in Game-maker studio:

I created an array using the following iteration:

V_X=0 //these are coordinates of my "pointer"
V_Y=0

repeat(100)
{
    A_CA[V_X,V_Y]=choose(-1,0,1) //now I declare the value of the pointed element in the array

    if V_X<10 //here I move the "pointer"
    {
        V_X+=1
    }
    if V_X=10
    {
        V_Y+=1
        V_X=0
    }
}

My goal is, at some point in the game, I would like to give the same value (0) to every element of the array, preferably without using the "repeat" command above, because I think that may hamper performance.


texts: Character automatic movement and rotation

texts:
I have problems with a character. I want to move myself at some speed, and by typing on WASD keys to rotate this object and move to the side where the face is. The object moves continuously without pressing the key.
Let's say something to the snake game.This is my code, it goes, but I can not do this rotation.

private float speed = 0.01f;
private float moveSpeed = 12f;
Vector2 vector = Vector2.up;
Vector2 moveVector;
[HideInInspector] public bool IsMoving = false;
[HideInInspector] public bool canPress = true;
 private void Start()
{
    InvokeRepeating("Movement", 0.5f, speed);
}
   void Update()
{
    if (canPress)
    {
        if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
        {
            canPress = false;
            IsMoving = true;
            vector = Vector2.right;
            //transform.Rotate(0f, 0f, -90f);
            transform.rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y + rotateObj, transform.rotation.z);
          }
          else if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
          {
                canPress = false;
                IsMoving = true;
                vector = Vector2.up;
          }
          else if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
          {
                canPress = false;
                IsMoving = true;
                vector = -Vector2.up;
               //transform.Rotate(0f, 0f, -90f);
          }
          else if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
          {
                canPress = false;
                IsMoving = true;
                vector = -Vector2.right;
                //transform.Rotate(0f, 0f, +90f);
          }
      }
      moveVector = vector / moveSpeed;
    }
    void Movement()
    {
        if (IsMoving)
           transform.Translate(moveVector);
    }

If anyone knows how to do this I would be grateful. !!!


texts: I've been trying to figure out the correct method for changing the resolution/fullscreen state of a GLFW window for a while now, but after searching all I found were references of how to do it with older versions of the library such as this. I suspect you'd just destroy the window object and re-create it, but was not sure because of how some functions such as glfwSetKeyCallback take a GLFWwindow* as a parameter, and I don't know if that'd continue to work after it has been re-created. The documentation also does not have any examples on doing such a thing, so any help would be appreciated.


texts:
I am trying to generate vertex normals for a given triangles/vertices list with the following code:

**BASE METHOD:**

private void CalculateNormals()
{
    for (Int32 i = 0; i < m_Meshes.Count; ++i)
    {
        Mesh mesh = m_Meshes[i];

        List<Point3D> vertices = mesh.GetVertices();
        List<Triangle> triangles = mesh.GetTriangles();

        List<Point3D> normals = new List<Point3D>(vertices.Count);

        for (Int32 y = 0; y < vertices.Count; ++y)
            normals.Add(new Point3D(0.0f, 0.0f, 0.0f));

        for (Int32 y = 0; y < triangles.Count; ++y)
        {
            Triangle triangle = triangles[y];
            UInt16 index1 = triangle.Index1;
            UInt16 index2 = triangle.Index2;
            UInt16 index3 = triangle.Index3;

            Point3D vertex1 = vertices[index1];
            Point3D vertex2 = vertices[index2];
            Point3D vertex3 = vertices[index3];

            Point3D a = vertex2 - vertex1;
            Point3D b = vertex3 - vertex1;
            Point3D normal = a % b;

            normals[index1] += normal;
            normals[index2] += normal;
            normals[index3] += normal;
        }

        for (Int32 y = 0; y < normals.Count; ++y)
            normals[y] = normals[y].Normalize();

        mesh.AddNormals(normals);
    }
}

**POINT3D METHODS & OPERATORS:**

public static Point3D operator +(Point3D left, Point3D right)
{
    Single x = left.X + right.X;
    Single y = left.Y + right.Y;
    Single z = left.Z + right.Z;

    return (new Point3D(x, y, z));
}

public static Point3D operator -(Point3D left, Point3D right)
{
    Single x = left.X - right.X;
    Single y = left.Y - right.Y;
    Single z = left.Z - right.Z;

    return (new Point3D(x, y, z));
}

public static Point3D operator /(Point3D point, Single value)
{
    Single x = point.X / value;
    Single y = point.Y / value;
    Single z = point.Z / value;

    return (new Point3D(x, y, z));
}

// Crossed Product
public static Point3D operator %(Point3D left, Point3D right)
{
    Single x = (left.Y * right.Z) - (left.Z * right.Y);
    Single y = (left.Z * right.X) - (left.X * right.Z);
    Single z = (left.X * right.Y) - (left.Y * right.X);

    return (new Point3D(x, y, z));
}

public Point3D Normalize()
{
    Single magnitude = (Single)Math.Sqrt((m_X * m_X) + (m_Y * m_Y) + (m_Z * m_Z));

    if (magnitude == 0.0f)
        return (new Point3D(0.0f, 0.0f, 0.0f));

    return (this / magnitude);
}

This is what I get:

What am I doing wrong? Can someone help me please?

EDIT:

I tried to do this process with a single mesh containing a single triangle to have a better control over what's going on in my algorithm. Here are the triangle vertices values:

Here are the values I get:

And here are the correct values automatically calculated by a plugin tool:


texts: LibGDX: How do I manage Player position?

texts:
I'm making a 2D isometric tiled game using LibGDX. In my Player class, I created a vector2 that I named 'pos' to manage the player position, then I draw my Player with:

    batch.begin();
    batch.draw(localPlayer.texture,LocalPlayer.pos.x,LocalPlayer.pos.y);
    batch.end();

Let's say pos = (0,0), then the Player will be rendered at the bottom left corner of my screen.

When I translate the camera, the (0,0) still correspond with the bottom left of my screen, so the pos Vector2 is about my screen, not my map...

What should I do to get a Coordinate System based on the map and not on my screen? I would not prefer using the Sprite Class...

Thank you :)


texts:
I am trying to make a simple 2D game engine using Monogame and the Krypton 2.0 lighting engine. So far I have succeeded in rendering a light but I am unable to generate any shadows from any hull's. Does anyone know if this can be done using Krypton with Monogame? If this cannot be done does anyone know of any other lighting engines that work with Monogame. I just need to draw one light from the center of the view port.

As a side note I was able to get proof that the hull is in the correct position because I can see a grey outline of the hull at the correct position. My creation code for the light and the hull is the following:

        var texture = LightTextureBuilder.CreatePointLight(this.GraphicsDevice, 512);

        Light2D light = new Light2D()
        {
            Texture = texture,
            Range = 700,
            Color = Color.White,
            Intensity = 0.5f,
            Angle = MathHelper.TwoPi * 1f,
            X = 0,
            Y = 0,
        };

        var hull = ShadowHull.CreateRectangle(new Vector2(1,1));
        hull.Scale = new Vector2(50, 50);
        hull.Position = new Vector2(75,0);

        _krypton.Lights.Add(light);
        _krypton.Hulls.Add(hull);

As for drawing krypton I use the following code:

            _krypton.Matrix = ActiveRoom.Camera.GetTransformation();
            _krypton.SpriteBatchCompatablityEnabled = true;
            _krypton.CullMode = CullMode.None;
            _krypton.Bluriness = 1;
            _krypton.LightMapPrepare();

            _spriteBatch.Begin(/*camera transform and blending. Nothing special*/);
           //draw code is here
            _spriteBatch.End();

            _krypton.Draw(gameTime);

The only changes that I made to krypton itself was to replace the XNA references with Monogame and I had to comment out all of the ColorWriteEnable lines from the KryptonEffect.fx file so that the Monogame content pipeline would compile the shader. Is there something that I have missed or will I have to find a new lighting engine?

Thanks for your help in advance. Any advice is much appreciated.


texts: While in the rendering loop, is it OK to call glUseProgram? Does it have a big overhead? I'm planing to use a program for each different material in the scene. I'm a real beginner with OpenGL and I'm afraid that changing the program several times for each frame it's not the best practice (although I can't think of something else).


texts: Unity3D Get collision without having Rigidbody

texts:
I am trying to detect a collision between 2 objects, each one of them has a Collider component.
In the script I have the method OnCollisionEnter(Collision other) where I want to check if the collided object is the same as a pre-defined variable, but when they collide, nothing gets called.

If I try to attach a Rigidbody to one of the objects, it works, but that makes the Rigidbody object behaves weird, like going up and down, and changing its rotation.

Is there a way to check for collision without having a Rigidbody attached? Or if not, how can I make the object with Rigidbody not moving weirdly, and rotating?


texts:
Okay, I've been programming in Java for about ten years, but am entirely new to LWJGL. I have a specific problem whilst attempting to create a text console. I have built a class meant to abstract input polling to it, which (in theory) captures key presses from the Keyboard object and appends them to a StringBuilder/StringBuffer, then retrieves the completed string after receiving the ENTER key.

The problem is, after I trigger the String return (currently with ESCAPE), and attempt to print it to System.out, I consistently get a blank line. I can get an appropriate string length, and I can even sample a single character out of it and get complete accuracy, but it never prints the actual string.

I could swear that LWJGL slipped some kind of thread-safety trick in while I wasn't looking.

==UPDATE==

I've now determined that a null value was appended at the beginning of my StringBuffer. The problem can (sloppily) be solved with a command.delete(0, 1) line, freeing the actual String data. However, I don't know how that null got in there to begin with. If anyone sees it before I do, please let me know.

Here's my code:

static volatile StringBuffer command = new StringBuffer();

@Override
public void chain(InputPoller poller) {
    this.chain = poller;
}

@Override
public synchronized void poll() {
    //basic testing for modifier keys, to be used later on
    boolean shift = false, alt = false, control = false, superkey = false;

    if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT))
        shift = true;
    if(Keyboard.isKeyDown(Keyboard.KEY_LMENU) || Keyboard.isKeyDown(Keyboard.KEY_RMENU))
        alt = true;
    if(Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || Keyboard.isKeyDown(Keyboard.KEY_RCONTROL))
        control = true;
    if(Keyboard.isKeyDown(Keyboard.KEY_LMETA) || Keyboard.isKeyDown(Keyboard.KEY_RMETA))
        superkey = true;

    while(Keyboard.next())
        if(Keyboard.getEventKeyState()) {
            command.append(Keyboard.getEventCharacter());
        }

        if (Framework.isConsoleEnabled() && Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
            System.out.println("Escape down");
            System.out.println(command.length() + " characters polled"); //works
            System.out.println(command.toString().length()); //works
            System.out.println(command.toString().charAt(4)); //works
            System.out.println(command.toString().toCharArray()); //blank line!
            System.out.println(command.toString()); //blank line!

            Framework.disableConsole();
        }

        //TODO: Add command construction and console management after that
    }
}

Maybe the answer's obvious and I'm just feeling tired, but I need to walk away from this for a while. If anyone sees the issue, please let me know. This machine is running the latest release of Java 7 on Ubuntu 12.04, Mate desktop environment.

Many thanks.


texts: Unity3D smooth movement with joypad button press

texts:
First off, I'm sorry this is such a silly question, but for the life of me I can't seem to get it to work. And I've just spent the last hour trying to do so.

All I want to do is have my camera move up, in a smooth fashion, when I press the shoulder button on my joypad. I have it so that when I press the button, it jumps up. Not in a smooth movement.

The code I have is as follows:

    float _maxY = 0.0f;
    if (Input.GetKeyDown(KeyCode.Joystick1Button5))
   {
      _maxY++;
      transform.Translate(0, _maxY, 0);
   }

This is found within my update function. I've been looking for the answer to this for hours now, but can't find anything. Can anyone please help me?


texts:
From what I understand, SpriteBatch's purpose is to batch as many draw operations to send to the GPU. Each batch can handle one texture at a time, and changing SpriteBatch context/texture is expensive, so when you need to draw many different textures in one frame you use a texture atlas, putting sprites that are most likely to be drawn by the same component in the same page.

So my questions are:

Assuming there are numerous components using the same texture page, how am I supposed to group them together and issue their drawing method?
What is an efficient way to deal with a component that uses sprites from two different texture pages? Should I handle two different drawing methods for each texture page? or perhaps take the context texture page as parameter and draw only what's relevant for it?
What about dynamically generated textures?
What if you don't know which texture pages a component needs? (For example, a custom visual equipment where you can't possible put all the equips in the same texture page since there might be thousands of em, and it's determined only at runtime)

I've seen many articles on how SpriteBatches work technically but nothing meaningfull on how to actually make the best use out of them. Would a good solution be to somehow queue my draw operations sorted by texture? If so, what would be a good generic way to implement it?


texts:
I'm trying to animate multiple(3) entities using one model(IQM format).

It's working but performance is really bad because I'm calling animate function for each entity in my game loop (I think problem is there).

What's the best way to animate multiple entities (with different animation ofc) in OpenGL? I think I can try build one VBO / entity for better performances but I don't think it's the best way to do it.


texts: Apply bone tranforms when importing FBX in XNA

texts:
Preconditions: I have some models, that does only contain some meshes and one texture. There is no animation within the model. An example: a model of a table.

I want to draw the Model with a custom effect, so I have to swap the effect after loading the model. In order to draw them correctly, I have to apply the bone transformation manually on each draw for each mesh and effect as can be seen here. So there are two questions:

Is there a option during import that allows my to apply the bone transformation on all vertices, so that during draw call I should not have to do this?
Is there a option during import that merges all vertices into a Vertex- and IndexBuffer, that allows me to draw the whole model with just one call?

I'm pretty sure that the build-in "Autodesk FBX - XNA Framework" does not support this features, but maybe there is an other imported available or an other possibility I missed.

The aim is to speed up rendering a little bit especially by using instancing. So having one VertexBuffer to draw at one time would be pretty nice.


texts: What's the newest trend / method for terrain rendering?

texts: The last time I checked in on terrain rendering, ROAM was the new hotness.  Yes, that was a long time ago.  I liked ROAM a lot, though, because it was extremely simple to program, and gave pretty decent results.  I imagine that the technology has improved quite a bit now.  What are the most popular methods for terrain rendering these days?


texts: How can I stop my Jitter physics meshes being offset?

texts:
I'm developing a C# game engine and have hit a snag trying to add physics. I'm using XNA for graphics and Jitter for physics. I am trying to split the XNA model into it's meshes, then create a ConvexHull for each mesh. I then attempt to combine those into a CompoundObject, this however isn't working and depending upon the model the meshes are offset by different amounts.

This is the code I'm currently using and it gives me:

Any ideas?


texts: does order of updates and renders matter?

texts:
I know in a game loop there needs to be an order like physics should update before rendering. So, I have created two separate functions: update and render and the game loops like below:

while(running) {
    clock.reset();
    for(auto system : systems) {
        system->checkForInput();
        system->update(clock.getElapsedTime());
    }

    for(auto system : systems)
        system->render();
}

Some systems have empty render function or empty update functions.

My question is, does the order of updates or renders matter? would it matter if gui is rendered before graphics, or input is updated after physics?


texts: As i have only unity build in exe format how can i put it to the startup of my window so that it run automatically when computer becomes start. Remember I don't want to put it manually is there any scripting ref available to do this or else auto solution?


texts: Combining rotation,scaling around a pivot with translation into a matrix

texts:
In short: I need to combine rotation (in the form of a quaternion), scaling around a pivot point along with translation into a transformation matrix.

The long:
I am trying to implement a proprietary model format. This format includes animations. Part of that animation involves generating a matrix which combines rotation (in the form of a quaternion) and scaling around a pivot point, with translation into a transformation matrix. I am using OpenGL and the OpenGL math library (GLM)

Someone else has already implemented parts of the proprietary model format using DirectX. The part in question was implemented in directX like this:

D3DXMatrixTransformation(&BaseMatrix, &ModelBaseData->PivotPoint, NULL, &ScalingVector, &ModelBaseData->PivotPoint, reinterpret_cast<D3DXQUATERNION*>(&RotationVector), &TranslationVector);

I found the WINE implementation of this function and attempted to duplicate it like this:

mat4 m1, m2, m3, m4, m5, m6, m7, p1, p2, p3, p4, p5;

m5 = glm::translate(0,0,0);
m7 = glm::translate(pivot+translationVector);
m1 = glm::translate(-pivot);
m3 = glm::scale(scalingVector);
m6 = glm::mat4_cast(rotationQuaternion); //Convert quaternion to a matrix

//m2 & m4 are identity
p1 = m1;// * m2
p2 = p1 * m3; //Apply scaling first
p3 = p2;// * m4;
p4 = p3 * m5;
p5 = p4;
p5 = p4 * m6;
mat4 result = p5 * m7;

(I realize glm::translate(0,0,0) is the identity matrix)
Unfortunately neither the scaling nor the rotation seems to work correctly like this. So I took another approach based off of this ordering of translation, rotation and scaling.

mat4 result = glm::scale(scalingVector) * glm::translate(pivot) * glm::mat4_cast(rotationQuaternion) * glm::translate(translationVector);

However the scaling does not appear to be around the pivot point and I'm not entirely sure about the rotation. Does anyone have any tips on how to accomplish this?


texts: Need some advice on how to decide where to implement my enemy behaviours

texts:
I'm in the middle of writing a platformer game in Unity using C#. I have my character, if he presses the kick button his state switches to kicking. During this "kicking" state the character doesn't actually do anything, he only publicly exposes the kicking information such as kickForce etc.

The enemies however have a check in their update functions for the players isKicking value, if he is and the enemy lies within the range for being kicked by the player then the enemy has forces applied to itself and such. All this works fine but I've been thinking about future implementation of different enemy types, if I want to implement other types of enemies that do not behave the same this same script will not work.

To me this is inintutive, part of me thinks that the kicking behavior should be in the player class, he should retrieve all enemies within the area of kicking and run them through some sort of KickObject method. However this is my very issue, I am unsure of what the cleanest and most straightforward (and easily extendable) way of doing this is. I have this problem in general when it comes to implementing the structure of the game, i don't know the best answer and I feel that often when I am planning things they get much more complicated than I had originally planned for down the line and the structure i had in place starts to fall apart.

Any advice on this matter would be greatly appreciated.

TL:DR - For kicking enemies, should the behaviour be applied by the player or is the method of every enemy having its own "be kicked" code the better way to do this. General game development code structure questions.


texts: Making pickup objects with gravity that won't push the player on collision

texts:
I am trying to create pickups, that appear after an enemy dies, and that the player can pick up, but I am running into some issues.
First of all, I want the pickups to be affected by gravity, so I need a rigidbody2d and a boxcollider2d (non-trigger), so this works.

Now, if I want to collect the pickups on contact, I need to make the layers for the loot and the player get in contact, so that they can interact.

Now, of course, I do not want to push the pickups around. I want to actually pick them up when I touch them, but the collider is not a trigger so I thought I would use OnCollisionEnter to handle this.
        void OnCollisionEnter2D(Collision2D other)
        {
            var loot = other.gameObject.GetComponent<ILoot>();

            loot?.PickUp(gameObject); // Destroys also the pickup
        }

While this works, I am still using a non-trigger collider, which means that there are some physics effects that are not desired. For instance, when I "jump" onto the pickups.

Notice the subtle, but still present, slowdown in the fall, when the player enters in touch with the pickups?
How could I solve this issue??


texts: How do I write to a 16-bit depth buffer using Monogame and HLSL?

texts:
I'm working on shadow mapping. Part of the implementation involves drawing 3D models to a depth buffer with recommended 16-bit depth. To that end, I'm first creating a render target as follows:

new RenderTarget2D(graphicsDevice, width, height, false, SurfaceFormat.HalfSingle, DepthFormat.Depth16)

My HLSL shader is shown below.

#define VShaderModel vs_4_0_level_9_1
#define PShaderModel ps_4_0_level_9_1

matrix World;
matrix LightProjection;

struct MapVOutput
{
    float4 Position : SV_Position;
    float Depth : Depth;
};

MapVOutput MapVShader(in float4 position : SV_Position)
{
    MapVOutput output;
    output.Position = mul(position, mul(World, LightProjection));
    output.Depth = output.Position;

    return output;
}

float MapPShader(MapVOutput input) : Depth
{
    return input.Depth;
}

technique CreateShadowMap
{
    pass Pass0
    {
        VertexShader = compile VShaderModel MapVShader();
        PixelShader = compile PShaderModel MapPShader();
    }
};

The idea is to render the scene from the light's perspective (using the LightProjection matrix) and store depth information only. However, trying to compile this shader gives the following error:

pixel shader must minimally write all four components of SV_Target0

Note that the shader currently uses vs_4_0_level_9_1 and ps_4_0_level_9_1 to compile. I've tried changing those to simply vs_4_0 and ps_4_0, which lets the shader compile, but causes an error to be thrown during runtime (with a cryptic error message).

Given all this, I have several questions I'm hoping to understand.

To generate a shadow map, I only need to store 16-bit depth information. Is SurfaceFormat.HalfSingle the correct format to use for this purpose?
I only need to store 16 bits, but the pixel shader function writes a float (32 bits). How can I write only 16 bits to the render target? If I write a float, is the value properly truncated anyway?
I've looked at existing shadow map samples and noticed that the Depth value in MapVOutput uses the TEXCOORD0 semantic rather than `DEPTH'. Is DEPTH the correct semantic to use on this variable?
How do I resolve the HLSL error listed above without simply returning a color? Google hasn't given me useful answers so far, and switching compiler versions seems to introduce other problems.

Thank you.


texts:
I'm trying to capture some screenshots for my game. They need to be saved as jpgs to a folder, latency is not an issue, I don't care if it happens over 10 seconds. My number one priority is to keep the game at a steady framerate.

Some things I've tried:

I've tried ScreenCapture.CaptureScreenshot but that is super slow and the game hangs for a split second.
I've tried the old method of texture2d.ReadPixels() and EncodeToJPG() but that was unbelievably slow.
I also found a relatively new feature: https://docs.unity3d.com/2018.3/Documentation/ScriptReference/Rendering.AsyncGPUReadback.html

I found a repo using this feature to capture screenshots asynchronously: https://github.com/keijiro/AsyncCaptureTest
This requires the use of OnRenderImage(), but I'm using LWRP and OnRenderImage() isn't supported in scriptable render pipeline.

Pulling my hair out

Some metrics from my testing:

ScreenCapture.CaptureScreenshot is ~200ms.
ReadPixels() is 40-70ms.
Texture.Apply() is ~5ms.
EncodeToJPG() is 35-50ms.
File.WriteAllBytes() is <1ms.

Also posted this question here and here:


texts:
I'm beginning to make a tile-based 4x game, but I ran into a conceptual issue: My inspiration for this game are the Civilization games, particularly Civ 2, and I noticed something I was interested in mimicking, but I was wondering how it was done.

This is that while the map is isometric, it is not square. I was wondering how it does this. My first thought would be to use an array, but then you have the corners being basically unused space.

To give an example of what I'm talking about:

One idea I have is that there are really two arrays, and whenever a diagonal is made (which would be up, down, left, and right to the player), it moves on one array, and any non-diagonal movement (which to the player is diagonal) moves to the other array.

This is illustrated by this picture (the mountains are one array and the hills are another array):


texts: Flash animation or Sprite sheet animation good for Unity mobile games

texts:
I would like to develop dress-up and cooking kind of games. So it needs lots of animations. Our designers done the animations in the lash. I found the plugins callued GAF and UniSWF to convert flash animation to Unity or We can convert animations into sprite-sheets and animate them in Unity, But i don't know which one is the best way to do animations for mobiles with better performance and lower game size.

Any kind of suggestion is good. Thank you!


texts: Why are multiple Nav Mesh Agents jittery when the target is inaccessible?

texts:
I have a simple scene. Most of the land is flat, except for three raised cylindrical platforms coming up from the ground. I have several enemies with Nav Mesh Agent components attached, with their target being the player. I used the Standard Assets' ThirdPersonCharacter script, and then called character.Move(agent.desiredVelocity, false, false); within the Update() of a character control script.

The agents work great when the player runs around on the ground. When the player hops on the platform (about 2 units above the ground), an agent will walk toward the edge of the platform and then stop, just as expected. However, if I throw in a second agent, both agents work fine only until the player stands on the platform. Then they start to jitter, like they cannot make up their minds on whether to turn left or right when they should really just walk straight. If I add even more agents, the jittering gets worse. With enough, they don't even move forward and simply turn left and right rapidly.

Clearly, there is a problem with interference, and I understand the agents are designed to avoid obstacles as well as each other, but here is what I found and tried so far:

I switched the obstacle avoidance quality to None. The jitter still happens just as much.
Some other posts suggested setting IsKinematic to true for moving obstacles. I cannot do this because the character script depends on the rigidbody not being kinematic.
I adjusted the height of the platform and re-baked the navmesh. It had no effect. It must be the fact that the platform is not actually accessible, so that the agents can only make a partial path.
I messed with the pathfinding settings on the agent, such as turning auto repath off, since it has to do with partial paths. There were no noticeable changes.

Does anyone know what might be causing the jitters and how I could fix this?

Update

As requested, here is how my Nav Mesh agent is configured:


texts: How can I seamlessly animate textures across tiles like in Civilization 6?

texts:
I am trying to make a much simpler version of the graphic effects we see in the game Civilization 6. This question applies to the graphics on land and ocean tiles. But I first noticed this effect on the ocean tiles.

So you will see the waves effect (fairly near centre of the image), if you ever played the game you'll know that these waves roll into the coast and are there to let you know its an ocean tile and not a lake.

But these waves span several hex tiles, appearingly seamless. But the map is procedurally generated and so land tiles and ocean can appear in any random formations.

How does it know which animated texture to play for each tile?

I already have made the hex tile map.
I have NOT yet learnt how to add my own custom material/shader to make the texture animate, but I believe I can learn this on my own

But I really am at a loss of how the tile 'knows' what its neighbours are doing and is able to join the texture so nicely). Is there a name for this process of which i can do further research? Any tips on where to start making this effect. (I only want it to look very basic to start with , I'm not expecting to be able to recreate Civ6 any time soon :P

Many thanks!


texts: How do engines avoid "Phase Lock" (multiple objects in same location) in a Physics Engine?

texts:
Let me explain Phase Lock first: When two objects of non zero mass occupy the same space but have zero energy (no velocity).

Do they bump forever with zero velocity resolution vectors or do they just stay locked together until an outside force interacts?

In my home brewed engine, I realized that if I loaded a character into a tree and moved them, they would signal a collision and hop back to their original spot. I suppose I could fix this by implementing impulses in the event of a collision instead of just jumping back to the last spot I was in (my implementation kind of sucks).

But while I make my engine more robust, I'm just curious on how most other physics engines handle this case. Do objects that start in the same spot with no movement speed just shoot out from each other in a random direction? Or do they sit there until something happens? Which option is generally the best approach?


texts: Flow effect to static water on a isometric city

texts:
Hello everyone I want to give the idea that the river in my city is flowing but I am having an hard time to figure how.

Do you have any idea of what I should look into to?


texts: Individual Skeletal Animation with OpenGL

texts:
I have been able to implement a pipeline in OpenGL which reads Collada files and can animate them through interpolating the keyframes. However, as somebody brand new to graphics, I don't quite know how one would go about doing individual joint animation.

For example, if I have a sprite and I would like to move just their arm joint, none of that animation information is stored in a Collada file. How would I go about making a system that can move each joint independently?


texts: How to only render part of an image in lwjgl/openGL

texts:
I'm making a mining/building game in java using slick2D and I want to make it so you can only see a few blocks in any direction while you are underground. The best example I could find of what I want to do is the game miner dig deep.

One way I thought of doing it would be to have a large image and just draw transparent areas on it where you need to be able too see but even if that would be an efficient method I wouldn't be sure how to do that.


texts: (UE4) Simulate physics breaks timeline animation

texts:
I'm using timelines to animate my boat object, which does not have any limbs.  So all I need to accomplish is rotation and a little movement.

However, when the player dies, I need the boat to sink using simulate physics.
When I turn simulate physics on, the timelines stop animating the boat.

The nodes I'm using are GetActorTransform and SetActorRotation


texts:
I am currently in school studying game design and programming and I am wondering, simply: How are games updated?

Whenever I create simple, little programs, if I change anything, essentially the entire program is recreated. Obviously, game with sizes of 5, 10, even 20 Gb are much too large to recreate the whole thing if there are only a few small changes, so what is the process of updating the game's code?

Specifically PC if anything, but knowledge on other systems would be nice too, if they are different.


texts: Why is my OpenGL 4.1 shader not working on OS X Macbook ( works on Linux )?

texts:
I've recently rebuild shaders for my program and it stopped "working" ( black screen ) on OS X ( El Capitan ), but it's ok on Linux. What could be the cause?

There are no shader compilation errors, and here is my shader code:

https://github.com/Marqin/YuriaViewer/blob/master/vertex.glsl

Keep in mind that this software worked on El Capitan with OpenGL 4.1 before shader rewrite. Here are my glfw hints:

glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

My program also is checking for GL_ARB_gpu_shader_fp64 and it's available on my Macbook ( Macbook Air 2013 mid ).

EDIT1:

I've "debugged" it a little and it looks that i is always lesser than vis on OS X, that's why it's black.

EDIT2:

I made a simple test - I've typed all uniform values in shader by hand and now it wasn't black, but I've got some gibberish on screen. Then I've changed every dvec3 and dvec2 to float versions and it showed nice fractal. So it looks like double is not working on OS X. But how can it be? It's saying that GL_ARB_gpu_shader_fp64 is available and it even doesn't complain when I request it in vertex shader.

EDIT3:

It works on iMac with R9 M395. So it's problem with Intel hardware ( or problem with OS X Intel driver ).


texts: I've just finished making the core aspects of my HTML5 game. I have a server and all that, but is there a site where I can find people that would test my game? I figured that getting my friends to do it wouldn't be a good option because they are probably biased, so I need people that I never met before, complete strangers. Also, would the people at gamedev forums be willing to do that? Would it be considered as advertising?


texts: How to find the points of intersection of two OBBs

texts:
In my game I need to be able to find the points of intersection between two OBBs.

I'm using Separate Axis Theorem to check if there's an intersection and get the penetration vector if there is one.

Can I use SAT to also solve this problem? If not, how can I solve this?


texts: What are the advantages of having component logic in a "system" versus the component itself?

texts:
For the past few days I've been trying to make my first game. I did some research on usual development practices and patterns and I settled on a composition system where the different components communicate using messages that the container-GameObject distributes.

For instance say that I press the attack key. The playerInput component sends an AttackMessage to all the other components using the notify function of the GameObject. The Weapon component picks the message, sets some local variables and sends  a RigidBodyStateMessage to the RigidBody component which in turn sends another message containing the rotation and position of the GameObject. The Weapon component catches the message and instantiates a bullet using the information passed in the message.

Communication between different objects is achieved using messages sent in message buses on which the GameObjects have registered. For example, the PhysicsComponent continuously sends messages to the collisionBus which are then delivered to the registered GameObjects.

This approach allows for complete decoupling between the components but I am not sure if it may create any long-term problems. Some people also told me that components shouldn't have any logic in them and that they should only keep data which will be processed in systems. I was wondering what advantages the latter method would bring compared to the one that I am currently using. Sorry for the wall of text, I am writing from my phone.

Any help is much appreciated!


texts: How do I procedurally animate a cell eating another cell?

texts:
The entities in my game are soft-body, amorphous cells. I'd like to create an animation where enemies are engulfed by the player's cell.  That is, I want to generate a "cell eating another cell"-effect. See this video for the type of motion I want: https://www.youtube.com/watch?v=iO_vOFFf1uQ

I'm considering using fluid dynamics to achieve this, but I'm lost as to where to start. I'm working in Unity2D, and Fluvio doesn't seem to provide what I need.  Does anyone have advice on the best way for me to proceed?


texts:
I'm developing a game that will require renting a server. The server will be used to host scores, clans, friends(on/off), match making, lobby, and chat. The game/match will be hosted by each player (to lower the cost). How much would a server like this cost? Any hosting recommendation? How much would it cost if the server hosts the games/matches too?

I want to know a base price (imagine a card game or turn based RPG, even though my game is real time).


texts: How do I drag my widgets without dragging other widgets?

texts:
I have a bunch of drag-able widgets on screen.  When I am dragging one of the widgets around, if I drag the mouse over another widget, that widget then gets "snagged" and is also dragged around.

While this is kind of a neat thing and I can think of a few game ideas based on that alone, that was not intended.  :-P

Background Info

I have a Widget class that is the basis for my user interface controls.  It has a bunch of properties that define it's size, position, image information, etc.  It also defines some events, OnMouseOver, OnMouseOut, OnMouseClick, etc.  All of the event handler functions are virtual, so that child objects can override them and make use of their implementation without duplicating code.

Widgets are not aware of each other.  They cannot tell each other, "Hey, I'm dragging so bugger off!"

Source Code

Here's where the widget gets updated (every frame):

public virtual void Update( MouseComponent mouse, KeyboardComponent keyboard ) {
    // update position if the widget is being dragged
    if ( this.IsDragging ) {
        this.Left -= (int)( mouse.LastPosition.X - mouse.Position.X );
        this.Top -= (int)( mouse.LastPosition.Y - mouse.Position.Y );
    }
    ... // define and throw other events
    if ( !this.WasMouseOver && this.IsMouseOver && mouse.IsButtonDown( MouseButton.Left ) ) {
        this.IsMouseDown = true;
        this.MouseDown( mouse, new EventArgs() );
    }
    ... // define and throw other events
}

And here's the OnMouseDown event where the IsDraggable property gets set:

public virtual void OnMouseDown( object sender, EventArgs args ) {
    if ( this.IsDraggable ) {
        this.IsDragging = true;
    }
}

Problem

Looking at the source code, it's obvious why this is happening.  The OnMouseDown event gets fired whenever the mouse is hovered over the Widget and when the left mouse button is "down" (but not necessarily in that order!).  That means that even if I hold the mouse down somewhere else on screen, and simply move it over anything that IsDraggable, it will "hook" onto the mouse and go for a ride.

So, now that it's obvious that I'm Doing It Wrong™, how do I do this correctly?


texts: Change the image of sdl window with a new one

texts:
I will make a game and it has 3 buttons on its menu. Those buttons supposed to change the picture the background of the menu

When i click on play, another picture should appear like so

I found a solution which is closing the current program and starting another one that has the comming soon picture  but what i would like to do is to only change the picture without the need to close the program and start another one ,
Here is my code for the menu screen:

#include <stdlib.h>
#include <stdio.h>
#include <SDL/SDL.h>

  int continuer=1;
  SDL_Event event;

int main(int argc, char *argv[])
{
    SDL_Surface *ecran = NULL, *imageDeFond = NULL, *sapin = NULL;
    int continuer=1;
    SDL_Event event;
    SDL_Rect positionFond,positionSapin;

    positionSapin.x = 0;
    positionSapin.y = 0;
    positionFond.x = 0;
    positionFond.y = 0;

    SDL_Init(SDL_INIT_VIDEO);

    ecran = SDL_SetVideoMode(800, 600, 32, SDL_HWSURFACE);
    SDL_WM_SetCaption("Chargement d'images en SDL", NULL);

    /* Chargement d'une image Bitmap dans une surface */
    imageDeFond = SDL_LoadBMP("menu.bmp");
    /* On blitte par-dessus l'écran */
    SDL_BlitSurface(imageDeFond, NULL, ecran, &positionFond);

    SDL_Flip(ecran);
    SDL_FreeSurface(imageDeFond);

    while(continuer)
 { SDL_WaitEvent(&event);
   switch(event.type)
   {
       case SDL_QUIT:
        continuer=0;
       break ;
       case SDL_KEYDOWN:

     switch (event.key.keysym.sym)

      {

          case SDLK_ESCAPE:

              continuer=0;

          break;

       }

      break;
    case SDL_MOUSEBUTTONUP:
       if (event.button.button == SDL_BUTTON_LEFT)
        {
            positionFond.x = event.button.x;

            positionFond.y = event.button.y;
             if (event.button.x> 150 && event.button.x < 320 && event.button.y > 340 && event.button.y < 415 )
              {
               continuer = 0;
              }
              else if (event.button.x> 150 && event.button.x < 320 && event.button.y > 105 && event.button.y < 180 )
                  {
                     continuer=0;
                      SDL_Quit();
                    int status = system("./cs");

                    }

        }

     break ;

  }
   }

    SDL_Quit();

    return EXIT_SUCCESS;
}

Here is my second code when i click on the play button:

#include <stdlib.h>
#include <stdio.h>
#include <SDL/SDL.h>

  int continuer=1;
  SDL_Event event;

int main(int argc, char *argv[])
{
    SDL_Surface *ecran = NULL, *imageDeFond = NULL, *sapin = NULL;
    int continuer=1;
    SDL_Event event;
    SDL_Rect positionFond,positionSapin;

    positionSapin.x = 0;
    positionSapin.y = 0;
    positionFond.x = 0;
    positionFond.y = 0;

    SDL_Init(SDL_INIT_VIDEO);

    ecran = SDL_SetVideoMode(800, 600, 32, SDL_HWSURFACE);
    SDL_WM_SetCaption("Chargement d'images en SDL", NULL);

    /* Chargement d'une image Bitmap dans une surface */
    imageDeFond = SDL_LoadBMP("menujouer.bmp");
    /* On blitte par-dessus l'écran */
    SDL_BlitSurface(imageDeFond, NULL, ecran, &positionFond);

    SDL_Flip(ecran);
    SDL_FreeSurface(imageDeFond);

    while(continuer)
 { SDL_WaitEvent(&event);
   switch(event.type)
   {
       case SDL_QUIT:
        continuer=0;
       break ;
       case SDL_KEYDOWN:

     switch (event.key.keysym.sym)

      {

          case SDLK_ESCAPE:

              continuer=0;
                SDL_Quit();
           int status = system("./menu");

          break;

       }
 }
   }

    SDL_Quit();

    return EXIT_SUCCESS;
}

Is there any solution to make it in the same program without closing and reopning an other program because when i tried it the problem was the buttons of the first picture(menu image) was still active so when i click on the zone of quit it closes the program even though the menu image is hidden under the second.


texts:
To avoid shadow acne I usualy use front face culling which works great. But for my current implementation the mesh is a quite complex terrain (depending on the lod level) and than the shading (dot product of the normals face with the negative light direction) is not always correct as some normals are actually facing the light. But still there is no information in the shadowmap to shadow these fragments in the shadowmap because of the front face culling ( like it is not exact enough).
What I end up with, is that there are some bright spots in the shadowed area.
I am not really sure why this does not work, because that would mean, that the front face culling is also culling some back faces, if the mesh has a very high level of detail, right?

In the Image with Front Face Culling (top picture) you can see these bright lines in the shadowed area where as without FF Culling (bottom image) the shadowed area is completely black.

My current workaround is, that I check the highest LOD level that is currently displaying and than according to that switch back an forth between ff culling and bias.

I use OpenGL:

The front face culling:

glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);

The shading in the fragment shader:

float shading = max(dot(normal,-lightDir), 0.0);


texts: Load a specific sprite by name from a SpriteSheet with Resources.Load

texts:
I want to avoid loading all the sprites from a sprite sheet into a dictionary. Is there a way to access the specific sprite inside the sheet. Right now I'm using this code :

 prefabImage.sprite = Resources.Load<Sprite>(spritePath+spriteName);

But this loads a single sprite. Can I change spritePath to somehow point inside the sprite sheet?


texts: How to apply game progression changes on screen loading in a Zelda like game

texts:
I'm trying to develop a 2D game like Zelda. The game is divided in screens with exits linking each other. I store each screen data (including objects and NPC positions) on a separate file, and when the main character steps on the exit, the next screen data is parsed and the screen is loaded. Everything works just fine so far.

I'm now trying to implement the game progression system, along with the save system. I've read a lot about some ideas on how to do that, finite state machine design, what to store on save files, serialization and everything, but I'm kind stuck here.

Let's say that action X triggers event Y, moving some NPC from point A to point B. The player then saves and quits the game. When the game is loaded, it must position that NPC on point B.
To achieve that, should I rewrite the files that contains screen data so when the screen is parsed it draws the NPC on its new place? Or should I store its new position on a separate file, and apply the changes on the screen after its loaded? Or maybe there's a better and less ugly way.

Any suggestions are welcome.


texts: Why are the vertices from a mesh not transforming using a camera?

texts:
I am able to use a camera class to change the view and rotation of a simple quad, so I know it works, but when I move on to a more advanced geometry, such as a mesh, I am unable to affect the transform of the object at all.  The WVP matrix does change in the mesh example (using print statements), but no movement or rotation is observed.

My camera first calls

camera.SetLens(0.33f * (float)Math.PI, Width / Height, 0.5f, 1000.0f)

on initialization, where width and height is the width and height of the window, SetLens is defined here:

public void SetLens(float fovY, float aspect, float zn, float zf)
{
  FovY = fovY;
  Aspect = aspect;
  NearZ = zn;
  FarZ = zf;

  NearWindowHeight = 2.0f * NearZ * (float)Math.Tan(0.5f * FovY);
  FarWindowHeight = 2.0f * FarZ * (float)Math.Tan(0.5f * FovY);

  Proj = Matrix.PerspectiveFovLH(FovY, Aspect, NearZ, FarZ);
}

Every frame I call Draw, and it updates the view matrix of the camera. (Draw is on the bottom of this code snippet)

public void UpdateViewMatrix()
{
  var r = Right;
  var u = Up;
  var l = Look;
  var p = Position;

  l = Vector3.Normalize(l);
  u = Vector3.Normalize(Vector3.Cross(l, r));

  r = Vector3.Cross(u, l);

  var x = -Vector3.Dot(p, r);
  var y = -Vector3.Dot(p, u);
  var z = -Vector3.Dot(p, l);

  Right = r;
  Up = u;
  Look = l;

  var v = new Matrix();
  v[0, 0] = Right.X;
  v[1, 0] = Right.Y;
  v[2, 0] = Right.Z;
  v[3, 0] = x;

  v[0, 1] = Up.X;
  v[1, 1] = Up.Y;
  v[2, 1] = Up.Z;
  v[3, 1] = y;

  v[0, 2] = Look.X;
  v[1, 2] = Look.Y;
  v[2, 2] = Look.Z;
  v[3, 2] = z;

  v[0, 3] = v[1, 3] = v[2, 3] = 0;
  v[3, 3] = 1;

  View = v;
}

private void Draw()
{
  camera.UpdateViewMatrix();
  Matrix view = camera.View;
  Matrix proj = camera.Proj;
  Matrix world = Matrix.Identity;
  Matrix WVP = world * view * proj;
  d3dDeviceContext.UpdateSubresource(ref WVP, worldViewProjectionBuffer);
  ...
 }

For the camera to make changes, I call the following functions on keypress/mouse movement

public void Strafe(float d)
{
  Position += Right * d;
}

public void Walk(float d)
{
  Position += Look * d;
}

public void Pitch(float angle)
{
  var r = Matrix.RotationAxis(Right, angle);
  Up = Vector3.TransformNormal(Up, r);
  Look = Vector3.TransformNormal(Look, r);
}

public void Yaw(float angle)
{
  var r = Matrix.RotationY(angle);
  Right = Vector3.TransformNormal(Right, r);
  Up = Vector3.TransformNormal(Up, r);
  Look = Vector3.TransformNormal(Look, r);
}

In my vertex shader I just set the position of the vertex like this:

output.position = mul(worldViewProj, position);

So again, I can get it working with a simple triangle or quad, but I need to load triangles and their connectivity from a TIN and I am able to draw the mesh on the screen but my camera operations are not translating the mesh at all. Any clues on what I might be doing wrong?  For clarification, the whole mesh should be considered one object.


texts: Storing coordinates of every object in server side in MMOs

texts:
In an MMORPG:

Is it typical or feasible to store the coordinates of every tree, bush rock.. etc in the server side for collision detection?

If so, what would be a feasible way to store such a huge number of coordinates (data structures and such, performance issues handling)?

If not, is this type of collision detection done entirely in the client side, with the server not checking at all?

Or is there a middle ground, with the client checking collision and server verifying? If so, how would the server verify the same without keeping the coordinates in the server as well?


texts:
In my cocos2d app I was wondering how to make a CCSprite move on the screen but have the screen focused on the CCSprite, so when the sprite moves the view moves with the CCSprite. Is there a tutorial to do this?

Thanks


texts: How do I map facial motion capture markers to blend shape weights?

texts: For shoestring budget facial motion capture, I can use OpenCV or Blender to track sharpie dots on my face, but how do I then map that to blend shape weights of a game character that has a quite different facial structure? This sounds like an n-dimensional natural neighbor interpolation problem where n is number of dots times two. Is there any publicly available prior work the shoulders of which I can stand on? Or an affordable piece of software that I could use?


texts: How to determine vertex index using Shader Model 3 or lower?

texts:
I need something like SV_VertexId (added in Shader Model 4) in HLSL shader to determine which vertex is currently handled. Unfortunatelly, I can compile only vs_3_0 or lower.

The objective is to change position of one specific vertex using HLSL. I can't edit the mesh and can't pass any data from game engine, my capabilities are limited by HLSL shader.

Shader is writing only for one mesh (humain face), I need to change it's shape a bit (for example, close an eye or make it smiling). I already tried to locate vertex by TEXCOORD, but had no idea how to separate it from other triangles verticles connected to it (placed at the same point where many triangles are met).

if ( VS.TC[0] > 0.8828125 && VS.TC[1] > 0.6328125  && VS.TC[1] < 0.671875 ) {
    // Upper lip center
    VS.Position += VS.Normal * uUpLip;
}

Could you, please, give me any advice how to identify / move only one specific verticle in HLSL? I need something like moving verticle in Blender's Edit Mode (wytn neighbour triangles are still connected in one point), but my attempt with TEXTCOORD makes them moving in different directions

Thanks


texts:
Hi guys I am working on a combo feature and I want to compare two C# lists, something like this
bool found = false;

List<int> combo = new List<int>();
combo.add(1);
combo.add(1);
combo.add(1);

List<int> playerCombo = new List<int>();
playerCombo.add(1);
playerCombo.add(1);
playerCombo.add(1);

if(combo == playerCombo){
  found = true
}

The thing is that == seems that does not work, always throws false, any ideas?
Update: already answered here https://stackoverflow.com/questions/3669970/compare-two-listt-objects-for-equality-ignoring-order


texts: Does playing sound effects have to be filtering enabled?

texts:
In roblox I made a sword that plays the unsheath sound when equipped. This works by using a local script tell a server script to play it when equipped. I made a whole new remote event in replicated storage just for playing this sound effect and nothing else.

Is it really true that simply playing sound effects required filtering enabled?

Is all that extra work of creating the equipted event in replicated storage actually necessary or can I just play it in a non local script in the sword?


texts:
How to make the particle system appear inside the Canvas ? No need for unity store assets.
I'm using Unity 5.5.0


texts: Pros and cons of loading DirectX DLLs directly?

texts:
I have been looking at the source code of various commercial games, and I have noticed that a lot of them load video card/input DLLs directly using LoadLibrary().

I wanted to mod one, but also make my own engine, so I was wondering what would be the benefits of loading DirectX 11 DLLs directly, as opposed to link the program with .libs?


texts: I have a fire particle emitter in my project and I have it following a football. My goal is to make the football look like it is on fire but the problem is when I add it to the screen it can only be in front of the football or behind it. I want to be able to add it to the screen and make it transparent so that the football will still show through to a certain point. Does anyone now how I would go about doing this?


texts: How do C# and UnityScript differ in Unity development?

texts:
Other than the obvious language differences, how do UnityScript and C# differ when developing games in Unity3D?

Is there a noticable performance difference?
Is the UnityScript code packaged as-is? If yes, does this help the game's moddability?
Is it possible to use libraries developed for one language while developing in the other one?
Can the two languages be mixed in the same Unity project; coding some parts in C# and others in UnityScript?


texts: How to plot hex tiles with different length sides?

texts:
I'm trying to create a basic grid of hex tiles. I found some code:

s=h/Math.cos(30*Math.PI/180)/2;
tile._x=x*s*1.5;
tile._y=y*h+(x%2)*h/2;

That does just that, but I think it's setup for hexes that have same length sides. However, my hex has different length sides. Its width is 140 and its height is 80. How would I change that code to accomodate this?


texts:
I've got a ball rolling along a flat surface towards a wall. If the ball collides with the wall, it always bounces perpendicular to the wall, no matter what it's velocity before, instead of following the angle of reflection.

Here is the relevant information about the ball:
Non-Kinematic Rigidbody
Collisions set to Continuous
Physic Material with 0.6 friction and 0.7 bounciness
Combine Modes are both average

And the wall:
Non-Kinematic Rigidbody
Collisions set to Continuous
Physic Material with 0.6 friction and 0.7 bounciness
Combine Modes are both average

I can probably manually check for collisions and change the velocity along the angle using Vector3.reflect, but this should be something the Unity Physics engine handles if I can figure out how. Is there anything that can be done in-engine to get the bounce angles to set properly?


texts:
When creating a central rendering system for all game objects in a given scene I am trying to work out the best way to go about passing the scene to the render system to be rendered.

If I have a scene managed by an arbitrary structure, i.e., an octree, bsp trees, quad-tree, kd tree, etc. What is the best way to pass this to the render system?

The obvious problem is that if simply given the root node of the structure, the render system would require an intrinsic knowledge of the structure in order to traverse the structure.

My solution to this is to clip all objects outside the frustum in the scene manager and then create a list of the objects which are left and pass this simple list to the render system, be it an array, a vector, a linked list, etc. (This would be a structure required by the render system as a means to know which objects should be rendered). The list would of course attempt to minimise OpenGL state changes by grouping objects that require the same rendering operations to be performed on them.

I have been thinking a lot about this and started searching various terms on here and followed any additional information/links but I have not really found a definitive answer. The case may be that there is no definitive answer but I would appreciate some advice and tips.

My question is, is this a reasonable solution to the problem? Are there any improvements that I could make? Are there any caveats I should know about?

Side question: Am I right in assuming that octrees, bsp trees, etc are all forms of BVH?


texts: Making games on Structure programming language c or c++

texts:
I am learning structured programming language C.  I know about data type, control statements, loops, arrays, strings, functions, pointers, structures and STL.

My question is, if I want to make game in C/C++:

Which topics should I learn?
Do I need to learn more topics mentioned above?
Do I need OOP in C++?
Is this possible without advance C++ graphics programming?
What are the advantages of OOP C++ and graphics programming?
Is there anything I need more than C/C++?


texts:
I'm new to Unity. I was learning coroutines and I wrote this.

private void Fire()
{
    if(Input.GetButtonDown("Fire1"))
    {
        StartCoroutine(FireContinuously());
    }
    if(Input.GetButtonUp("Fire1"))
    {
        StopAllCoroutines();
    }
}

IEnumerator FireContinuously()
{
    while(true)
    {
        GameObject laser = Instantiate(LaserPrefab, transform.position, Quaternion.identity) as GameObject;
        laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 10f);
        yield return new WaitForSeconds(firetime);
    }
}

When the button is pressed the coroutine is called and it enters the 'while' loop. When I leave the button it stops the coroutine. Shouldn't it get stuck in the 'while' loop as it is an infinite loop ? Why?


texts: How can I obtain a copy of the Kinect commercial SDK?

texts:
As far as I know, in order to publish a Kinect game on XBOX console, you need a commercial version of the Kinect SDK. The problem is, I couldn't find a reliable source to research about the subject. Do you know:

What are the conditions for getting the Kinect commercial SDK?
Is it possible to buy it without owning a company?


texts: How do I make this block go back to the left with another click?

texts:
This is the script I've written so far which makes the block move from the left of the screen to the right on a mouse click. What I want to achieve is for the block to move back to the left when I click the mouse again. So I can have a back and forth movement with each mouse click. Thank you for any help it's much appreciated.

public class PlayerControls1 : MonoBehaviour  {

private bool hasBeenTapped = false;
private bool control = false;
public float speed = 20f;

void Update () {
    if (Input.GetMouseButtonDown (0)) {
        hasBeenTapped = true;
            }

    if (hasBeenTapped && transform.position.x < 4 && control == false){
        transform.Translate (Vector2.right * speed * Time.deltaTime);
    }

    if(transform.position.x > 4.0f) {

        control = true;

        hasBeenTapped = false;
    }

    if(hasBeenTapped && transform.position.x == 4 || transform.position.x < 4 && control == true) {
        transform.Translate (-Vector2.right * speed * Time.deltaTime);

    if(transform.position.x < -4){

            control = false;

            hasBeenTapped = false;
        }
    }
  }
}


texts:
There is a theoretical mismatch of the entity system and the savegame system, which is think is common, but I haven't found resources about that. Therefore I will explain both systems first, as short as possible. I would really appreciate any thoughts and solutions for this conceptual problem.

Entity system

I have an entity system for my game. That means there is a function to create a new entity that simply returns a unique integer id. And there are functions to add, get and remove properties, thus any C++ objects, to a given id.

An entity id is just a contiguous integer, which is stored as a member. When a new entity is created, this number is incremented by one and returned as the new id. When entities get deleted, only all of their properties are removed and freed but their id actually remains and is not given to a new entity again.

Now you know the basics of my entity system. As an example, an entity might have properties for physics simulation, character animation, health and skill points, camera to render from its view, and so on.

(Originally, I described my entity system in more detail. But it wasn't directly related to this question and and wanted to shorten the question. It can still be viewed in the revision history.)

Savegame system

Previously, there was no savegame system and I created all entities as new ones on startup. But now I want to save the state when closing the application and load that on startup so that the player can continue where he left off.

I use SQLlite for storing, where each type of entity property gets its own table. I haven't decided yet if each row should store the entity id as primary key. Because this is part of my current problem.

Mismatch of both

Unfortunately, I cannot just store simply all of the entities to database, because some entities are only temporarily valid. For example the window property that holds a window handler from the operating system, which must be requested every startup. Or the meshes which aren't kept in memory, but just hold the VBO ids to the vertices on the GPU.

So I have to store some, but not all entities. I could store their entity id in the SQLite table and allow the entity system to add entities by a given new id. But I cannot guarantee that this id isn't already used by entities that where newly created at startup. Do you see the mismatch?

Can can I store the entity id to table, and still ensure that when being loaded, no other entity shares this id? Or how to restructure and rethink my entity system and savegame system to overcome this issue, in general?


texts: Does Unity for PC use Direct3D or OpenGL?

texts:
I am a mac developer using Unity and I hardly use a PC. When you build a Unity game for Windows, does it use Direct3D or OpenGL?

P.S. I'm not sure if it's called Direct3D or DirectX


texts:
I'd like to implement an AI for my game, which has agents that should be able to take care of themselves.

The Sims use a system of smart objects that advertise their services, a design pattern that seems very nice since all the logic is hidden away in the object to be used, and it seems simple enough to get started.

I am currently stumped though how to extend it to interactions between multiple people, and to people using objects together, especially when it doesn't make much sense to use an object together. (I don't want a character to set up a boardgame and wait, no one comes and he leaves again)


texts: Where and how should I check for collision in multiplayer game?

texts:
I'm making a multiplayer game. For now, I added a script to towers and I have booleans to change using OnTriggerEnter.

When triggered, client sends a message to server and towers health starts to get lower. So it works.

But I don't know if it's safe to use OnTriggerEnter because it calculates on the client side. Should I calculate on the server side ? And how I do it ? (Using Physics.ComputePenetration is a little bit slow.)


texts: Unity Camera - Clamping when Zoom changes?

texts:
I've got a basic camera I am working on for a 2D game that moves with the player and clamps to the area of the map. To the basics I've introduced a combination of player and eventual height-based zoom sort of Ski Safari or Lunar Lander style.

Zooming, however, changes the clamp positions and allows the land edges to be seen again. How can I fix this in the code, to prevent the edges that should be clamped from being seen when zoom is in effect?

using UnityEngine;

public class CameraController : MonoBehaviour
{
    public int zoomSpeed = 1;
    public int zoomMax = 25;
    public int zoomMin = 50;

    public float tarVelocity;
    public GameObject target;
    public Vector3 offset;

    private Vector3 targetPos;

    private Camera _cam;

    void Start()
    {
        _cam = GetComponent<Camera>();
        targetPos = transform.position;
    }

    void FixedUpdate()
    {
        if (target)
        {
            Vector3 targetDirection = (target.transform.position -   transform.position);
            tarVelocity = targetDirection.magnitude * 5f;
            targetPos = transform.position + (targetDirection.normalized *   tarVelocity * Time.deltaTime);
            transform.position = Vector3.Lerp(transform.position, targetPos + offset, 0.25f);
        }

    }

    void LateUpdate()
    {
        ClampCamera();
        CheckZoom();

        Vector3 posNoZ = transform.position;
        posNoZ.z = -10;

        transform.position = posNoZ;

    }

    private void ClampCamera()
    {
        Vector3 clampMovement = transform.position;

        clampMovement.x = Mathf.Clamp(clampMovement.x, 8f, 112);
        clampMovement.y = Mathf.Clamp(clampMovement.y, 6.6f, 100);

        transform.position = clampMovement;
    }

    private void CheckZoom()
    {
        if (Input.GetAxis("Mouse ScrollWheel") > 0 && Camera.main.orthographicSize > zoomMax)
            Camera.main.orthographicSize -= zoomSpeed;

        if (Input.GetAxis("Mouse ScrollWheel") < 0 && Camera.main.orthographicSize < zoomMin)
            Camera.main.orthographicSize += zoomSpeed;
    }
}


texts: Not sure how to deal with overlapping UI

texts:
As shown above, that is the issue I am faced with, tbh I am unsure how to fix it, I have tried and its coming to a point where I am drawing blank. I am quite newbie when it comes to this.

So what I have now is multiple canvas each one displaying the name of the part that it is linked to and when the part moves so does the UI with it, the problem I have is that some parts dont move and therefore creating the issue of UI clustering together, so I need to move the UI rather than the parts.

What I have tried is OnTriggerEnter and adding a box collider/rigidbody to the canvas and tried to move the UI when they collided but I couldnt get that to work, probably down to me.

if (gameObject.tag == "car")
    {

        //get the gameObjects name that canvas is attached to
        canvasName.text = gameObject.name;

        newPos = mainCam.ScreenToWorldPoint(this.transform.position);

        //set the position of the UI
        newPos.x = transform.position.x;
        newPos.y = transform.position.y + 7f;
        newPos.z = transform.position.z;

        //canvas position
        if (_canvas != null)
        {
            _canvas.transform.position = newPos;

        }

That is the code that I am using to attach the UI to the part. I was hoping to try something along the lines, but then again I am clueless.

if collision is detected, newPos.y = newPos + 2f; etc...

So any help would be appreciated. Apologies if that was explained bad.


texts:
I'm trying to stop movement when sprite arrive target position. But i couldn't handle it. Sprite  still move and pass target position.

Here's the code that runs every update to move it.

    public override void Update(GameTime gameTime)
    {
        if (!IsNasted)
        {
            //Find the delta time
            float delta = (float)gameTime.ElapsedGameTime.TotalSeconds * 300;
            //Find the direction
            Vector2 direction = ConvertUnits.ToDisplayUnits(targetPos) -
                 ConvertUnits.ToDisplayUnits(body.Position);
            if (direction.Length() < delta)
            {
                body.Position = targetPos;
                if (minx == movements.Count - 1) minx = 0;
                else minx++;
                targetPos = ConvertUnits.ToSimUnits(movements[minx]);
            }
            else
            {
                direction.Normalize();
                //Move towards it
                currentPos = direction * delta;
                body.Position += ConvertUnits.ToSimUnits(currentPos);
            }
        }
        base.Update(gameTime);
    }


texts:
I am making the game in this tutorial: https://www.youtube.com/watch?v=OR0e-1UBEOU

and at 2:53:23 he is coding a LevelController script. I noticed that mine wasn't working the way his was and so I went to try and debug the error. I found that the error was in the function FindObjectsOfType(); You can find my code below.

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

public class LevelController : MonoBehaviour
{
    private Enemy[] _enemies;

    private void onEnable()
    {
      _enemies = FindObjectsOfType<Enemy>();
    }

    // Update is called once per frame
    void Update()
    {
      Debug.Log(_enemies);
    }
}

When I run this my debug log returns null values which is confusing because I have 3 objects (Monster, Monster (1) and Monster (2)) which have the Enemy script assigned to them.

What could be going wrong?


texts: Is good idea to use single threaded server for games? Also can it handle multiple clients?

texts:
I was developing an game. I using single threaded nodejs(socket.io) server. It is good for simple games or games like basic 3d world? Usually game will have 10-20 players(clients).
Also is single threaded server can handle multiple clients same time?
like player 1 walks player 2 jumps same time.


texts: Where the fxc.exe is located in Windows SDK?

texts: I'm using Windows SDK under Windows 8 with Visual Studio 2013. Where I can find fxc? I do not use old Directx SDK.


texts: 3DS Max 2012 OBJ file import missing polygons

texts:
I started learning OpenGL. I got to a point I want to import some "real" objects. After "Googling" I decided I will go with OBJ file for start, since it is simple to understand, and there are plenty of tutorials on how to read them properly.

I have from university access to 3DS Max 2012. So I tried to create very simple model (just deformated cube) and exporting it using OBJ file, just to vertices and triangles for the moment, without textures, so I can examine its structure by myself. But if I imported it right back to 3DS from OBJ file, now it renders somewhat strange, like its smoothen, and with lightsource, even I have none in scene. But the geometry, its wireframe is intact.

So I thought maybe it is problem of exporting only vertices and triangles so I downloaded Enterprise-D model from internet, exported with everything on (normals, textures everything), and again imported it. Now, some polygons are missing.

So, I want to ask, am I doing something terribly wrong, or is there some incompatibility issue between .max and .obj file ? Even it is only simple textured model without any lightsources, animation etc.? Thanks.

Edit: I tried objects with MeshLab, the first, deformated cube was absolutelly OK. But still bothers me that 3DS Max doesen´t render it properly. In Enterprise-D model, there are polygons missing even in MeshLab. I uploaded rar archive with .max model of Enterprise, same .obj model exported from 3DS, and obj model of deformated cube. Download here (2.5 MB, filesonic).


texts:
The script:

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

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

    private bool scaleUp = false;
    private Coroutine scaleCoroutine;

    //Colors change
    public Color startColor;
    public Color endColor;
    public float colorDuration; // duration in seconds

    //Lights change
    public DimLights dimlights;
    private Coroutine lightCoroutine;

    //Rotate
    public float rotationSpeed;
    public float rotationDuration;

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

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

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

            if (lightCoroutine != null)
                StopCoroutine(lightCoroutine);

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

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

        //Change color
        if (Input.GetKeyDown(KeyCode.C))
        {
            StartCoroutine(ChangeColor());
        }

        //Rotate
        if (Input.GetKeyDown(KeyCode.R))
        {
            objectToScale.transform.Rotate(Vector3.up * rotationSpeed * Time.deltaTime);
            //StartCoroutine(RotateObject());
        }
    }

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

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

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

    IEnumerator ChangeColor()
    {
        float t = 0;

        while (t < colorDuration)
        {
            t += Time.deltaTime;
            GetComponent<Renderer>().material.color = Color.Lerp(startColor, endColor, t / colorDuration);
            yield return null;
        }
    }

    IEnumerator RotateObject()
    {
        float startTime = Time.time;

        while (Time.time - startTime < rotationDuration)
        {
            objectToScale.transform.Rotate(Vector3.up * rotationSpeed * Time.deltaTime);
            yield return null;
        }
    }
}

I tried using StartCoroutine but it didn't work.
So for testing I tried to make that if I'm click/pressing on R once it will rotate the object nonstop but it's not working either it's not rotating it all.

Nothing i click on R and nothing happen.
Tried to change the rotationSpeed from 1 to 10.


texts:
After spending a while looking through the forums, I haven't been able to find a thread that deals with transforms on an image.

Essentially, what I'm trying to do is display and hide an image at the start of a level in a game I'm working on. The image should start out large and with 100% transparency, then shrink to a certain size within the camera bounds with no transparency, idle for a second, then fade back out the way it came.

How would this be done programmatically? Thanks in advance!


texts: In Unity, why do my animator states wait until the end of each animation to change?

texts:
I'm trying to make a simple idle-walk transition in Animator using Unity.
I've set a script that changes the Speed value from the Animator, and it works perfectly when I move the character forward when the game is on.

The transitions work well between both animations, except that they don't start automatically after the speed has changed to greater than zero.

I've found out that it waits until the animation loop gets to it's end, which makes the game feel dull and not fluid at all.

I don't think there's an issue with the code, but I'm attaching it anyway:

#pragma strict
var anim : Animator;

function Start () {
    anim = GetComponent("Animator");
}

function Update () {
    var move : float = Input.GetAxis ("Vertical");
    anim.SetFloat("Speed",move);
    transform.Rotate(0,Input.GetAxis("Horizontal"),0);
    transform.Translate(0,0,(Input.GetAxis("Vertical")*Time.deltaTime*move));
}


texts: How to implement status-changing effects for attack class in turn based RPG?

texts:
I'm implementing "On Attack" and "On Receive Damage" within my game and from these two answers(Implementing flexible buff system,Implementing attack class in RPG  ) I got that I will be implementing custom handlers which will modify the attack effects. I've included an example below.

My question is - how to handle status changing special effects, such as knockdown, poison over time, petrify, etc? Do I need include them in my attack/damage class and have defender's damage handlers adjust the attack parameters, or is there a better way to handle special effects?

@interface Attack : NSObject

-(id)initWithDamage:(int)damage type:(int)damageType;

@property (nonatomic)int type;
@property (nonatomic)int value;
@property (nonatomic)int penetration;
@property (nonatomic,strong)NSMutableArray* attackEffects;
@end

Here's the understanding that's starting to form in my head:

Attacker records everything about the attack in an Attack class:
Create Attack class for each attack
Record damage type(physical/magical) and value
Pass Attack to the attacker's (onAttack) handlers
Each effect within attackers list of buffs applies it's effects to attack,(ex: poison over time, knockdown)
Pass the attack over to defender for his (onReceiveDamage) buffs to handle
Defender's list of buffs marked "on receive damage" modifies the attack (poison immunity removes poison over time)
Pass attack over to the defender to resolve
Check for special conditions (ex: can't poison undead), further adjust attack effects
Each effect that has passed the check is applied to defender

Repeat for counter attack.

What I'm concerned about: the method mutates attack instance, meaning any time I ask a character for attack, I actually need to get a copy of the attack. My attack class has started as a tuple, and there's already some code around that expects that checking attack is a simple operation. If attack gets overloaded with effects, and starts to be passed around as copy, this may have implications on my other code.