texts: How to architect input code to utilise state machine?

texts:
I have an InputController which currently handles all user input, so it looks at button states and updates entity intentions according to some simple rules.

I'm looking to add a new state to the game which essentially means displaying the player's inventory on screen. During this state I want the background to continue animating but want the user input to only interact with the inventory layer.

As the code stands right now the background will animate just fine under the inventory layer but the InputController will continue to behave like the layer isn't there and attempt to map clicks etc. to the game world.

An easy solution would be to add simple conditional logic in the controller if (currentState == x) but wondered if I could better utilise my existing game state machine. I have states such as game_loading, in_game, menu etc.

The only ideas I can come up with is either calling out to something like state.HandleInput() from inside the controller, that way the state is in control of what the player can and can't do but the downside is that input specific logic is being handled by a state rather than input specific code, which I'm not comfortable with.

Alternatively, I could reverse that and get the state to be the entry point and then they call out to specific input classes. So something like inGameState.HandleInput() calls out to inGameInputController likewise with inventoryState. This seems like the better approach.

I'm clearly not sure which way round the dependencies should orient. Am I missing a layer of abstraction somewhere? Or am I overcomplicating things?


texts: What does mean the float value in a voxel data?

texts:
We know that a voxel can be represented by a three dimensional array of boolean or float values. There is an answer that demonstrates this perfectly: the difference between binary/boolean or floating-point voxel.

If we use the binary way, we probably use a byte[,,], so we have 256 slots. They can be used to represent the content. For example, 0 can be air, 1 grass, 2 stone, 3 water.

By this way, we can define what is solid or not and which colour where.

But what about the floating-point way? So my question: What does the float value mean in a floating-point voxel context? Is there a way to use it as the binary way to describe the content and keep the terrain smooth?.

What I've experimented & What I get it?

I've tried to build a mesh with Marching Cube, filled with "random" 3d fractal from Perlin Noise. The result looks very good, but now how I am supposed to define what is what? (Air, Stone, ...)

I am pretty sure the solution was already answered in this answer. Unfortunately, even if I read the answer 5-6 times, I don't get it.

I understand there is a threshold which defines what is solid or not.

Giving me 3 for-loop pseudo code to fill with floating-point the three dimensional array would probably be helpful.


texts: How to adapt a webgl shader using mouse position to have symmetrical behaviour

texts:
I'm trying to create a particular kind of effect for the background of my SpriteKit game, and I've found some shaders on shadertoy that are close to what I want, but I'm struggling to adapt them to do exactly what I want..

There are a few shaders that simulate the sun with atmospheric scattering based on its xy position.
here are some examples:
https://www.shadertoy.com/view/MsVSWt
https://www.shadertoy.com/view/MdtXD2

I want something similar to this effect but I want the glow to be symmetrical, so that when the 'sun' reaches close to bottom or top edge the glow effect is at a maximum, and when it is in the centre it is at a minimum. I've been playing with these shaders trying to get this effect but my understanding of webgl is clearly lacking as I'm struggling to achieve this.

What I've tried playing with is replacing variables such as sunPosition.y with abs(sunPosition.y) - my logic being that the y axis ranges from -1 to 1 so I should be able to get symmetry by making everything positive.. but this in fact has no effect.

If someone can nudge me in the right direction would be greatly appreciated as I'm now thoroughly confused by webgl!


texts: LibGDX - Sending event to a button behaves differently from actually clicking it

texts:
I have a button on screen, and I want the user to be able to dismiss it by either clicking on it, or hitting space. The button is constructed as follows:

button = new TextButton("RESUME", skin);
button.setVisible(false);

button.addListener(new InputListener(){
  @Override
  public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
    return true;
  }

  @Override
  public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
    button.addAction(
      Actions.sequence(
        // send out of the screen
        Actions.moveTo(WORLD_WIDTH / 2 - button.getWidth() / 2, -button.getHeight(), 0.2f),
        Actions.hide(),
        Actions.run( () -> {
          resumeGame();
        }),
        Actions.removeActor()
      )
    );
  }
});

...
table.add(button);
stage.AddActor(table);
...

So if I make the button appear and click on it, everything is fine. I can repeat the sequence "button appear/click" at will, and each time the button will move offscreen to the bottom and will be removed from the table. I want the button to do exactly the same when the user hits space, so I did:

private void clickButton(TextButton button){
    InputEvent inputEvent = new InputEvent();
    inputEvent.setRelatedActor(button);

    inputEvent.setType(InputEvent.Type.touchDown);
    button.fire(inputEvent);

    inputEvent.setType(InputEvent.Type.touchUp);
    button.fire(inputEvent);
}

// then:

stage.addListener(new InputListener(){
  @Override
  public boolean keyDown(InputEvent event, int keycode) {

    if (keycode == Input.Keys.SPACE){
      clickButton(button);
      return true;
    }
}

Now when the button is shown and I hit space, it looks like it works, but if I make the button appear again, it's shown briefly then it disappears (it's removed from the table). It's like the final Actions.removeActor() in the button listener is not executed when the button is "clicked" using space, and it's then executed the next time when the button appears again, making it disappear immediately.

EDIT: this is indeed the case. I put a debug print statement right before the Actions.removeActor() action, and upon mouse click the text is printed, but using clickButton() it's not (and it's printed instead when the button is shown again and readded to the table).

Am I doing something wrong here? What's the "correct" way to click a button programmatically (yes, I've already seen https://stackoverflow.com/questions/25870645/programatically-perform-click-on-actor-libgdx)


texts: How to create a looping or spherical world?

texts: I wish to create a 3D first person world, in which the player, once they reach one end of the map are unknowingly transported back to the opposite end, or a spherical world with a surface where the player can walk on while still experiencing gravity like normal. Unfortunately I couldn't find a good solution for doing that in either unity or ue. Any ideas would be appreciated.


texts: Should the color of a texture be adjusted for display on a television?

texts:
If a 24bit RGB image with a range of 0-255 per channel is displayed on a television that displays a range of approx. 16-235 per channel, color detail will be lost, correct?

If so, should images be pre-processed to only store a valid range? I would like to do this with code, not in a picture editing application. I vaguely recall reading that a linear mapping is not the best way to do this, but unfortunately I can't locate the article I was reading! What is this process called? What other details do I need to know?


texts: Only first vertex of data used in shader OpenGL

texts:
I'm making a voxel game like Minecraft which was working fine until I added water. Then I realized that whatever the texture was for the first visible block was applied to the rest of the blocks in the chunk. I am drawing a total of 36 vertices per cube and it seems that although the instanced array for the cube positions is working, only the first 36 texture coordinates are being used.

I raised all visible ocean. Locks in the second picture which is how I determined the actual coastline.

creating the buffers

glGenVertexArrays(1,&chunk->chunkVAO);
    //glGenBuffers(1,&chunk->chunkEBO);
    glGenBuffers(1,&chunk->cubeVBO);
    glGenBuffers(1,&chunk->posOffsetVBO);
    glGenBuffers(1,&chunk->texCoordVBO);

glBindVertexArray(chunk->chunkVAO);

glBindBuffer(GL_ARRAY_BUFFER,chunk->cubeVBO);
glBufferData(GL_ARRAY_BUFFER,sizeof(cubeVertices),cubeVertices,GL_STATIC_DRAW);

glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,3*sizeof(GLfloat),(GLvoid*)0);
glEnableVertexAttribArray(0);

glBindBuffer(GL_ARRAY_BUFFER,chunk->texCoordVBO);
glBufferData(GL_ARRAY_BUFFER,sizeof(glm::vec2)*36*65536,NULL,GL_DYNAMIC_DRAW);

glVertexAttribPointer(1,2,GL_FLOAT,GL_FALSE,2*sizeof(GLfloat),(GLvoid*)0);
glEnableVertexAttribArray(1);

glBindBuffer(GL_ARRAY_BUFFER,chunk->posOffsetVBO);
glBufferData(GL_ARRAY_BUFFER,sizeof(glm::vec3)*65536,NULL,GL_DYNAMIC_DRAW);

glVertexAttribPointer(2,3,GL_FLOAT,GL_FALSE,3*sizeof(GLfloat),(GLvoid*)0);
glEnableVertexAttribArray(2);
glVertexAttribDivisor(2,1);

filling the texture and position VBO after occlusion culling

glBindBuffer(GL_ARRAY_BUFFER,chunk->texCoordVBO);

glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(texCoords),&texCoords[0]);

glBindBuffer(GL_ARRAY_BUFFER,chunk->posOffsetVBO);

glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(positions),&positions[0]);

glBindBuffer(GL_ARRAY_BUFFER,0);

rendering

glBindVertexArray(temp->chunkVAO);

glDrawArraysInstanced(GL_TRIANGLES,0,36,temp->visibleBlocks);

How come only one of the blocks worth of texture coordinates is  being  used?


texts:
I'm trying to make my own 3D model editor to better learn 3D programming. I have my translate manipulators and I'm trying to calculate the Vector2 that the mouse would have to move in order to move an object down a specific axis. This will obviously change based on the position of the camera, position of the object and the axis. I have the majority of it working, I'm just not sure on how to finish it. If the camera is completely horizontal to the object then the values come out correct, but once I start to move the camera above or below the object the values start to get less accurate. I figure I need to incorporate the camera's up vector into it, but I'm not sure how.

The code snippet is for the X axis.

Vector3 meshCameraDistance = meshPosition - cameraPosition;
Vector3 angleAxis = new Vector3(1, 0, 0);
float meshCameraAngle = Vector3.Angle(meshCameraDistance, angleAxis);
Vector2 mouseDragDirection = new Vector2(Mathf.Sin(Mathf.Deg2Rad * meshCameraAngle), Mathf.Cos(Mathf.Deg2Rad * meshCameraAngle));

if (meshCameraDistance.z < 0)
{
    mouseDragDirection = new Vector3(-mouseDragDirection.x, mouseDragDirection.y);
}

speed = (manipulatorSpeed.x * mouseDragDirection.x) + (manipulatorSpeed.y * mouseDragDirection.y);


texts: How can I define items in my RPG like Java game?

texts:
I am casually working on an RPG type game in Java but I am having trouble figuring out how I can have items that can do many different things without creating a different class for every item.

As an example, how would I create an Axe that could chop trees and attack monsters?

If I extend either the chopping or the weapon class then I can't extend the other class.

If I have chopping and weapon be an interface then I will have a lot of duplicated code when a dagger can also attack monsters and a different axe can cut trees.

I am hoping there is a way to have a single Item class and load the items and their respective abilities from a file. If that is possible how can it be done? If it isn't then what is the best way to have items in a game?


texts: How to make a function in Haxe that reads content from text file and does something with each line?

texts:
How can I make a function in Haxe that reads a line from a text file, prints it/saves it to a variable, and then goes to the next line?

My objective is to make the dialogues on a text file, having the code read a line, and if the first word (a keyword like 'Dialogue01') is found, it reads all the text after such keyword on the same line and it checks the next line for another keyword or a different command to notify the game to advance or show the next dialogue.


texts: How do I get a reference to a component on a sibling object in C# Script?

texts:
I'm working on a game, where the player dumps trash from Trash cans into a Trash Truck. These Trash cans have a random chance of having a Racoon on top of them.
I have a script set up to detect when the player enters a Collider Trigger attached to the Racoon, which will cause it to play an animation and start attacking the player.
To do that, it needs to work with a racoon navigation component on a neighbouring object:

I'm trying to access the RacoonNAVAI component on the Racoon_Mover game object with this line:
racNav = transform.parent.parent.Find("Racoon Mover").gameObject.GetComponent<RacoonNAVAI>();

But it's throwing a null reference exception. How can I correctly get a reference to this component?


texts: SFML - How to implement a simple 2D lighting system

texts:
Lately, I've been reading a lot about 2D lighting systems in a game, and have observed just how much lighting can add to a game's graphics appeal. However, as for implementing one of these in SFML, I am clueless. The lighting system I would like doesn't have to be too complex - I don't need things such as shadows. What I would like is something like this, which I made in Java using swing:

How this works:

I draw a black rectangle over the whole image with an alpha that changes based on the in-game time of day - 0 during the day, 128 during the night.
On top of that rectangle, I draw a gradient on top of the player's x and y coordinates - from (255, 255, 255, 100) to (0, 0, 0, 0)

What would be the ideal way to impement this in SFML?


texts:
I am working on the server plugin for TF2. I need it for getting some stats from game (no hacking and cheating). My problem: I got message "No valid signature found..." while testing my plugin. But I want to make my plugin public in future (maybe).

Please tell me about signing procedure. How can I get valid signature for my plugin? What I must to do (send my plugin to Valve or what else)?


texts:
I'm making a game for Windows Phone 8 using XNA 4.0 in Visual Studio express 2012. I'm trying to add a background image to the game with a size of 1366x768 (as I believe WP8 only supports up to 720p). Everything stretches  well on the other emulators (WVGA and WXGA) until I use the 720p emulator and I get black bars on the sides:

How can I fix this, or is this normal?

This is all the code I have used so far:

GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    Texture2D Background;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";

        graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight;

        this.graphics.IsFullScreen = true;

        // Frame rate is 30 fps by default for Windows Phone.
        TargetElapsedTime = TimeSpan.FromTicks(333333);

        // Extend battery life under lock.
        InactiveSleepTime = TimeSpan.FromSeconds(1);
    }

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize()
    {
        // TODO: Add your initialization logic here

        base.Initialize();
    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        Background = Content.Load<Texture2D>("SkyBackground");

    }

    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// all content.
    /// </summary>
    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        base.Update(gameTime);
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        // TODO: Add your drawing code here
        spriteBatch.Begin();
        drawBackground();
        spriteBatch.End();

        base.Draw(gameTime);
    }

    private void drawBackground()
    {
        spriteBatch.Draw(Background, GraphicsDevice.Viewport.Bounds, Color.White);
    }


texts: Making A Sprite Rotate To A Specific Angle XNA 4.0

texts:
I have a game that the character spins when you press either of the triggers on the xbox remote. Here's the code.

if (gamepadState.IsButtonDown(Buttons.RightTrigger))
        RotationAngle += spinSpeed;

if (gamepadState.IsButtonDown(Buttons.LeftTrigger))
        RotationAngle -= spinSpeed;

what i want to happen is when neither of the triggers are being pressed he rotates back to a rotation angle of 0. I know How to make him go back to 0 when neither triggers are pulled but its too abrupt. How can i make the sprite actually rotate back to an angle of 0?


texts:
How can i Serialize IConvertible variable to show up in the inspector? As it now, i can only see the string name. But not the value.

E.g adding CStat

item.AddCStats("description", "This a long ranged boosted weapon.");
item.AddCStats("attack", 10);
item.AddCStats("speed", 50f);
item.AddCStats("unique", true)

[System.Serializable]
public class Item : ISerializationCallbackReceiver
{
    [SerializeField]
    public int id = 0;
    [SerializeField]
    public int amount = 1;
    [SerializeField]
    public List<CStats> cstats = new List<CStats>();
    public Dictionary<name, IConvertible> cstatsDictionary = new Dictionary<name, IConvertible>();

    public Item(int id, int amount)
    {
        this.id = id;
        this.amount = amount;
    }

    public void AddCStats<T>(string name, T value) where T : IConvertible
    {
        if (!cstatsDictionary.TryGetValue(name, out _))
        {
            cstatsDictionary.Add(name, value);
        }
        else
        {
            cstatsDictionary[name] = value;
        }

        for (int i = 0; i < cstats.Count; i++)
        {
            if cstats[i].name == name)
            {
                cstats[i].value = value;
                return;
            }
        }

        cstats.Add(new CStats(name, value));
    }

    public T GetCStat<T>(string name) where T : IConvertible
    {
        return cstatsDictionary.TryGetValue(name, out IConvertible value) ? ConvertToType<T>(value) : default;
    }

    public void OnAfterDeserialize()
    {
        cstatsDictionary = new Dictionary<string, IConvertible>();
        for (int i = 0; i < cstats.Count; i++)
        {
            cstatsDictionary.Add(cstats[i].name, cstats[i].value);
        }
    }

    public void OnBeforeSerialize()
    {
    }

    private T ConvertToType<T>(IConvertible value) where T : IConvertible
    {
        return (T)value.ToType(typeof(T), null);
    }
}

[System.Serializable]
public class CStats
{
    [SerializeField]
    public string name = String.empty;
    [SerializeField]
    public IConvertible value = null;

    public CStats(string name, IConvertible value)
    {
        this.name = name;
        this.value = value;
    }
}


texts: Programatically loading fonts, textures, and media in XNA

texts:
So far, in my rhythm game, I've been using XNA's Content Pipeline for loading static resources in my app (videos, sound effects, etc). However, down the road I'd want to allow users to create their own themes, as well as making custom notecharts for whatever songs they'd like to play. Is there any way to load say, a Texture2D or Video object, from disk without using the Content Pipeline, given a file path to the resource?

EDIT: Even thought this is XNA, I'm targeting Windows only (no Zune, WP7, or Xbox 360).


texts: Square Grid Polygonal Terrain Query algorithm?

texts:
I have a square, fixed-grid terrain with one terrain type per grid unit in my game, and I want to do an arbitrary polygonal terrain query which returns all of the grid units enclosed/intersected by the polygon. Can anyone point me towards an algorithm for this?

I'll be using this to make sure that my actors aren't going through invalid terrain when they move.

Thanks!


texts:
I'm trying to use GLFW3 to develop VJing application. So basic idea is use two windows:

1st window for fullscreen projection on secondary monitor (basically projector)

2nd window for (hopefully) fullscreen GUI.

It does not have to share context, as GUI window will be just using libRocket for controlling content, recieving MIDI & OSC commands, etc.

Problem is that so far, when I switch projection window on second monitor to fullscreen, it runs, but as soon as I move mouse to primary monitor and click somewhere, projection window gets minimized. Also, GUI window gets a poor framerate.

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <GLFW/glfw3.h>

using namespace std;

void errorCallback(int error, const char *description){
fputs(description, stderr);
}

static void keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods){
if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
{
    glfwSetWindowShouldClose(window, GL_TRUE);
}
}

int main(){

glfwSetErrorCallback(errorCallback);
if (!glfwInit())
{
    exit(EXIT_FAILURE);
}

int MonitorCount;
GLFWmonitor ** monitors = glfwGetMonitors(&MonitorCount);

//GLFWvidmode* modes = glfwGetVideoModes(monitors, &MonitorCount);

GLFWwindow *window;
window = glfwCreateWindow(1024, 768,"Projection", monitors[0], NULL);
GLFWwindow *controls;
controls = glfwCreateWindow(1024, 768, "Controls", glfwGetPrimaryMonitor(), NULL);

glfwSetKeyCallback(window, keyCallback);
while(!glfwWindowShouldClose(window)){

     //// PROJECTION WINDOW
    glfwMakeContextCurrent(window);

    float ratio;
    int width, height;
    glfwGetFramebufferSize(window, &width, &height);
    ratio = width / (float) height;
    glViewport(0,0, width, height);
    glClear(GL_COLOR_BUFFER_BIT);

      glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glRotatef((float) glfwGetTime() * 50.f, 0.f, 0.f, 1.f);
    glBegin(GL_TRIANGLES);
    glColor3f(1.f, 0.f, 0.f);
    glVertex3f(-0.6f, -0.4f, 0.f);
    glColor3f(0.f, 1.f, 0.f);
    glVertex3f(0.6f, -0.4f, 0.f);
    glColor3f(0.f, 0.f, 1.f);
    glVertex3f(0.f, 0.6f, 0.f);
    glEnd();

    //// ---- CONTROL WINDOW ----
    glfwMakeContextCurrent(controls);
    glfwGetFramebufferSize(controls, &width, &height);
    ratio = width / (float) height;
    glViewport(0,0, width, height);
    glClear(GL_COLOR_BUFFER_BIT);

          glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glRotatef((float) glfwGetTime() * 100.f, 0.f, 0.f, 1.f);
    glBegin(GL_TRIANGLES);
    glColor3f(0.f, 0.f, 0.f);
    glVertex3f(-0.6f, -0.4f, 0.f);
    glColor3f(0.f, 1.f, 0.f);
    glVertex3f(0.6f, -0.4f, 0.f);
    glColor3f(0.f, 0.f, 1.f);
    glVertex3f(0.f, 0.6f, 0.f);
    glEnd();

    glfwSwapBuffers(controls);
    glfwSwapBuffers(window);

    glfwPollEvents();
}

glfwDestroyWindow(controls);
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);

}

I'm on Win7 / VS2012 using nVidia 680m


texts: Geometry Shader and Stream Output with Directx11

texts:
I am having trouble trying to send verticies generated in the Geometry Shader to Stream Output. What I am trying to accomplish is to generate verticies from the Geometry Shader and store them to a vertex buffer so that I can use the vertex buffer to draw later.

I read that I have to use the CreateGeometryShaderWithStreamOutput function to create a Geometry Shader that can send verticies to Stream Output instead of the rasterization stage.

This is how I am trying to use it:

    device->CreateGeometryShaderWithStreamOutput(this->mGSBlobSO->GetBufferPointer(), this->mGSBlobSO->GetBufferSize(), so_decl, 1, &stride, 1, D3D11_SO_NO_RASTERIZED_STREAM, NULL, &this->mGeometryShaderSO)

I am getting an E_INVALIDARG at this line. I am specifying D3D11_SO_NO_RASTERIZED_STREAM because I think this means that I do not want to send data to the rasterizer but I am not sure. When I replace D3D11_SO_NO_RASTERIZED_STREAM with a 0, I do not get this runtime error, but I do not get the result I want.

How can I setup the geometry shader to store vertices to a vertex buffer in Stream Output?


texts: I've got a web-based strategy game in which you build a city. Coding is smooth, but I'm kind of hung up on how long it takes my buildings to build. I want to keep the user playing, but have them long enough to keep them having to come back to the game. I've currently got it where each building has a base build rate that is exponentially increased by the building's level. I can adjust the times by changing the base build rate, but I was wondering if there is a better, or perhaps more widely-accepted way of doing this. I worry that a 113 day build on a level 10 building before reaching the next city level where the user has to start over will discourage further playing.


texts:
I have a pretty vanilla Monogame game. I'm using PNG for all my sprites (made in Photoshop). I noticed that XNA is butchering the aliasing; no matter what I do, my graphics appear jaggedy.

Below is a screenshot. The bottom half is what XNA shows me when I zoom in 2X using a Matrix on my GraphicsDevice (to make the effect more obvious). The top is when I pasted the same sprites from Photoshop and scaled them to 200%.

Note that partially transparent pixels are turning whiteish.

Is there a way to fix this? What am I doing wrong?

Here's the relevant call to draw to the SpriteBatch:

spriteBatch.Draw(this.texture, this.positionVector, null, Color.White, this.Angle, this.originVector, 1f, SpriteEffects.None, 0f);

(this.positionVector can easily be Vector.Zero; Color.White as 100% alpha, I think; this.Angle can be a real angle (small > in the image) or zero (the orb itself).


texts:
The other day I herd this "MSN Game API" mentioned, but I can not find any information about it anywhere. This particular API seems to be for browser based games (Such as Flash, and ActiveX embedded games).

What exactly is this API for? And is that its correct name? is it to do with the MSN Zone? Where can I find more information about it, and maybe even some documentation on the actual API.


texts:
I'm building a game using SDL in Linux platform.

Now I want to read user input with SDL_GetKeyboardState, but my doubt is wich is the best way using a thread or a timer.

I tried both and I think they work well.


texts:
As far as I'm aware, all 3D animation software (Maya, Blender...) has framerates. That is, keyframes can only be placed on discrete points in time. Why is that? Why can't animation keyframes be placed at any point in time?
The animations are interpolated in the game engine anyway, the game framerate is rarely the same as the animation framerate and even then, somethimes the game's frames land inbetween the animation's frames and we see the interpolated animation anyway.


texts:
I'm creating a Top-Down Racing Game in C++ using GLUT/OPENGL and SOIL first of all I just wanted some opinions on how the track should be done. I was thinking about using a tile-map and so far I've implemented one but it draws a polygon for each value in the tile-map then uses the assigned texture. This is obviously a really in efficient way of drawing the background.

So how to go about concatenating the appropriate texture's together into one PNG/GL-TEXTURE that way I can just draw one big polygon and use the texture created from the concatenation process.

Also what's the best way of going about collision detection when it comes to tile-maps?


texts:
I'd like to limit rotation of an object, so I've written following snippet:

if (targetRotation < constraintMin) {
    targetRotation = constraintMin;
} else if (targetRotation > constraintMax) {
    targetRotation = constraintMax;
}

It works fine when moving in clockwise direction (big chunk starting right of blue lines), however nothing I've tried works work counterclockwise (smaller chunk between blue lines) because of Math.PI -> -Math.PI jump.

Here's working outer angle constraint between -3 and 3. However I'd like to make one between 3 and -3, but cannot think of how to do that.

const SPEED = 0.05;
let div = document.querySelector('div');
let targetRotation = Math.PI - 0.1;
let rotation = 0;

const CONSTRAINT_MIN = -3;
const CONSTRAINT_MAX = 3;

function rotate(dt) {
  let deltaRotation = (targetRotation - rotation) % (Math.PI * 2);

  let constraintDiffMin = ((CONSTRAINT_MIN - deltaRotation) + Math.PI * 4) % (Math.PI * 2);
  let constraintDiffMax = ((CONSTRAINT_MAX - deltaRotation) + Math.PI * 4) % (Math.PI * 2);

  //This works for outer angle
  if (deltaRotation < CONSTRAINT_MIN) {
    deltaRotation = CONSTRAINT_MIN;
  } else if (deltaRotation > CONSTRAINT_MAX) {
    deltaRotation = CONSTRAINT_MAX;
  }

  //But how to make it constraint inner angle between MAX and MIN?

  if (Math.abs(deltaRotation) > Math.PI) {
    deltaRotation -= 2 * Math.PI * (deltaRotation / Math.abs(deltaRotation));
  }

  rotation += deltaRotation * SPEED;
  div.style.transform = 'rotate(' + rotation + 'rad)';

  requestAnimationFrame(rotate);
}

document.addEventListener('mousemove', function(e) {
  targetRotation = Math.atan2(e.y - 100, e.x - 100);
}, false);

requestAnimationFrame(rotate);
div {
  width: 100px;
  height: 30px;
  background: linear-gradient(45deg, #BADA55, red);
  transform: rotate(0);
  margin: 85px 50px 0;
}
<div>
</div>

How can I resolve this?


texts:
I am using advanced OpenDL methods (VBO, VBA, ...) to render over screen. Currently I abstracted vbo, vba, index buffer, texture, and shader to a class called 'Object2D'.

I tried to render two objects on screen. I saw that when the same shader is applied to both objects it works fine; but if the two objects are rendered with two different shader script, only the one rendered last is visible to screen.

Here is Object2D::render():

void Render()
{
    if(check_status())
    {
        sh.bind(); //shader
        vb.Bind(); //vertex buffer
        ib.Bind(); //index buffer
        tex.bind(); //texture buffer
        glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT,NULL);
    }
    else{}
    //sh.unbind();
}

And here is the drawing function (assume the two 2D objects are obj and box):

void display()
{
    glClear(GL_COLOR_BUFFER_BIT); //refresh/..
    box.sh.setUniformMat4x4("m_projection",GL_FALSE,1,&m_PROJ[0][0]);
    box.Render();
    obj.sh.setUniformMat4x4("projection_matrix",GL_FALSE,1,&m_PROJ[0][0]);
    obj.sh.setUniformMat4x4("view_matrix",GL_FALSE,1,&view_transform[0][0]);
    obj.Render();
    glFlush();
}

And this is the shader binded to box:

#shader vertex
#version 330 core

layout(location = 0) in vec4 positions;
uniform mat4 m_projection;
void main(void)
{
    gl_Position=m_projection*positions;
}

#shader fragment
#version 330 core

layout(location=0) out vec4 color;

void main(void)
{
    color=vec4(1.0,0.4,0.3,1.0);
}

and this shader is binded to obj:

#shader vertex
#version 330 core

layout(location = 0) in vec4 positions;
layout(location=0) in vec2 texture_coodrinate;
out vec4 p;
out vec2 TexCoord;
uniform mat4 projection_matrix;
uniform mat4 view_matrix;

void main(void)
{
    gl_Position=projection_matrix*view_matrix*positions; //modelvi
    p=projection_matrix*view_matrix*positions;;
    TexCoord=texture_coodrinate;
}

#shader fragment
#version 330 core

layout(location=0) out vec4 color;
in vec4 p;
in vec2 TexCoord;
uniform vec4 U_color;
uniform sampler2D tex_;

void main(void)
{
    ;
    U_color;
    color=texture(tex_,TexCoord);
}

My problems are:

Two of the objects aren't being rendered if until and unless both the shaders are same
Unbinding the shader result in no rendering?


texts:
What sort of design patterns and ideas might one use to build a somewhat general purpose card game framework?

This stems from I made an attempt to build a clone of the popular Steve Jackson game "Munchkin".  Because of the nature of that game I ended having to hard code so many card functionalities that the development became chaotic and over-bearing.  I had wanted to build something general but ended up with just to many classes with to many overridden functions and switch statements to determine behavior.

I was curious what someone with more experience in design would handle such a task of building a general purpose card game framework, or at least something that could be extended.  Or is it best that if I want to make a simulation of a card game like Munchkin, i'm stuck making a specific framework.

I would like to use C#.

EDIT

I would like to clarify somewhat of what i'd eventually like to achieve.  I'd like a framework where I can basically implement phases with custom functionality (phase 1: draw cards, phase 2: apply upkeep rules, phase 3: play cards, phase 4: resolve, etc).

I think then defining a ruleset would be wise which would be coupled with both the cards and the phases.

Then, the cards would be defined and I suppose tied to the rules so for instance a rule might be "During upkeep phase, lose 1 token".  However, a card that the player has might provide "Don't lose any tokens during the upkeep phase".  So it would be nice to be able to tie this together but within the guts of the framework.

I suppose this might be way out of my league as well.


texts: how can I rotate a tetrahedron's vertices so that it's pointing straight up?

texts:
I am trying to render an Equilateral triangle in 3D, and I came across this answer:
https://math.stackexchange.com/a/562895/15497
So based off of that, I made my vertex points:
(1, 1, 1),
(1, -1, -1),
(-1, -1, 1),
(-1, 1, -1),

This looks great when I draw lines across these points, however the triangle is not pointing straight up as I would like it to.  I am trying to understand how to calculate the right amount to rotate the X, and Z axis so that it is pointing upwards?

I messed around with rotating the X by PI / 5 and Z by -PI / 5 and got something close:

But that is not right...


texts: Making game constants/tables available to game logic classes/routines in a modular manner

texts:
Suppose I have a game where there are several predefined constants and charts (a XP chart, cost of goods and so on). Those could be defined at runtime, or load from files at start-up. The question is how should those logic routines access the constants and charts?

For example, I could try using global variables, but that cause all classes relying on the variables to  be tightly coupled with them.


texts: SDL (or OpenGL), HTML5, Gecko and vector movies

texts:
I'm writing a platform game which uses SDL for the main graphics code. There is a chance that I may be using OpenGL for the rendering at a later stage, so answers could relate to either.

I'm needing a good method to include vector animations (such as a starting video) within the game.

Being a platform game, I would prefer to limit the dependents and size of the data. This rules out using Theora as the resulting vector animations would be needlessly lossy and overly large compared to the rest of the content. Flash sounds like an OK option, however it is finicky to embed (or even use) on non-windows platforms, and requires significant amounts of dependencies.

My idea is to use HTML5 animations, rendered by Gecko (the embeddable Firefox rendering engine) or WebKit (the Chrome rendering engine) in SDL, or rendered to an OpenGL surface in SDL. Quite simply - is this feasable? Are there any other examples as to how I should embed it? Is there a better (read: smaller and simpler) solution?


texts: How to simulate explosions vehicle parts?

texts:
I've downloaded some 3D vehicle models that I bought from the Asset Store, because I don't know how to create 3d models.

These objects have different meshes for different vehicle parts: steering wheel, doors, body, lamp lights, hood etc.

I would like to simulate an explosion and apply physics impulses to each of the parts.

I've tried this flow:

Create a rigidbody for each vehicle part, set its weight and set:
isKinematic = true;   useGravity= false;
Create a mesh collider for each part and disable it
Create a main box collider for vehicle

When a bullet, or other explosive object, hits my vehicle, I've tried to use a script to enable these components on the parts: rigidbody (isKinematic = false, useGravity=true) and mesh collider, and, obviously, apply a force explosion.

The problem is that it's not possible to enable a mesh collider at runtime for performance reasons (it lags a lot, and this does not depend on PC/Hardware power, but depends from graphics pipeline).

So my question is: how can I simulate an explosion by applying forces to individual vehicle parts?


texts:
this.attract = function () {
        for (let i = 0; i < numofplanets; i) {
            var r = Math.sqrt(Math.pow(blackhole.x - planet[i].x, 2) + Math.pow(blackhole.y - planet[i].y, 2));
            planet[i].acclx = (blackhole.mass(blackhole.x - planet[i].x)) / Math.pow(r, 3);
            planet[i].accly = (blackhole.mass - (blackhole.y - planet[i].y)) / Math.pow(r, 3);
            // planet[i].acclx=(blackhole.x-planet[i].x)/60000; without force implementation in which planets get sucked inside the blackhole
            // planet[i].accly=(blackhole.y-planet[i].y)/60000; without force implementation in which planets get sucked inside the blackhole)
            planet[i].speedy += planet[i].accly;
            planet[i].x += planet[i].speedx;
            planet[i].y += planet[i].speedy;
        }
    }

i am trying to create gravity simulation model for a game in JavaScript.i need planets to move around a black hole in elliptical orbits.
first i calculate acceleration and then add it to velocity and according to that i calculate the next position of planet. i first tried with just calculating distance vector between planets and black hole but in that scenario planets directly gets sucked inside the black hole and i need them to move in elliptical orbits. i tried calculating acceleration due to gravity but i think formula is wrong so can you correct it or provide some other implementation.


texts:
So I've been making this top down 2D java game in this framework called Greenfoot and I've been working on the AI for the guys you are gonna fight. I want them to be able to move around the world realistically so I soon realized, amongst a couple of other things, I would need some kind of pathfinding.

I have made two A* prototypes. One is grid based and then I made one that works with waypoints so now I need to work out a way to get from a 2d "map" of the obstacles/buildings to a graph of nodes that I can make a path from. The actual pathfinding seems fine, just my open and closed lists could use a more efficient data structure, but I'll get to that if and when I need to.

I intend to use a navigational mesh for all the reasons out lined in this post on ai-blog.net. However, the problem I have faced is that what A* thinks is the shortest path from the polygon centres/edges is not necessarily the shortest path if you travel through any part of the node. To get a better idea you can see the question I asked on stackoverflow.

I got a good answer concerning a visibility graph. I have since purchased the book (Computational Geometry: Algorithms and Applications) and read further into the topic, however I am still in favour of a navigational mesh (See "Managing Complexity" from Amit’s Notes about Path-Finding).
(As a side note, maybe I could possibly use Theta* to convert multiple waypoints into one straight line if the first and last are not obscured. Or each time I move back check to the waypoint before last to see if I can go straight from that to this)

So basically what I want is a navigational mesh where once I have put it through a funnel algorithm (e.g. this one from Digesting Duck) I will get the true shortest path, rather than get one that is the shortest path following node to node only, but not the actual shortest given that you can go through some polygons and skip nodes/edges.

Oh and I also want to know how you suggest storing the information concerning the polygons. For the waypoint prototype example I made I just had each node as an object and stored a list of all the other nodes you could travel to from that node, I'm guessing that won't work with polygons? and how to I tell if a polygon is open/traversable or if it is a solid object? How do I store which nodes make up the polygon?

Finally, for the record: I do want to programme this by myself from scratch even though there are already other solutions available and I don't intend to be (re) using this code in anything other than this game so it does not matter that it will inevitably be poor quality.


texts:
gluLookAt is not available in OpenGLES 2.  OpenGLES 2 is also using floats not doubles.

Taking the description on the gluLookAt man-page, I have implemented it like this:

void graphics_t::set_mvp_look_at(const vec_t& eye,const vec_t& centre,const vec_t& up) {
#if !defined(GL2) && !defined(NDEBUG)
    matrix_t check;
    glMatrixMode(GL_PROJECTION);
    glLoadMatrixf(pimpl->mvp.f);
    gluLookAt(eye.x,eye.y,eye.z,centre.x,centre.y,centre.z,up.x,up.y,up.z);
    glGetFloatv(GL_PROJECTION_MATRIX,check.f);
#endif
    const vec_t f((centre-eye).normalised()),
        s(f.cross(up.normalised())),
        u(s.cross(f));
    const matrix_t m = {{
        s.x, s.y, s.z, 0,
        u.x, u.y, u.z, 0,
        -f.x, -f.y, -f.z, 0,
        0, 0, 0, 1
    }};
    set_mvp_matrix(matrix_t::translation(-eye).transposition() * (m.transposition() * pimpl->mvp)); // setter notifies shader
#if !defined(GL2) && !defined(NDEBUG)
    if(pimpl->mvp != check)
        std::cout << "WARNING! Error setting look-up: " << std::endl << pimpl->mvp << std::endl << " != " << std::endl << check << std::endl;
#endif
}

As you can see I have some inline unit-testing when building for a non-OpenGLES 2 target (that's my own GL2 define).

Now the code seems to work, although it feels somehow slightly wrong depth but I can't put my fingers on that.

However, the code is printing warnings all the time, e.g.:

  WARNING! Error setting look-up:
  matrix_t<[4.79627,0,0.424102,-261.019],[0.243815,5.79255,-2.75737,51.5329],[0.158943,-0.862347,-1.79752,269.079],[0.0794715,-0.431174,-0.898762,350.119]>
  !=
  matrix_t<[5.31579,0,0.470039,-289.291],[0.270225,6.41998,-3.05604,57.1149],[0.158943,-0.862347,-1.79752,269.079],[0.0794715,-0.431174,-0.898762,350.119]>

As you can see, the numbers are very nearly the same but not-quite.

My comparision function for my matrix class is fuzzy with if(fabs(f[i]-rhs.f[i])>0.001) return false;.

Is this error within expected bounds when using float precision instead of doubles?  Or is there a bigger bug in my translation?


texts: What all should be happening during the "Loading" screen?

texts:
Do I just need to be creating instances of all of my graphics into memory that are loaded from file?  What is the best way to handle this?  Do I just need some sort of assets manager that creates these graphic instances during the loading screen and is then referred to later?

What are common things that need to be pre-loaded in games?  How  much should I pre-load?

Is it worth showing some sort of progress bar?  How can I keep load times short?  What should the loading screen look like?

What are some good examples of loading screens?  Any code examples?

Specifically, my game is for Andriod (Java/mobile), but feel free to make your answers generic.


texts: How to keep a square in front of moving camera?

texts:
I'm currently attempting to create a Lens of Truth effect like what we find in Zelda: Ocarina of Time:

  The Lens of Truth allows [the player] to see things that are not normally visible to the naked eye. It can show fake walls and floors, and invisible objects and enemies. (Source: Zelda wiki)

I'm attempting it by using a square frame that is positioned in a scene and an object that should only be visible when viewed through that frame.

The way I tried it is, I defined the square vec4s like this and transform it using the world, view and projection matrix:

vec4 fc[4];
fc[0]=vec4(0,0,0,1);
fc[1]=vec4(1,0,0,1);
fc[2]=vec4(1,1,0,1);
fc[3]=vec4(0,1,0,1);
for(int i=0;i<4;i++){
   fc[i].xyz =  vec4( (worldMat * fc[i]) ).xyz;
   fc[i].w=1.0;
   fc[i] = pass.Proj*(pass.View*fc[i]);
}

In theory I should now get the positions of these 4 points in screen space relative to the position of the object.

Now I should just be able to do this:

if(!inside(inPs.glPosition.xy,fc[0].xy,fc[1].xy,fc[2].xy,fc[3].xy) ){
    discard;
}

to clip the fragment if it is outside the quad of those points (inside is  function by me, the problem is not here), since I basically figure out the screen space coordinates of the square frame.

But if I run the thing the coordinates of the square corners move all over the place.

If I debug the thing by displaying the position of those points on the object, they  don't move at all when I translate the camera, but only when I rotate it, when It should logically be the other way around. Imagine a sheet with a ligthbulb behind it. If you stand still, the position of the lamp on the sheet doesn't change, but when you move around, the light will be on other places of the sheet. I have a feeling, there's something wrong with my thought process here, but I can't figure out why.


texts:
In a 3D flight simulator with a Crimson Skies level of realism (as in, arcade level rather than realistic), how do you determine the movement of an aircraft each game clock tick?

(Crimson Skies is an arcade-like flight simulator: http://youtu.be/OWmYt0LZDnU?t=3m )

I presume the game advances in fixed steps, and each step each moving object moves in a straight line with constant velocity from its current position to the next.

What basic parameters would you need to determine the mass, speed, throttle .etc. Also how would you combine them?


texts:
I made a small game engine with a hierarchy, but have a with problem with applying transform down the hierarchy. I have an object with a parent, and I want the child to rotate around the parent with an offset (the childs localPosition, relative to the parent, and a parent rotation).

For example, I have a parent "Earth", and a child "Moon". The "Earth" rotates, and the "Moon" rotates with a 100, 50 offset.

How do I rotate an object around another object with an angle and an offset?

Each object has:

x / y localPosition
private x / y globalPosition
localRotation
private globalRotation

This is what I have, so far:

float atr = Deg2Rad(parent->GetGlobalRotation());
globalPosition.x = parent->GetGlobalPosition().x + cos(atr) * localPosition.x;
globalPosition.y = parent->GetGlobalPosition().y + sin(atr) * localPosition.y;

but it only only on the x-axis if localPositon is 50, 0


texts: Ambient occlusion of cubes, a specific case

texts:
After much fiddling around and thinking I've got my AO working on my game engine as intended; except one specific case.

When a block is nestled between others on two sides, but the corner block is missing, that corner doesn't get occluded. This isn't too shocking, because there's no logic to do otherwise. However, I can't think of a way to neatly solve that case. If I make it detect a block on each pair of sides, then check for the corner piece, we will end up with lots of broken AO in various scenarios, and that will be a lot of checks to boot.

Here's the table I came up with today which finally solved the missing bits of my AO algorithms:

Click for larger view

The logic in my code (C# MonoGame) essentially enforces this table.

If nobody comes up with anything better, I'll put a series of booleans in the checks for each side, then run through each combination and adjust as though a pair of side block were the corresponding corner block.


texts: How can I accurately lerp Colors over seconds?

texts:
I have some code to lerp between two colors over a set number of seconds, and the lerp works fine:

private Color lerpingColor;

private IEnumerator LerpColorsOverTime(Color startingColor, Color endingColor, float time)
{
    float step = 0.0f;
    while (step < 1.0f)
    {
        step += Time.deltaTime / time;
        yield return new WaitForSecondsRealtime(Time.deltaTime);
        lerpingColor = Color.Lerp(startingColor, endingColor, step);
    }
}

The problem is, the lerp time takes longer than the time I provide in my parameter.  For example, LerpColorsOverTime(Color.white, Color.black, 5.0f); takes over 8 seconds to lerp.

My best guess is that I am being very inefficient in the way I am lerping.  I tried accounting for the calculation time, but it does not seem to work.  In the particular case shown, it is because calculationTime is always 0, since the code to update the time is never run between my Time.time checks.  I tried various approaches, with this being my best:

private Color lerpingColor;

private IEnumerator LerpColorsOverTime(Color startingColor, Color endingColor, float time)
{
    float calculationTime = Time.time;
    float step = 0.0f;
    while (step < 1.0f)
    {
        step += Time.deltaTime / time;
        calculationTime = Time.time - calculationTime;
        yield return new WaitForSecondsRealtime(Time.deltaTime - calculationTime);
        calculationTime = Time.time;
        lerpingColor = Color.Lerp(startingColor, endingColor, step);
    }
}

I also tried other variations of Time.time, such as DateTime.Now.Miliseconds / 1000.0f and Time.realtimeSinceStartup, but they failed as well.

How can I make this code efficient enough to run in the expected time, or make some sort of change with the seemingly same effect?


texts: Matrix interpolation for animation blending

texts:
I use the XNA Animation Component library to perform blending between animations. It uses spherical linear interpolation between matrices.

In most cases this works without problems. However, I have one model where all of the animations are blended wrong. Weird rotation and warping of the model occurs.

I was told by a math expert that the problem may lie in the method that does the matrix interpolation. He said:
"The right way to do it would be to decompose A=UP (polar decomposition), obtain quaternion from U and lerp/slerp it, while interpolating P component-wise.
I'm not sure why the original author refrained from implementing the polar decomposition as its implementation is straightforward and easy."

I have included the code below.

I need some help in making the recommended changes. I am an expert in C# but know almost nothing about matrix interpolation.

private static Quaternion qStart, qEnd, qResult;
private static Vector3 curTrans, nextTrans, lerpedTrans;
private static Vector3 curScale, nextScale, lerpedScale;
private static Matrix startRotation, endRotation;
private static Matrix returnMatrix;

public static void SlerpMatrix(
        ref Matrix start,
        ref Matrix end,
        float slerpAmount,
        out Matrix result)
    {
        if (start == end)
        {
            result = start;
            return;
        }
        // Get rotation components and interpolate (not completely accurate but I don't want
        // to get into polar decomposition and this seems smooth enough)
        Quaternion.CreateFromRotationMatrix(ref start, out qStart);
        Quaternion.CreateFromRotationMatrix(ref end, out qEnd);
        Quaternion.Lerp(ref qStart, ref qEnd, slerpAmount, out qResult);

        // Get final translation components
        curTrans.X = start.M41;
        curTrans.Y = start.M42;
        curTrans.Z = start.M43;
        nextTrans.X = end.M41;
        nextTrans.Y = end.M42;
        nextTrans.Z = end.M43;
        Vector3.Lerp(ref curTrans, ref nextTrans, slerpAmount, out lerpedTrans);

        // Get final scale component
        Matrix.CreateFromQuaternion(ref qStart, out startRotation);
        Matrix.CreateFromQuaternion(ref qEnd, out endRotation);
        curScale.X = start.M11 - startRotation.M11;
        curScale.Y = start.M22 - startRotation.M22;
        curScale.Z = start.M33 - startRotation.M33;
        nextScale.X = end.M11 - endRotation.M11;
        nextScale.Y = end.M22 - endRotation.M22;
        nextScale.Z = end.M33 - endRotation.M33;
        Vector3.Lerp(ref curScale, ref nextScale, slerpAmount, out lerpedScale);

        // Create the rotation matrix from the slerped quaternions
        Matrix.CreateFromQuaternion(ref qResult, out result);

        // Set the translation
        result.M41 = lerpedTrans.X;
        result.M42 = lerpedTrans.Y;
        result.M43 = lerpedTrans.Z;

        // Add the lerped scale component
        result.M11 += lerpedScale.X;
        result.M22 += lerpedScale.Y;
        result.M33 += lerpedScale.Z;
    }


texts:
I'm currently developing a small game, that includes spell casting.
My class structure looks like this:

AbstractSpell

AbstractDamageSpell

AbstractClickableSpell

AbstractClickableDamageSpell

"Clickable" means that the user has to hit a key followed by a mouse click. Some spells don't need that extra mouse click (like Windwalk). As you can see, AbstractDamageSpell and AbstractClickableDamageSpell have the same properties and methods.
Is there a better way of extending these classes? Any hints in general?


texts: Unity AI issue with recalculating NavMesh at runtime

texts:
I am using Unity NavMesh to control my units.
I am running into an Issue when updating Navmesh at runtime, It seems agents re-calculate their path whenever it is modified, which makes sense, but it causes this line (check if unit is on last corner) to return an IndexOutOfBounds error:
agent.steeringTarget == agent.path.corners[agent.path.corners.Length - 1]

I guess something is happening while re-calculating path that might mess with this for 1 frame. I solved this by putting a try/catch around it, but is there some better way I can manage this so I don't get the error at all?


texts: Swapping out Vertex Buffer Necessary for Terrain LOD?

texts:
I am using Directx 11 to try and implement terrain level-of-detail.

I am trying the idea represented in this tutorial:
http://www.rastertek.com/tertut18.html

Which is split your terrain into nodes, and render different quality nodes depending on how far away they are from you.

Each of my nodes has its own vertex buffer (bad idea?), however I am trying to map/unmap when I swap out a particular node for its higher quality version.  I noticed that unless my vertex buffer is the size of the high quality version, then surrounding nodes gets affected, I believe this is to be expected since I am essentially overwriting memory in the vertex buffers of the other nodes.  So is the only way to go about map/umap is to make each node have the space for the high quality terrain?

If so, then I can't do map/unmap because I run out of memory.  What's another approach then?  Making a new vertex buffer with the desired size whenever I swap?  Won't this be too slow?


texts: What is the difference between a tech tree and crafting?

texts: Are tech trees and crafting the same thing, except the mechanism to attain them?  What the real difference between the two?


texts:
I am starting to learn OpenGL with FreeGLUT using the Superbible and the knowledge I have from my elementary graphics to brush up on my skills.

To get more from this experience I want to integrate a GUI to overwrite the one FreeGLUT uses, now my question is this: is this thing possible and what library should I use?

Some characteristics for the library:

Open source
Multi-platform (Linux and Windows)
C/C++

If you have any other recommendations please feel free to post them along with your answers for my problem.


texts: Unity 5 - Time Remaining displaying in scene but not in Game

texts:
I'm currently learning game development in Unity from this course on Lynda.com. Currently I'm trying to displaying the time remaining in the game after it has been set to 5 minutes initially. When I look at the scene, I can see the text for the timer displayed in the top left corner of the canvas, but when I run the game, I'm not seeing it at all.

I made a script for a game manager which is derived from a Singleton class. The game manager contains a private variable (and an accessor method) for the time remaining. I have another script that accesses the value for the time remaining and displays it on screen. In the Unity editor, I  added a UI game object for the text box and then added the text box to the GUI representation of the timer label attribute. It seems like everything should be working but since  I'm still very new to this, I'm probably missing something simple. Here is the code for both scripts:

GameManager.cs

public class GameManager : Singleton<GameManager> {
    private float _timeRemaining;

    public float TimeRemaining
    {
        get { return _timeRemaining; }
        set { _timeRemaining = value; }
    }

    private float maxTime = 5 * 60; // In seconds.

    // Use this for initialization
    void Start () {
        TimeRemaining = maxTime;
    }
    // Update is called once per frame
    void Update () {
        TimeRemaining -= Time.deltaTime;
        if(TimeRemaining <= 0)
        {
            //Now Deprecated
            //Application.LoadLevel(Application.loadedLevel);
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
            TimeRemaining = maxTime;
        }
    }
}

UpdateUI.cs

public class UpdateUI : MonoBehaviour {

    [SerializeField]
    private Text timerLabel;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        timerLabel.text = FormatTime(GameManager.Instance.TimeRemaining);
    }

    private string FormatTime(float timeInSeconds)
    {
        return string.Format("{0}:{1:00}", Mathf.FloorToInt(timeInSeconds / 60), Mathf.FloorToInt(timeInSeconds % 60));
    }
}

EDIT:

Canvas Settings in the inspector

Image of the Time Remaining displayed in the scene


texts: Libgdx Scene2D second screen animating and accept input while still loading

texts:
I'm currently developing an app Scene2D that involves a small number of screen switches.  I am having a problem that after calling set screen there appears to be a pause of a second or two (I think it's the non UI logic is being performed in the new screen constructor to aid setting up UI actors), which is fine.  But during that second pause.  It appears my second screen is already running in the background but not being rendered. I think this is happening because of two problems:

Animations and Actions that are supposed to begin when the second screen loads are already one or two seconds in progress by the time the second screen loads.
During the pause before the second screen loads, the first screen is still rendered in freeze frame, but any user input is queued and processed in the second screen after it renders! Meaning that the user is effectively clicking on things that are not yet rendered which can cause some problems for their experience.

I already am setting the input processor in the show method but it show appears to be called before the screen is actually visible and rendering frames.

Is there something I have misunderstood about the life cycle? Or common pitfalls I may have fallen into?  Only a problem on Android, Desktop is fine but possibly only because the loading times are too fast to notice either problem.


texts: Blocking Physics Raycasts with Unity's 4.6 UI?

texts:
I use raycasts to determine hit objects and object selection in our game. I want these to be blocked by UI elements. Before I had a crude form of that where I just excluded rects of the screen, though with a non-rectangle shaped UI that's pretty difficult.

I want to have physics raycasts NOT go through UI objects, can this be done? My initial thought it adding colliders to the UI objects, though I'm not sure if the colliders will scale with elements based on screen size.

Note: Canvas Group does not apply to physics.raycast


texts: Is there an upgrade path from Asset Store to package manager for TextMesh Pro?

texts:
A little while back I used the Asset Store to install TextMesh Pro after following a tutorial. The version I got was 1.2.2.  I have since then had it pointed out to me that the newest version is now available through the Package Manager. The version there is 1.2.3.

I have tried changing which version i am using but have had no luck. I did quite a bit of work with adding texts and do not want to redo all of it. Simply deleting the package from my app, and then installing it from the package manager does not work. All text scripts end up not linked.

Is there anything I can do to switch my project over from the app store to the package manager?


texts: Applying Animation to specific parts of a humanoid model

texts:
I have imported a humanoid character from AutoDesk Character Generator into Unity. Once you specify that you want the character for Unity, a humanoid skeleton in integrated, in order to use MecAnim.

I also have a plug-in that applies the user's motion data to this character and animates it. Because the plug-in is free and open-source, I am trying to apply the motion data to different MecAnim bones, to see if I can do so.

By the way, by "motion data" I am referring to 2 arrays: one that contains positions and one that contains orientations of a number of joints and bones. So, I can access these Vector3 and Quaternion data...

Is it enough to just apply, for example, the left foot's orientations to the right foot, or do I need to also do it with positions, in order to inter-change the animations/motions/movements of these 2 limbs?

This is the method I have written so far:

public void swapLimbsPosRot(Vector3[] positionsArray, Quaternion[] rotationsArray)
{
            Vector3 tempPos = positionsArray[16];
            positionsArray[16] = positionsArray[20];
            positionsArray[20] = tempPos;

            Quaternion tempRot = rotationsArray[16];
            rotationsArray[16] = rotationsArray[20];
            rotationsArray[20] = tempRot;
}

But it doesn't work, because when I apply it to my array of transforms before updating, severe jitters show there is a fighting going on between MecAnim and my motion capture device' incoming motion data, but for now I am just wondering:

If you wanted to swap the animations/movements/motions of 2 similar MecAnim parts, what would you do? What would you swap? How would you go about it?

p.s. Of course, first I tried swapping the mecanim bones (right & left feet) but that turned out silly, as the "actual" feet of my MecAnim character had been swapped!

Some code, showing how the swapping and updating are done now, hoping someone could please help me find the cause of the jitters.

    void Update()
    {
        Vector3[] latestPositions;
        Quaternion[] latestOrientations;

        if (mvnActors.getLatestPose(out latestPositions, out latestOrientations))
        {
                // If this variable is set to true, then do the swapping.
                if (swapLimbs)
                {
                    swapLimbsPosRot(latestOrientations);
                }

                // Update both the pose and the model, using the delayed data.
                updateMvnActor(currentPose, latestPositions, latestOrientations);
                updateModel(currentPose, targetModel);
        }
    }

    /// Swap the rotations of different mimicking limbs; e.g. LeftHand = 16 & RightHand = 20
    public void swapLimbsPosRot(Quaternion[] rotationsArray)
    {
        float tempRotY = rotationsArray[16].y;
        rotationsArray[16].y = rotationsArray[20].y;
        rotationsArray[20].y = tempRotY;

        float tempRotZ = rotationsArray[16].z;
        rotationsArray[16].z = rotationsArray[20].z;
        rotationsArray[20].z = tempRotZ;
    }

The motion data that comes in is always the latest positions and orientations from the device, so Update modify them and then apply them to the character to animate it. So, for example, in my Update, I get the latest pose (i.e. the latest positions and orientations) and then I swap the orientations of left and right hands, but the jitters are severe...


texts: Using a remote highScore storage/retrieval system. I have no idea on how to implement

texts:
The system is something like this:

  highScoreDB || Validator || PlayerSession
  ---Database---||--Script---||----Game------

PlayerSession is an active game session, on finalizing a match, the game checks if highScoreDB is full, if full; compare the session's score with the lowest DB score and replace if its greater; if not full then just add the session score normally. Upon score submission, the game also sends some other data for the Validator.

The Validator checks if the score is legit by processing the extra data(match duration, key entities interacted with, etc); if the score is valid, then score is applied successfully; otherwise, it's rejected and the sent data is logged elsewhere(not relevant ATM).

The highScoreDB simply stores the data for retrieval by players.

Now I do not know how to make and where to stick the scripts as well as how to appropriately store the data. I'd appreciate any assistance on this matter.


texts: Unity reflections going white with camera movement

texts:
Please refer to this video to understand the issue I am facing.

With camera movement, there is a strong white reflection that appears over the complete model. What settings do I need to change to fix this ?


texts: What are the tools, programming languages and development processes of AAA games?

texts:
Only thing I am able to find about "big" games like ac, hl, bf, cod is engine used to run the game. But I am interested in what software development methodology, programming and scripting languages were used. As well as tools for creating models, music, animations and other media. Further, were the team team organisations and so on for a certain game (or game series).
Is this information even available to the public?


texts: How to make a cell shader like BOTW in Unity?

texts:
It seems most cell shader tutorials focus on individual shaders for materials, but the effect used in BOTW seems to be more like a filter, that is applied to everything.
I've researched multiple examples that have been done in UE4 like here and here but nothing in Unity.
How would I apply something like this in Unity?


texts: How to properly write "stick to surface" character logic that handles unexpected large time deltas?

texts:
I've been trying to wrap my head around this issue: in a 2D platformer game (but this may as well apply to 3D games) I want the character to "stick" to the surface that it's moving along and at the same time maintain the same velocity no matter the incline/decline of the current surface. Also, if my character's speed is 1 unit/sec and the current delta time is 0.25, I want it to travel exactly 0.25 units no matter the "shape" of the surface met along the way during the frame.

Naively, I started with this base logic (warning, pseudo-code incoming):

vel += acceleration * timeDelta;
movementDelta = vel * timeDelta;

hit = raycast(pos, downward);

if (hit)
{
    vectorAlongSurface = hit.normal * fancyLinearAlgebra;
    pos += vectorAlongSurface.Normalized * movementDelta.Magnitude;
}
else
{
    pos += movementDelta;
}

But this is correct only if my character moves along the same surface normal for the whole frame and it breaks pretty badly if during the frame the surface has different normals along the way. This can give the feeling that the speed at which the character is moving is inconsistent. To give you an example:

While I do expect answers like "just don't make your terrain like that" I'm also considering situations where my game might experience an unexpected lag and have to deal with a large time delta that might push the character through different surface normals during the same frame.

Any advice on how to properly handle this would be much appreciated. I was thinking about somehow tracing all the changes of surface inclination from the character's position to the "naive raycast hit" point, but that seems to be quite expensive, especially considering that all the enemy characters would have to do the same. There must be some simple solution to this that I'm not seeing. Or maybe there's a way to make the inconsistency of speed in the given example less noticeable/irrelevant?

Thank you guys.


texts: Started game development no idea of computer graphics. Should I learn tools or concepts?

texts:
I am in 6th semester of my Computer science bachelor degree program, Working as Intern in a start up company. I started game development using AndEngine, things are going good because I have good hold on OOP and Java.

But I don't have any experience in OpenGL programming and neither studied a course of computer graphics. I want to develop 3D games and there are tools available like Unity3d etc.

My question is should I master tools or take online lectures of computer graphics to get started on basics. I want to continue game development as my profession. So what should I do? start learning from scratch or Learn already built tools and just dive into development?

I see successful designers with no background of academic study, just did a photoshop course and now they are in the softwarehouse and making websites, sprites etc.


texts:
I have a character with a camera behind him. The head of the character rotates with the LookAt function on the character's head rig.
The LookAt is done towards targets that may be to the right or left of the entire body of the transform character.
So I want to detect when the head rotates clockwise with respect to the controller body and when it rotates counterclockwise. How can I do this?


texts: Key released, multiple Keys, how to go around ncurses limitations?

texts:
I have been trying to make a small game in the terminal in C++ using ncurses.

After searching around for some time, I came to realize that ncurses is pretty limiting as far as keyboard inputs are concerned :

How to separate keyPressed and keyReleased events?
How to deal with multiple keys pressed at the same time?

Do you know of any solution to go around those limitations?

To answer someone's comment, in other languages I would use a keyListener to detect if a key has been pressed or released, and keep each pressed key in an array that I can use later :

array pressedKeys[];

keyPressed(event)
{
    pressedKeys.add(event.getKey());
}

keyReleased(event)
{
    pressedKeys.remove(event.getKey());
}

... // Later in update()
    if keyPressed.contains("up")
        goUp();

This does not seem possible in ncurses as it just gets the last pressed character with getch(), and pressed means keydown then keyup, which does not allow to keep track of the different keys pressed at the moment.


texts: Should I refer to browser-based games as HTML5 games or Javascript games?

texts:
First of all, I know that there are alternatives to both HTML5 and Javascript, but I worded the question so generally ("browser-based") because if I had said "HTML5" or "Javascript" games that would already imply an answer to the question.

When writing wiki posts or discussing, I usually call these games "HTML5/Javascript" games. They are written in Javascript, using the new HTML5 technology. What is the proper way to call them: HTML5 or Javascript games? I see that most people opt for HTML5, why?


texts: Detecting collision of two sprites that can rotate

texts:
I have a problem with collision detection in a 2D Java game.

Normally, what I would do is create a getBounds() method for an object that can collide with other objects. This method would return a new Rectangle(x,y,width,height), where x and y are the coordinates for the top-left corner of the sprite, and width and height are the width and height of the sprite.

But in the game I'm currently working on, there is a "tank" controlled by the user. The sprite of this tank rotates as long as the player holds one of the left or right arrow buttons. In other words, it can rotate to any angle. The tank's sprite is a rectangle.

So I can't simply do what I always do in this case.

How can I detect collision with this kind of sprite?
Thanks


texts: XNA 4.0 - Why does using a RenderTarget2d cause transparency on models?

texts:
I have been working through Riemers ShadowMap tutorial and everything was going well until the section on drawing to a separate rendertarget. I am using a different model and quads but I assumed the process would still work.

If I draw the scene directly to the back buffer I get:

When I draw it first to a RenderTarget2D and THEN to the screen, I get this weird transparent effect only on the model, the textured primitives below are still rendered fine:

The RenderTarget is defined:

PresentationParameters pp = device.PresentationParameters;
renderTarget = new RenderTarget2D(device, pp.BackBufferWidth,
           pp.BackBufferHeight, true, device.DisplayMode.Format, DepthFormat.Depth24);

And it is used in this way:

protected override void Draw(GameTime gameTime)
{
    device.SetRenderTarget(renderTarget);

    device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);

    DrawScene("Simplest");

    device.SetRenderTarget(null);
    shadowMap = (Texture2D)renderTarget;

    device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0);
    using (SpriteBatch sb = new SpriteBatch(device))
    {
        sb.Begin();
        sb.Draw(shadowMap, new Vector2(0, 0), null, Color.White, 0, new Vector2(0, 0), 1.0f, SpriteEffects.None, 1);
        sb.End();

    }
    base.Draw(gameTime);
}

What gives?

Edit 1:
I resolved the transparency effect by resetting:

device.DepthStencilState = DepthStencilState.Default;
device.BlendState = BlendState.Opaque;

But now the model has a purple tint on the side away from the light. Something to do with my Shader code I presume.

Edit 2:
Turns out the purple (blue) colour was a result of the window being cleared to .DarkSlateBlue and the RenderTarget having alpha transparency.
Fixed with:

sb.Begin(SpriteSortMode.Immediate, BlendState.Opaque);


texts: Component messaging system - using integers vs message objects

texts:
I'm currently working on a component based system for my game, and I've decided to use a messaging system to communicate between components. I've read some on the subject and it seems that most people are using message objects that extend on a base message object like so;

MySpecificMessage extends Message

or possibly they just have a single Message object which takes in a string variable that determines what it does, like so;

new Message("positionX:10"); //Plus other variables you might need

But I've also seen some implementations of this using statically defined integers as messages like so;

public static final int MySpecificMessage = 1; //Different numbers for different messages

Basically I'd like to know what the pros and cons are between them, and possibly when you'd use one over the other. Also, if you have any other type of messaging system please do share.


texts:
Is it possible to distort a quad multiplying its vertices by a specific world matrix? See the picture to understand what kind of distortion I need:

Please note, that the quad is in 3d space and I particularly need it's VERTICES to be distorted and NOT to rotate a perspective camera. The quad is laying on a plane with Z=0, all of the quad's vertices have their Z components equal to 0 and they should have their Z component equal to 0 after the transformation.

I know that it can quite easily be done by moving the vertices in a vertex shader, but the reason why I need to distort the quad using a World matrix is because I am rendering hundreds of such quads with a single draw call. Some of them need to be distorted and some dont. So I need a uniform vertex shader for every case and before doing branching in the shader I would like to know if such distortion can be done with a World matrix.


texts: Player object's model starts to shake after some time

texts:
I created a default scene in a new project and imported a model from Unity's asset store and then get this strange behavior of the model starting to shake for no reason after some time after starting the game.

I also have a script to read keyboard input and then apply forces to the model when the player presses some keys but the shaking of the model starts to happen even when the player does absolutely nothing.

I'm really confused and have no idea where to look for a problem and google doesn't seem to have a solution to this either.


texts: Where does Unity save the editor window layouts?

texts:
In every project there are the CurrentLayout.dwlt and CurrentMaximizeLayout.dwlt files, but those, as the name implies, are just the current layouts.

I've been unable to find the general files where it saves all your layouts, in order to copy it to another computer.

Where is it?


texts:
I want to give a border to all the buttons of settings that are enabled in my options menu.

Let's say that the demo mode is enabled, then the according "on" button should have an e.g. red border, while the "off" button hasn't got one. I don't care if the border is visible when you hover over the button (= the "highlighted" color is used) as long as the actual color change for highlighting/pressing the button still works.

So far I've only found the "Outline" effect but it only seems to work on the text component of a button, not the actual button itself. How do you do this in Unity (2017.3.1f1, preferably without using additional assets)?


texts: Blueprint For Switching Between Cameras In The Unreal Engine

texts:
So basically I have a scene in the Unreal Engine which has multiple cameras within it, the cameras are intentionally static as the application should behave more like a viewing gallery than a game. As the application is intended for mobile devices, the idea is that when a person touches the screen of their device, the rendering switches from the present camera to another one to show a different image. I have attempted to implement this action in the level blueprint with the following blueprint design:

Closer up:

Obviously in the scene there are three camera actors which must be switched between with the first camera viewed through being the 1st CameraActor hence the connection of the EventBeginPlay variable to the Set View Target With Blend variable that the 1st camera actor is connected to. When the Play button is pressed, the scene viewed from the first camera is rendered to the screen as desired however when the left mouse button is clicked equating to touch input on mobile devices, the scene does not switch to the second camera and the question is why?


texts: How to determine the end of list has been reached?

texts:
I'm trying to animate my object according to a set of recorded values from kinect skeleton stream by saving the (x,y,z) stream from the skeletal data into a list and then set my objects x and y position from the x,y of the list. However, once the list end has been reached it starts to animate again from the start. I don't want that - I just want the model position to keep going in the positive X direction. Is there any way I can check if end of the list has been reached and to just update the model position in x direction?

Or is there any other way to continue moving my sprite once the points in the list are over... i dont want it to start animating all the way again..

   protected override void Update(GameTime gameTime)
        {

            //position += spriteSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;

            //// TODO: Add your update logic here
            using (StreamReader r = new StreamReader(f))
            {
                string line;
                Viewport view = graphics.GraphicsDevice.Viewport;
                int maxWidth = view.Width;
                int maxHeight = view.Height;

                while((line = r.ReadLine()) != null)
                {

                    string[] temp = line.Split(',');

                    int x = (int) Math.Floor(((float.Parse(temp[0]) * 0.5f) + 0.5f) * maxWidth);
                    int y = (int) Math.Floor(((float.Parse(temp[1]) * -0.5f) + 0.5f) * maxHeight);

                    motion_2.Add(new Point(x, y));
                }

            }

                position.X = motion_2[i].X;
                position.Y = motion_2[i].Y;

            i++;

            a_butterfly_up.Update(gameTime);

            a_butterfly_side.Update(gameTime);

            G_vidPlayer.Play(mossV);

            base.Update(gameTime);
        }


texts:
I'm a newbie. I like to play games, but I'd also like to program them too. I know it's difficult to create a game, but please share the basic info I need to get started creating my first game. What do I need to study to become a game developer? What is
game AI? What is a Game Engine? What are the different types of game engine?


texts: Why this if logic isnot short circuiting?

texts:
I've this script in UNITY to check if the hit RayCastHid2D variable has some gameobject with hole tag or a parent gameobject with hole tag when I Raycast...

if (hit.collider != null && (hit.collider.gameObject.tag == "hole" || (hit.collider.gameObject.transform.parent.gameObject != null && hit.collider.gameObject.transform.parent.tag == "hole")))

Everything is fine until if (hit.collider != null && (hit.collider.gameObject.tag == "hole" ||

but when I enter (hit.collider.gameObject.transform.parent.gameObject != null && hit.collider.gameObject.transform.parent.tag == "hole") it throws a NullReferenceException....

But why?

It supposed to short circuit here hit.collider.gameObject.transform.parent.gameObject != null && if there's no parent gameobject!


texts: Direct3D - Get screen coordinates for printing multiple text elements

texts:
I have a function that I use to print text PrintText(char* text) that stores the text to a vector, which is then displayed if the vector is not empty. I'm trying to figure out how can I correctly print multiple char* to the screen, one under the next?

For example:This is line one.This is line two.

Both of those are stored in separate char* elements in the vector. How can I use Direct3D or C++ to correctly display consecutive char* elements as it is in the above example? As in getting the correct screen coordinates to display the next element?

Code:

void DrawString(char* String, int x, int y, int r, int g, int b, ID3DXFont* ifont)
{
    RECT ShadowPos;
    ShadowPos.left = x + 1;
    ShadowPos.top = y + 1;
    RECT FontPos;
    FontPos.left = x;
    FontPos.top = y;
    ifont->DrawTextA(0, String, strlen(String), &ShadowPos, DT_NOCLIP, D3DCOLOR_ARGB(255, r / 3, g / 3, b / 3));
    ifont->DrawTextA(0, String, strlen(String), &FontPos, DT_NOCLIP, D3DCOLOR_ARGB(255, r, g, b));
}


texts:
i'm developing an editor for a game...

and tonight i have been thinking about implement a visual ai designer...

this is how i think it should be:

What kind of visual components are used in theses tools? (Timers, Counters, Conditionals,...)
About implementation, i'm using C# and xna, how can i save/load this graphs?


texts: Applying a torque to a different centre of mass

texts:
In Unity I have an object with a circle collider attached to it and when I apply a torque to this object's rigidbody2D, it rotates as expected. However, I have now attached a sub-object to this object with a polygon (trigger) collider which I am using to detect when something is in a cone in front of the ship. There is no rigid body (2D or 3D) attached to the child object. The only rigid body on the object is the one I am applying torque to.

However, when I do this, the centre of mass of the ship is moved to the centre of this collider, which produces totally the wrong effect. This happens even if I move this collider to the root node (so both it and the circle collider are attached).

I either need a way of getting the rigid body to ignore the child collider/allow me to set the centre of gravity, or else some other way of detecting objects inside a region.


texts: How do I fix objects "popping" or jittering in physics engine?

texts:
I've got a simple physics engine that solves collisions by simply correcting the position of overlapping bodies (just circles for now) directly, as opposed to just changing the velocity or applying an impulse. Velocity is only changed after impacts are already resolved, or during the integration part.

I've had the problem that in heaps of objects the top objects apply too much pressure (this exists implicitly, there's no pressure modelling in the algorithm) on the objects at the bottom of the heap, which results in them getting pushed through floors, etc.

I wanted to fix this by sorting the objects by their y-coordinate, so the collisions are resolved bottom-up. But now, the engine shows weird popping behavior for objects which should actually be at rest (see gif)

Without just giving you the source code - what could this be?


texts:
I have an object, and i want to interpolate its position between two points over a given time period; but i dont want it to be a linear interpolation. I'm not sure if i'm phrasing this right.

vector posA; // Where we start
vector posB; // Where we end
float timeI; // An interval from 0 - 1

normally i would just do it linearly

vector currentPos = posA  + (posB - posA) * timeI

but i want the object to either:

a) move faster at the start and slower at the end
b) move slower at the start and faster at the end

Can anybody point me in the right direction


texts:
I was able to make a full screen blur with the depth of field post process which I want to use for the background both my pause menus and my in game HUD. The issue is that when I want to use it for my in game UI it needs to only be rendered under the HUD and not the entire screen. Is there any way the I can mask the post process to a UMG widget for simplicity?

The other solution that I thought of was to create a material and mask it off in the material. The problem is that PostProcessInput0 already has the blur applied and I can't use the SceneColor any more, so I don't have a way to get the original texture without the blur. Is there any way to do this?

Cheers.


texts: Why doesn't Unity keep keydown states between scenes, and how can I change that?

texts:
So basically, when my scene in Unity changes and I'm holding down, say, Right or Left, when the scene resets, my player (and Unity) doesn't even recognize that I'm still holding that button, until I lift my finger and put it back.

Any thoughts?

Sorry for any broken English or anything, I'm running off two hours of sleep.


texts:
My scene has a simple cube, and a camera built with the lookAt function (I'm using OpenGL). The scene renders fine, and I'm sure I have my model/view/projection matrices set up correctly.

Now I'm trying to implement arcball rotation for my camera, but I'm having some trouble. I've got it down to calculating the angle/axis rotation for a virtual sphere in normalized screen coordinates. That means when I move my mouse left to right, I get an angle around the Y axis... and moving my mouse up/down will get me an angle about X.

I'm not sure where to go from here -- what do I need to do with my axis so I can apply the angle to simulate camera rotation about its viewpoint?

If I try directly applying the axis/angle rotation the camera/view transform I get what you'd expect. The view is rotated about the world axes which the mouse moving over the virtual sphere on the screen corresponds to. So if I move the mouse up/down the view rotates about the world's X axis (what I get reminds me of a first-person view)... but this isn't what I want.

I think I need the axis I get to be transformed so it passes through the camera viewpoint and is oriented correct in reference to the camera... but I don't know if that's right or how to do that.


texts: What is a good path-finding algorithm when a target is moving?

texts:
I've been looking for a path-finding algorithm for a moving target.
If there are no obstacles in proximity Seek behaviour would be good.
However, A* or some other path-findings are needed when obstacles are on the way to the moving target.

The problem I'm facing now is that calculating a path using A* seems not efficient for a moving target.
so I want to know if there are some good or preferred ways to solve this problem.

The image below shows some basic background of the problem.
The red arrow shows the direction my Seek behavior calculates.
But I want the "Chaser" to take the green direction instead.

Thanks in advance.


texts: Proper way to encapsulate a Shader into different modules

texts:
I am planning to build a Shader system which can be accessed through different components/modules in C++. Each component has its own functionality like transform-relevated stuff (handle the MVP matrix, ...), texture handler, light calculation, etc...

So here's an example:

I would like to display an object which has a texture and a toon shading material applied and it should be moveable.

So I could write ONE shading program that handles all 3 functionalities and they are accessed through 3 different components (texture-handler, toon-shading, transform).

This means I have to take care of feeding a GLSL shader with different uniforms/attributes. This implies to know all necessary uniform locations and attribute locations, that the GLSL shader owns. And it would also necessary to provide different algorithms to calculate the value for each input variable. Similar functions would be grouped together in one component.

A possible way would be, to wrap all shaders in a own definition file written in JSON/XML and parse that file in C++ to get all input members and create and compile the resulting GLSL. But maybe there is another way that is not so complex?

So I'm searching for a way to build a system like that, but I'm not sure yet which is the best approach.


texts: Why when getting the waypoints objects in script the order in the array is not the same as in the hierarchy?

texts:
At the top

public GameObject[] waypoints;

In Start

void Start()
    {
        waypoints = GameObject.FindGameObjectsWithTag("Waypoint");
    }

In the Hierarchy i have 5 Spheres:
In this order:

But when using a break point i see in the variable waypoints:

Why when getting the waypoints in the script they are not in the same order ?


texts: 1 Texture For Multiple Models, Or 1 Model Using Different Textures For Each

texts:
I'm creating some voxel flowers that are exactly the same, just different colours.  Is it better to create 5 models and use 1 texture that has the 5 different colours, or create 1 model and use 5 different textures for each colour?

Am curious as to which is more efficient in regards to performance, as there could be quite a few flowers on screen.

I'm playing around with MagicaVoxel and Unity.


texts:
I'm using Mirror as UNet is deprecated.
How can I get the local player GameObject in my code?


texts: What are some non-obvious topics to learn for game development?

texts:
I've been writing games for around 10 years now (from QBasic to C# and everything in-between). I need to start stretching my skills into different areas. What are other, surprising topics I should read up on?

Expected topics would include the usual suspects:

Programming language of your choice
Scripting language
Source control
Project management (or Agile)
Graphics API
Maybe some AI (A* path-finding?)
Physics (projectile physics)
Unit testing (automated testing)

I'm looking for more esoteric topics; things that you don't expect to need to know, but if you do know them, they make a difference. This could include things like:

Art skills (drawing, lighting, colouring, layout, etc.)
Natural language processing
The physics of sound (sound-waves, doppler effect, etc.)

Personally, I feel that having technical art skills (eg. can make decent art-work if you can only come up with ideas; or, following Photoshop/GIMP tutorials) was the most beneficial for me.

This is not intended to be an open-ended question; I'm looking for specific skills that helped you and you expect will continue to benefit you in the short- and long-term.


texts: How to run a long task without freezing my game?

texts:
I have a component that is in charge of generating a level at runtime, and this is an operation that takes quite some time. As a consequence, I experience a hang when this operation is executed (when the scene is loaded).

This problem can be summarized to the fact that SceneManager.LoadSceneAsync in fact is not async at all in its second phase, when it initializes all the objects.

There are three approaches I have searched for and thought about:

Slicing the operation as explained on this video:

This is non-trivial, I would have to rewrite chunks of code for the sake of avoiding a few seconds hiccup at scene load. Furthermore, the person explaining in the video says that they changed Unity source code which I don't have access to.

Running the operation in a background thread:

This is definitely interesting, it would require minimal changes. The only problem is that at some point I have to create Unity objects (GameObject, Mesh etc) and this is not possible when outside Unity thread.

I was thinking more or less of this code to be run on the background thread:

class Builder
{
    public void Build()
    {
        // 1. do something long

        // 2. create Unity object with result from #1
        // something like that
        // await RunInUnitySynchronizationContext(() => new GameObject(...))

        // 3. do extra stuff on the result of #2
    }
}

The thing is I have no idea at all on how that second step should be written, if possible at all.

Use a non-animated Loading screen and wait for it to finish:

This is the simplest and effectively does away with the problem by 'just' hiding it.

Question:

What's an effective approach to solve this problem?


texts: ScriptableObjects events execution order?

texts:
Given the code:
[CreateAssetMenu(fileName = "newGameManagerInstance", menuName = "Game/Game Manager Instance")]
public class GameManagerSO : ScriptableObject
{
    private GameManager instance;

    public GameManager Instance { get { return instance; } set { instance = value; } }

    private void Awake()
    {
        Debug.Log("1");
    }

    private void OnEnable()
    {
        Debug.Log("2");
    }

    private void OnDisable()
    {
        Debug.Log("3");
    }

    private void OnDestroy()
    {
        Debug.Log("4");
    }
}

I have two questions:

Why the output in console when I enter play mode is "3" and then "2"? Shouldn't OnDisable be executed after OnEnable?

I'm using this scriptable object to hold an object reference only (I don't have the need to serialize the object, it's just a handy way I found to pass that reference through scenes without committing to singletons); can I code all initialization code for the object in OnEnable method? Can I assume it will always execute before any MonoBehaviour read it?

Also


texts: How to verify if the client files are the same as the server files?

texts:
In a client-server game architecture, what are the possible ways to verify that the client has not modified things like gfx assets or client side scripts?

Obviously no solution is perfect, but I would love to hear some ideas.

I am thinking something like an hash on all the files in the resources directory. Does that sound feasible?


texts: I'm creating a game with lots of instances. On each iteration of the game loop, I only want to deal with the ones that are near the player. Currently, I do this by constructing a list of all the existing instances within a rectangle surrounding the player every few iterations. However, this takes far too long. How could I speed it up?


texts:
How would client-side prediction for movement work? From how I understand it, the player inputs "Move Forward" and the character on the player's computer instantly starts to move forward. It also sends the input to the server along with a framestamp, say frame 100. The input arrives at the server on frame 110. The server knows that the player started movement on frame 100 so the character would've moved forward for 10 frames. On the server, the character moves forward 10 frame's worth then the result is sent. The official state is received and since it nearly matches up with the player's gamestate, the transition is smooth.

My concern is about how this would look on other people's computers who don't have knowledge of the input - only gamestate. How is 10 frame's worth of movement smoothed out when the other computer hasn't started moving the character forward 10 frames earlier?


texts: How can I determine the contact point of a collision?

texts:
I have two Farseer bodies. A static rectangle and a dynamic ball that is flying around. I want to determine where the ball touched the rectangle. I need the exact coordinates of the contact point.

How can I do that? Is there a way to determine the contact point?

 bool BlueRectangle_OnCollision(Fixture fixtureA, Fixture fixtureB, FarseerPhysics.Dynamics.Contacts.Contact contact)
   {
       if (fixtureB.Body == RedBall)
       {
          Vector2 normal;
          FixedArray2<Vector2> worldPoints;
          contact.GetWorldManifold(out normal, out worldPoints);

          if(contact.Manifold.PointCount >= 1)
          {
            Vector2 contactPoint = worldPoints[0];
          }
        }

        return true;
    }

It works with the following code.