texts: Moving several rectangles by dragging a single one in Monogame

texts:
I am trying to make a simple card game in which the hand of cards is displayed on a row to the player on screen, and by dragging a single card, all others should move accordingly, with the same speed as the mouse on the X axis only. This is my current code:

public void HandleInput(GameTime gameTime)
{
    _previousMouseState = _currentMouseState;
    _currentMouseState = Mouse.GetState();

    if (_currentMouseState.LeftButton == ButtonState.Released)
    {
        _dragged = false;
    }

    _mouseDown = _currentMouseState.LeftButton == ButtonState.Pressed
        && _previousMouseState.LeftButton == ButtonState.Released;
}

public void Update(GameTime gameTime)
{
    foreach (Card card in _players[0].Cards)
    {
        if (_mouseDown)
        {
            if (card.Area.Contains(_currentMouseState.Position))
            {
                _dragged = true;
            }

            if (_dragged)
            {
                int movementDelta = _previousMouseState.X - _currentMouseState.X;
                Debug.WriteLine("previousX: " + _previousMouseState.X
                    + " currentX: " + _currentMouseState.X);

                _players[0].Cards.Select(c =>
                {
                    Rectangle area = c.Area;
                    area.Offset(movementDelta, 0);
                    c.Area = area;
                    return c;
                }).ToList();
            }
        }
        card.Update(gameTime);
    }
}

HandleInput runs before Update on the game loop. I have implemented a screen manager, but I don't think that is the issue, here. The thing with this code is that the mouse previous X, most of the time, is exactly equal to the current X, and movement is erratic at best (meaning that 90% of the time nothing happens, and the other 10% all cards move on a huge, uncontrollable leap). I have also tried using gameTime in the calculations for the movement delta, but that doesn't work, either. I'm not sure in what other way could I could tackle this (dabbled a bit on using Vector2, but unsuccessfully). I'm kind of noobish to Monogame, but I understand that polling is preferred to event handling here.


texts: Does friction only apply in opposite direction of motion?

texts:
Let's say an object is sliding on a slope and is the object has a velocity of (0,0,5).
The friction would be acting in the opposite direction of motiong, being (0,0,-1).
However, gravity is also affecting the object on the slope. The gravity is doing an impulse of (-1,-1,0) every frame in the direction of the slope tangent. Should the object also experience friction in the direction of (1,1,0)? Or would it only experience friction in the direction of (0,0,-1)?
I find the notion that friction always opposes the direction of motion strange, because this means that when an object is sliding downwards slightly on a slope, but not much, due to friction acting in opposite direction of gravity, when you add an impulse in a perpendicular direction, suddenly the object will be sliding downwards much more because friction is no longer resisting gravity. Is that correct?


texts: Setting up a camera to make the world look large

texts:
I am attempting to configure my camera to give the impression of a normal sized player in a giant room. Since units are arbitrary, I figured this should be possible (despite the fact that the room is technically 24x24m big and I want it to feel more like a hangar).

I have tried tweaking down the FOV (to about 40 degrees) which has helped some, but I can't shake the feeling that I am a tiny person in a normal sized room rather than a normal sized person in a giant room.

What about the way the scene is being rendered is giving away this to my eye. Or is it just a lack of reference points?

I am using Unreal Engine if that affects the answer.


texts:
Alright, I have a bit of a confession to make: I accidentally posted this question in the wrong place: Stack Overflow. Whoops. Anyway, here's my problem. Sorry if you've seen this before. Here's the original post.

I've been struggling with this issue for a few days now. Windows builds for my game work fine, but when I build it to Android, it loads, shows the "made with Unity" screen, then fades to black. Now, I know the next scene (an animated logo) is running because it is playing the audio in real time. However, nothing in the scene is visible. Then, the UI for the in-game loading screen appears. Normally, the game would then load, and it does, but again, the camera thinks there are no sprites in the scene. I can still play the game, and the audio sounds just normal, but I can't see. Then, when I die, the game-over UI appears, and I can use it as normal. The shop-menu works absolutely fine, but the game itself does not. It's as if Unity decided that all SpriteRenderers in the game just didn't exist, and that the camera background color was now black. There are no scripts or animations causing this directly, as it does work in editor and on a PC build. The game also works fine using Unity remote, but the build has the issue. I also made sure that none of the textures were too large for Android (to the point where not one of them is larger than 256x256, which looks terrible but proves a point).

Now, before anyone asks, yes, I have seen the other question on this topic, and no, sadly, it did not help. My camera is set to "solid color", not "don't clear." I tried "skybox" too, just to be safe. I have also tried disabling post-processing, hoping that Android was just unable to handle it. It did nothing. I have even tried entirely disabling all of the sprites in the scene, but even then, the background is still black, indicating that the camera is still not playing nice. Also, here is a screenshot showing the quality settings for the Android build.


texts: Error while reading TGA file and doing Texture Cube map

texts:
In my program, i read a TGA file with a function like this:

char* LoadTGA(char* filename, int* width, int* height, int* bpp);

As you can see, this function: return a char array of image data (without TGA file header, from the first pixel row of image to the last pixel row of image), width of TGA image, height of TGA image, and bits per pixel of image data. The part of code that read image data is this:

    int w = pHeader->width; //width of image
    int h = pHeader->height;  // height of image
    int rowSize = w * pHeader->bits / 8;   //The bit is bits per pixel
    bool bInverted = ( (pHeader->descriptor & (1 << 5)) != 0 );  //My TGA image is not inverted so bInverted is false.
    for ( int i = 0; i < h; i ++ )
    {
        char * pSrcRow = pSrc +
            ( bInverted ? ( h - i - 1 ) * rowSize : i * rowSize );
        if ( pHeader->bits == 24 )
        {
           for ( int j = 0; j < w; j ++ )
           {
               *pDest ++ = pSrcRow[2];
               *pDest ++ = pSrcRow[1];
               *pDest ++ = pSrcRow[0];
               pSrcRow += 3;
        }
    }
}

As this code show, for my TGA image, which have bits per pixel (bpp) equals to 24, not inverted, the return char array will be from the first pixel row of image to the last pixel row of image.

I read a image of 512 x 384 pixels like this image below:

I use this image for texture cube so i read 6 parts of this image in following function:

bool Texture::SplitTextureCube(int i, char* des)
{
int l, m, size = width/4;
int aTopLeft[][2] = {{size*2, size}, {0, size}, {size, 0}, {size, size*2}, {size, size}, {size*3, size}};
int rowSize = height * bpp / 8;
for (int j = 0; j < size; j++ ) //height
{
    char * pSrcRow = imageData + (aTopLeft[i][2] + j) * rowSize + aTopLeft[i][0];
    if ( bpp == 24 )
    {
        for ( int k = 0; k < size; k ++ )   //width
        {
            *des ++ = pSrcRow[0];
            *des ++ = pSrcRow[1];
            *des ++ = pSrcRow[2];
            pSrcRow += 3;
        }
    }
    else
    {
        for ( int k = 0; k < size; k ++ )
        {
            *des ++ = pSrcRow[m + 0];
            *des ++ = pSrcRow[m + 1];
            *des ++ = pSrcRow[m + 2];
            *des ++ = pSrcRow[m + 3];
            pSrcRow += 4;
        }
    }
}
return true;
}

This function is called as below:

 char *face = new char[width/4 * height/3 * bpp/8];
    glGenTextures(1, &textureId);
    glBindTexture(GL_TEXTURE_CUBE_MAP, textureId);
    for (int i=0; i<6; i++)
    {
        SplitTextureCube(i, face);
        glTexImage2D (GL_TEXTURE_CUBE_MAP_POSITIVE_X+i, 0, GL_RGB, width/4, height/3, 0, GL_RGB, GL_UNSIGNED_BYTE, face);
        //glTexImage2D (GL_TEXTURE_CUBE_MAP_POSITIVE_X+i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, imageData);
    }
    delete [] face;

I guess you need no more explain. The problem is when my program running, my cube texture is disordered like this:

I sure that problems are inside my "SplitTextureCube" function, i sure that i read pixels in the wrong order, please help me fix that function.


texts:
I am a C# developer and wanted to start a hobby project building a persistent browser based game (PBBG). I work with C#, MSSQL and Angular and thought I would use those techniques for my hobby project as well.

When I started to search for do and donts and tips I realized that a lot of projects use PHP and I have actually not found any PBBG using C#, which I find really strange. It seems as the stack I'm working with (C#, MSSQL, Angular) could suit a PBBG.

The only reason I can think of C# not being used is the hefty price of Visual Studio and the fact that it wasn't open source.

Is there any other reason, or am I just bad at finding projects which use C#? Or can it be that I'm just bad at my work and don't realise that this stack is not good for PBBG?


texts:
I'm sure there are articles around on this but I'm not really sure what they are called.

animation blending tends to give me the blend between two different complete animation such as walk and run.

what I'm after is having a player with that has a walk/jump animation and a firing gun animation. Is this still animation blending?

Can anybody enlighten me to how this process could be achieved?


texts:
My problem is this. I have a simple box made in 3DS Max 2009, the Box is 10x10x10. I've tried to load it on XNA and traslate the camera for 15 units, but I can seem to find the values needed to see the box properly. Can anyone point me to a good resource where I can find some good introduction to XNA coordinate system and how is a simple box made in 3DS Max imported properly

Best regards,
David


texts: How can I use a different upscaling method in dx11?

texts: I need to upscale images using the 'box' scaling algorithm as the pixel art textures in my game don't scale well with bilinear because of the blur. Either that, or use high res pictures which would be undesirable and inflate the size by many times.


texts:
I have online game for which I wrote a simple external anticheat in c#, it checks my game's process modules and handles for suspicious activity. And so it works like this:

player starts launcher (anticheat) which then starts the game with
its pid as parameter
actual game (upon starting) reads that pid, locates anticheat
path using this pid and fetches md5 hash of my anticheat
If it doesn't match the game closes. Also if you close anticheat the
game closes too.

So theoretically there's no way user could exit anticheat without exiting the game except he could for instance suspend anticheat process and then its of no use. What simple thing I could do to prevent this from happening?
I was thinking - make a thread in the game that would check in a loop if anticheat process is suspended and exit if it is. Would that be a correct approach?

Is my architecture flawed or is it ok?


texts: Monogame/SharpDX Texture2D doesn't hold value

texts:
The problem I have discovered is most likely between classes, so I dont really have much option but to post the whole code here:
https://www.dropbox.com/sh/smyw9t1ap3by2vd/pBX-aJJ-Qx

I have been having some trouble with spritebatches rendering textures recently using monogame for windows 8 with xaml where it throws an error after a few seconds of running. The error only occurs after a few seconds, though the less efficient or more textures i render, the quicker it crashes. After doing a git submodule update, the error message is entirely gone, but the textures still dissappear from the screen leaving just the cornflower blue.

The folks on GitHub have decided that this is a problem with my code and not theirs, which means I am definitely doing something wrong. For reference, here is the issue thread: https://github.com/mono/MonoGame/issues/1927. Thanks for any help!

UPDATE: I have identified the source of the problem. It has to do with declaring and holding the texture.

    protected override void LoadContent()
    {
        _spriteBatch = new SpriteBatch(GraphicsDevice);
        ContentManager myManager = new ContentManager(Content.ServiceProvider, Content.RootDirectory);
        terrainEngine.Load(myManager);
    }

    ContentManager content;
    public void Load(ContentManager content)
    {
        this.content = content;
        blockTextures = content.Load<Texture2D>("Graphics\\Blocks");
        spriteFont = content.Load<SpriteFont>("Graphics\\SpriteFont1");
    }

Now, if I call Load(content) from inside the terrainEngine class Update method, then the program works, otherwise, the textures disappear after a second.


texts:
I recently implemented the SAT algorithm into my 2D game and at first it appeared to be working fine. However, when I move around and rotate the character in and out of the wall tiles, there are some angles and positions that do not register as a collision when the player and wall tile are clearly overlapping. I created my own RotatingRectangle class that rotates around the player and is the bounding box.

I am unsure what could be causing this, or if this is just natural SAT behaviour and it does not actually detect all collisions accurately? There are no other resources online for inconsistent SAT collision detection so I am lost. I will post my code for the projections and actual collision detection in case I made a silly mistake somewhere

    // Returns an array of projections, one onto each axes
    public Vector2[] ProjectOntoAxes(List<Vector2> points)
    {
        Vector2[] projections = new Vector2[2];

        for (int i = 0; i < Axes.Length; i++)
        {
            float max = float.MinValue;
            float min = float.MaxValue;

            for (int j = 0; j < points.Count; j++)
            {
                float res = Vector2.Dot(Axes[i], points[j]);

                if (res < min)
                {
                    min = res;
                }
                else if (res > max)
                {
                    max = res;
                }
            }

            projections[i] = new Vector2(min, max);
        }

        return projections;
    }

        private bool PlayerTileCollision(Tile tile)
    {
        // Check overlap on projections onto player axes
        Vector2[] projections = Player.BoundingRect.ProjectOntoAxes(tile.BoundingRect.Corners);
        for (int j = 0; j < projections.Length; j++)
        {
            if (Player.BoundingRect.Projections[j].X > projections[j].Y ||
                Player.BoundingRect.Projections[j].Y < projections[j].X)
            {
                // No overlap can exit
                return false;
            }
        }
        // Check overlap on projections onto tile axes
        projections = tile.BoundingRect.ProjectOntoAxes(Player.BoundingRect.Corners);
        for (int j = 0; j < projections.Length; j++)
        {
            if (projections[j].X > tile.BoundingRect.Projections[j].Y ||
                projections[j].Y < tile.BoundingRect.Projections[j].X)
            {
                // No overlap can exit
                return false;
            }
        }

        return true;
    }

UDPATE:
I have added code to visualise the projections and axes to see what is going on, and it appears that the projection code is not properly selecting the correct minimum and maximum values. I will try to figure out why now. (Purple lines are player projections and orange is the projections of that tile I am standing on, the top left one and the player axes can be visualised via the white lines at the origin)


texts: What do you use to support multiplayer turn-based network game for iOS and Android games?

texts:
If I'm doing a turn-based card game, what kind of technique do you use to support multiplayer gameplay over Internet?

Is it socket? If it's socket, which SDK (CoronaSDK etc.) can provide solid socket library?

Can Unity3D can be used solely to support what I need without using other socket servers like SmartFox or Electro?


texts: Tweaking Heightmap Generation For Hexagon Grids

texts:
Currently I'm working on a little project just for a bit of fun.  It is a C++, WinAPI application using OpenGL.

I hope it will turn into a RTS Game played on a hexagon grid and when I get the basic game engine done, I have plans to expand it further.

At the moment my application consists of a VBO that holds vertex and heightmap information.  The heightmap is generated using a midpoint displacement algorithm (diamond-square).

In order to implement a hexagon grid I went with the idea explained here.  It shifts down odd rows of a normal grid to allow relatively easy rendering of hexagons without too many further complications (I hope).

After a few days it is beginning to come together and I've added mouse picking, which is implemented by rendering each hex in the grid in a unique colour, and then sampling a given mouse position within this FBO to identify the ID of the selected cell (visible in the top right of the screenshot below).

In the next stage of my project I would like to look at generating more 'playable' terrains.  To me this means that the shape of each hexagon should be more regular than those seen in the image above.

So finally coming to my point, is there:

A way of smoothing or adjusting the vertices in my current method that would bring all point of a hexagon onto one plane (coplanar).
A better approach to procedural terrain generation that would allow for better control of this sort of thing.
A way to represent my vertex information in a different way that allows for this.

To be clear, I am not trying to achieve a flat hex grid with raised edges or platforms (as seen below).

I would like all the geometry to join and lead into the next bit.

I'm hope to achieve something similar to what I have now (relatively nice undulating hills & terrain) but with more controllable plateaus.  This gives me the flexibility of cording off areas (unplayable tiles) later on, where I can add higher detail meshes if needed.

Any feedback is welcome, I'm using this as a learning exercise so please - all comments welcome!


texts: getting bone base and tip positions from a transform matrix?

texts:
I need this for a Blender3d script, but you don't really need to know Blender to answer this.

I need to get bone head and tip positions from a transform matrix read from a file.
The position of base is the location part of the matrix, length of the bone (distance from base to tip) is the scale, position of the tip is calculated from the scale (distance from bone base) and rotation part of the matrix.

So how to calculate these?

bone.base([x,y,z]) # x,y,z - floats
bone.tip([x,y,z])


texts: How to add zombie arms to enemies in HTML canvas

texts:
I'm making a game with HTML canvas (not WEBGL). I have zombies that go to the center of the screen, but for now they are just circles. I want to give them two arms, like the arms players have in surviv.io. I have looked at this question: Moving an object in a circular path. I don't know what trigonometry to use to calculate the angle. Here is my code:

var canvas = document.querySelector('#canvas');
var context = canvas.getContext('2d');

function Enemy(x, y) {
  this.x = x;
  this.y = y;
  this.r = 5;
  this.color = `hsl(${Math.floor(Math.random() * 360)},50%,50%)`;
  this.vx = 0;
  this.vy = 0;
  this.draw = () => {
    this.x += this.vx;
    this.y += this.vy;
    context.beginPath();
    context.fillStyle = this.color;
    context.arc(this.x, this.y, this.r, 0, Math.PI * 2);
    context.fill();
  }
}
var enemy = new Enemy(0, 0);

function loop() {
  requestAnimationFrame(loop);
  context.fillStyle = 'rgba(0,0,0,0.2)';
  context.fillRect(0, 0, canvas.width, canvas.height);
  var angle = Math.atan2(canvas.height / 2 - enemy.y, canvas.width / 2 - enemy.x);
  enemy.vx = Math.cos(angle);
  enemy.vy = Math.sin(angle);
  enemy.draw();
}
requestAnimationFrame(loop)
<canvas id='canvas'>

I want the arms facing the center, and I want them to move when the enemy changes direction.


texts:
Everytime I start the game, or I swap animator controllers in the inspector (in runtime), the character is flipped in X axis until I start moving him.

How do I prevent this to happen? This happens to me everytime I start a new project and I grow tired of this.

Update

8 animations which are all idle ones of just 1 frame

Down
DownRight
Right
UpRight
Up

The last 3 have the Sprite Renderer's flipX enabled within their animations:

UpLeft
Left
DownLeft

In the middle of the transitions, sprite remains flipped until it reaches 1 or -1.

I recorded recently a video to display the issue.

  https://www.youtube.com/watch?v=dC09snKvHAM

Same as above but in 1080p and showing entire Unity window.

  https://www.youtube.com/watch?v=Ww3GkUvb7bc

2nd update

PlayerControls.cs:

using UnityEngine;
using System.Collections;

public class PlayerControls : MonoBehaviour {

    Rigidbody2D rb;
    PlayerStats pStats;
    Animator anim;

    void Awake () {
        rb = GetComponent<Rigidbody2D>();
        pStats = GetComponent<PlayerStats>();
        anim = GetComponent<Animator>();
    }

    void Update () {
        if (Input.GetAxisRaw("Vertical") > 0)
        {
            rb.velocity = new Vector3(rb.velocity.x, pStats.pMoveSpeed, 0);
        }
        if (Input.GetAxisRaw("Vertical") < 0)
        {
            rb.velocity = new Vector3(rb.velocity.x, -pStats.pMoveSpeed, 0);
        }
        if (Input.GetAxisRaw("Horizontal") < 0)
        {
            rb.velocity = new Vector3(-pStats.pMoveSpeed, rb.velocity.y, 0);
        }
        if (Input.GetAxisRaw("Horizontal") > 0)
        {
            rb.velocity = new Vector3(pStats.pMoveSpeed, rb.velocity.y, 0);
        }
        if (Input.GetButton("Vertical") || Input.GetButton("Horizontal"))
        {
            anim.SetFloat("OrientationY", Input.GetAxisRaw("Vertical"));
            anim.SetFloat("OrientationX", Input.GetAxisRaw("Horizontal"));
        }
    }
}

PlayerStats.cs

using UnityEngine;
using System.Collections;

public class PlayerStats : MonoBehaviour
{

    public string pName;
    public string pClass;
    public int pLevel;
    public float pExperience;
    public float pBasicDamage;
    public float pMoveSpeed;

    public string[] pClassList;

    Animator anim;
    public RuntimeAnimatorController[] animCtrl;

    void Awake()
    {
        anim = GetComponent<Animator>();
    }

    void Update()
    {
        pLevel = 1 + (int)pExperience / 240;

        if (!CheckAssignedClass())
        {
            pClass = "Warrior";
            Debug.LogWarning("Player class not found. Using 'Warrior' as default.");
        }

        if (Input.GetKeyDown(KeyCode.J))
        {
            SetClass(pClass);
        }

    }

    bool CheckAssignedClass()
    {
        bool found = false;
        var i = 0;
        for (i = 0; i < pClassList.Length; i++)
        {
            if (pClassList[i] == pClass)
            {
                found = true;
                break;
            }
            else { found = false; }
        }
        return found;
    }

    void SetClass(string className)
    {
        switch (className) {
            case "Warrior": {
                    anim.runtimeAnimatorController = animCtrl[0];
                    break;
                }
            case "Archer": anim.runtimeAnimatorController = animCtrl[1]; break;
            case "Mage": anim.runtimeAnimatorController = animCtrl[2]; break;
            default: anim.runtimeAnimatorController = animCtrl[0]; break;
        }
    }
}


texts: What is the optimal way to update different entities in an engine?

texts:
EDIT: half of my question seemed to disappear, but thankfully, it was still in the clipboard.
When I say entities, I mean instantiations of various classes in my engine (example class: Engine.Animation, or Engine.Scene). The language in question is Javascript.
 The situation:

The current structure of my engine goes something like this:
// The single engine object that only stores constructor functions,
// aka classes (or at least it used to only store those).
Engine = {};

Engine.Scene = function()
{
    ...
}

Lets take the Scene class as an example... It basically stores all the information needed to render the visual part of the game state, which is done by the Renderer class (renderer.render(scene, camera)).

 The problem:

All worked well, but then I realized that the entities sometimes needed to be updated! The best (and, for now, the only) example of this is the scene.AlphaDown() method, which makes the scene transparent, "shuts it down", in a way.
I implemented this with the use of setInterval (the interval would call a function that used to lower the scene's alpha depending on how much time passed. This is the kind of "update method" I am talking about: the one that needs to be called iteratively, usually at 60FPS.) But, I was told that it was a bad practice (here and here). It was suggested to me that I use alternative ways of updating entities (without the use of setInterval).

 The possible solution:

I meant to have an array in Engine, called toUpdate, in which different entities would push their update methods. Then, the Engine would have a central update() method, which would calculate the time since last updated, and call the entities' registered update methods, giving that time as an argument. In the previous example with a scene, AlphaDown() would register an update method by pushing it into the Engine.toUpdate array.
When the task of an update method (ie scene.alpha = 0) was completed, it would be removed from the toUpdate array.

 The problem with the solution:

This method has it's flaws, though. First, it would require the user to call Engine.update() on each of his game loop iterations. Then, it would make the global Engine object have methods, but I just want to keep it a namespace of some sort, a collection of useful classes. I don't want to dictate how a loop should be structured!

 The question:

Is my solution an acceptable way of updating entities? Are there some other, more standard ways? Should I strive to have my entities not have update methods that need to be iteratively called, and let the user implement them?


texts:
Is there a term of art for the collection of non-gameplay screens or pages in a game. I am thinking of screens such as:

title screen
options menu (key bindings, volume, graphics quality)
credits screen
hi-score table (maybe extradiegetic?)
help page
etc

These are all 'meta-screens', in that they help the player manage the gameplay experience, but are outside the gameplay space.

The term I am looking for should  not include screens for extradiegetic elements, such as inventory management, character dialog boxes, hint screens etc. as these are all related to, or control gameplay state.


texts: 2D water shader similar to Limbo's effect

texts:
I'm wondering how I would go about creating a 2D water shader that is seen in this video http://www.youtube.com/watch?v=phChFfi4GOs

The water effect that limbo uses is pretty awesome. I'm not so much concerned about the waves, other articles cover that, but how can I get the..diffraction, I believe it's called, and various blurriness and how the object looks like it's moving even though it isn't (like real water).

GLSL is my target language.

But I don't have any idea on how to do the blur-like below-surface water movement effect. Any ideas?


texts: How can I implement foot pedal of a car in unity?

texts: I trying to create 2-D car game in unity for mobile where player controls acceleration by sliding the pedal in touch screen.Mine idea of implementation is using UI slider. Is there any other good I can use? Please suggest me any other implementation if any available.I'm new to this field.


texts: Checking if an object is inside bounds of an isometric chunk

texts:
How would I check if an object is inside the bounds of an isometric chunk? for example I have a player and I want to check if its inside the bounds of this isometric chunk.
I draw the isometric chunk's tiles using OpenGL Quads.

My first try was checking in a square pattern kind of thing:

e = object;
this = isometric chunk;

    if (e.getLocation().getX() < this.getLocation().getX()+World.CHUNK_WIDTH*World.TILE_WIDTH && e.getLocation().getX() > this.getLocation().getX()) {
        if (e.getLocation().getY() > this.getLocation().getY() &&   e.getLocation().getY() < this.getLocation().getY()+World.CHUNK_HEIGHT*World.TILE_HEIGHT) {
            return true;
        }
    }
    return false;

What happens here is that it checks in a SQUARE around the chunk so not the real isometric bounds. Image example: (THE RED IS WHERE THE PROGRAM CHECKS THE BOUNDS)

What I have now:

Desired check:

Ultimately I want to do the same for each tile in the chunk.

EXTRA INFO:

Till now what I had in my game is you could only move tile by tile but now I want them to move freely but I still need them to have a tile location so no matter where they are on the tile their tile location will be that certain tile. then when they are inside a different tile's bounding box then their tile location becomes the new tile. Same thing goes with chunks. the player does have an area but the area does not matter in this case. and as long as the X and Y are inside the bounding box then it should return true. they don't have to be completely on the tile.


texts: What does the Node2D transform property do?

texts:
Following a Godot tutorial I encountered the transform property, but I'm not sure what it means nor how to use it.
I read the official Godot documentation, but it didn't give me a full explanation about the theme. I just got this:

Transform2D transform
Setter set_transform(value)
Getter get_transform()

Could someone explain to me more about this?


texts: How to create per-vertex normals when reusing vertex data?

texts:
I am displaying a cube using a vertex buffer object (gl.ELEMENT_ARRAY_BUFFER). This allows me to specify vertex indicies, rather than having duplicate vertexes. In the case of displaying a simple cube, this means I only need to have eight vertices total. Opposed to needing three vertices per triangle, times two triangles per face, times six faces. Sound correct so far?

My question is, how do I now deal with vertex attribute data such as color, texture coordinates, and normals when reusing vertices using the vertex buffer object?

If I am reusing the same vertex data in my indexed vertex buffer, how can I differentiate when vertex X is used as part of the cube's front face versus the cube's left face? In both cases I would like the surface normal and texture coordinates to be different. I understand I could average the surface normal, however I would like to render a cube. Also, this still doesn't work for texture coordinates.

Is there a way to save memory using a vertex buffer object while being able to provide different vertex attribute data based on context? (Per-triangle would be idea.)

Or should I just duplicate each vertex for each context in which it gets rendered. (So there is a one-to-one mapping between vertex, normal, color, etc.)

Note: I'm using OpenGL ES.


texts: How can I convert a string to quaternion?

texts:
private GameObject GetObjectFromFile(string path)
    {
        GameObject newobj = new GameObject();
        string[] text = new string[3];
        if (File.Exists(path))
        {
            text = File.ReadAllLines(path);
            foreach (string s in text)
            {

                    text = s.Split(':');
                    break;

            }
            var parent = text[0];

            var localPosition = StringToVector3(text[1]);
            var localRotation =StringToVector3(text[2]);
            var localScale = StringToVector3(text[3]);

            newobj.transform.localPosition = localPosition;
            newobj.transform.localRotation = localRotation;
            newobj.transform.localScale = localScale;
        }

        return newobj;
    }

    public static Vector3 StringToVector3(string sVector)
    {
        // Remove the parentheses
        if (sVector.StartsWith("(") && sVector.EndsWith(")"))
        {
            sVector = sVector.Substring(1, sVector.Length - 2);
        }

        // split the items
        string[] sArray = sVector.Split(',');

        // store as a Vector3
        Vector3 result = new Vector3(
            float.Parse(sArray[0]),
            float.Parse(sArray[1]),
            float.Parse(sArray[2]));

        return result;
    }

It's converting fine the localPosition and localScale but the localRotation is a quaternion and not vector3.

This is the text file format I'm reading from:

Main Camera (UnityEngine.Transform):(297.7, 5.1, 228.5):(0.0, 0.0, 0.0, 1.0):(1.0, 1.0, 1.0)

The part (0.0, 0.0, 0.0, 1.0) is the rotation.


texts:
i'm trying to using a SOAP service from my game but the problem is that after using wsdl.exe for generete the connector Unity inform me that System.Web namespace doesn't exist.

How can I use the wsdl?
There is some workaround without writing a lot of code?

Many thanks


texts: Create 2D sprites with libGdx using a shape and a texture separately

texts:
I am creating a 2D game with LibGdx that will have creatures that are generated from dozens of characteristics with potentially millions of unique combinations. For each segment of each creature, I want to use two sprites so that I can mix shapes and colors and cut down on my resources. I would like one sprite to be a black and white (or grayscale) of the shape of the body part while the second sprite is just a color pattern. I think I may need to write a shader that splices the color pattern onto my shape to give me the sprite I need. I just need some guidance on how to get started.

Another way of explaining this is with the example of clothing. I want to be able to draw a shirt shape, and pants shape, a socks shape, etc. and also draw different fabric patterns. Then I would mix and match the clothing with the pattern instead of drawing every possible combination. How can I accomplish this with LibGdx?


texts: Unknown error when trying to register a Minecraft ArmorItem

texts:
The error in question is [Inferred type 'I' for type parameter 'I' is not within its bound; should extend 'net.minecraft.item.Item']
on the following snippet of code
// Armor Items
public static final RegistryObject<ArmorItem> RINGMAIL_HELMET = ITEMS.register("ringmail_helmet",
        new ArmorItem(DnDCraftArmorMaterial.RINGMAIL, EquipmentSlotType.HEAD, new Item.Properties().group(DnDCraft.TAB)));

I have tried many things like what I do here
public static final RegistryObject<Item> RING = ITEMS.register("ring", ItemBase::new);

by putting the ItemBase::new snippet in the last paramter.
I've also tried seeing what IntelliJ suggests is best in-context action but none of those approaches seemed to fix the issue.
I'm not super familiar with Java or Minecraft modding so this may just be something simple that I am missing but any help or recommendations would be nice. Thanks!
Also this is the ItemBase class, in case that helps.
package com.fire.dndcraft.items;

import com.fire.dndcraft.DnDCraft;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;

public class ItemBase extends Item {
    public ItemBase() {
        super(new Item.Properties().group(DnDCraft.TAB));
    }
}


texts: Issues glVertexAttribPointer last 2 parameters?

texts:
Introduction

Hello I will start out by explaining my setup, showing samples as I go along explaining the situation.

I'm using these tools:

OpenGL 3.3
GLSL 330
C++

Problem

The problem is when I render the wavefront obj 3d model it gives a very weird visual glitch the model was supposed to be a square but instead its a triangluated mess with parts of the vertexes pointing in a stretched direction in massive amounts towards the bottom left side of the frustum....

Explanation:

I'm using std::vectors to store my wavefront .obj model data using sscanf to get the floating point values into the structure members x,y,z and store them into the Points structure variable p;

int index = IndexAssigner(1, 1);
ifstream file (list[index].c_str() );
points.push_back(Point());
Point p;
int face[4];

while (!file.eof() ) {
    char  modelbuffer[10000];
    file.getline(modelbuffer, 10000);
    switch(modelbuffer[0]) {
        case 'v' :
        sscanf(modelbuffer, "v %f %f %f",  &p.x, &p.y, &p.z);
        points.push_back(p);
        break;
        case 'f':
        sscanf(modelbuffer, "f %d %d %d %d", face, face+1, face+2,  face+3 );
        faces.push_back(face[0]);
        faces.push_back(face[1]);
        faces.push_back(face[2]);
        faces.push_back(face[3]);
    }
    //Turn on FileReader aka "RENDER CODE"
    FileReader = true;
}

then I render the Points vector using the .data() member of std::vectors to the frustum.

Other declarations:

int numfloats = 4;
float* point=reinterpret_cast<float*>(&points[0]);
int num_bytes=numfloats*sizeof(float);

Vector declarations:

struct Point {float x,  y , z; };
std::vector<int>faces;
std::vector<Point>points;

Render code:

glGenBuffers(1, &vertexbuffer);
glGenTextures(1, &ModelTexture);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBindTexture(GL_TEXTURE_3D, ModelTexture);
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA,  ModelSurface->w, ModelSurface->h, 0, GL_BGR, GL_UNSIGNED_BYTE, ModelSurface->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBufferData(GL_ARRAY_BUFFER, sizeof(points), points.data(), GL_STATIC_DRAW);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE,num_bytes ,points.data());
glEnableVertexAttribArray(3);

//Translation Process
GLfloat TranslationMatrix[] = {
        1.0, 0.0, 0.0, 0.0,
        0.0, 1.0, 0.0, 0.0,
        0.0, 0.0, 1.0, 1.0,
        0.0, 0.0, 0.0, 1.0
      };

//Send Translation Matrix up to the vertex shader
glUniformMatrix4fv(translation, 1, TRUE, TranslationMatrix);

glDrawElements( GL_QUADS, faces.size(), GL_UNSIGNED_INT,  faces.data());

I tried looking at what was causing this and went through every function every parameter ,etc looked at the man pages.

Then found out that it could be my glVertexAttribPointer.

Here are the man pages for glVertexAttribPointer

http://www.opengl.org/sdk/docs/man/xhtml/glVertexAttribPointer.xml

The last 2 parameters is my problem

How do I write those 2 last parameters do I try putting the data from Points into it?.

glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE,num_bytes ,points.data());

How does it work with vectors?

Is it fast?*

if you can not be bothered too look at the man pages here is the scripts coming from the man pages directly.

Stride

Specifies the byte offset between consecutive generic vertex attributes. If stride is 0, the generic vertex attributes are understood to be tightly packed in the array. The initial value is 0.

Pointer

Specifies a pointer to the first component of the first generic vertex attribute in the array. The initial value is 0.

If you want my full source -> http://ideone.com/fPfkg

Thanks Again if you do read this.


texts: Making a cube slowly rotate 180 degress one time on a mouseclick

texts:
I am new to C# and new to Unity. I made a script that can turn a cube slowly one time after a mouse click but I feel like its probably wrong for using FixedUpdate. Is this OK or is there a better way? What is wrong with this way?

using UnityEngine;
using System.Collections;

public class MouseClick : MonoBehaviour {

    public float myRotationSpeed = 1.0f;
    bool flipped = false;

    //when User clicks it with mouse
    void OnMouseDown ()
    {

        if (flipped == false)
        {
        flipped = true;
        }
    }
    void FixedUpdate ()
    {

        if(flipped == true && gameObject.transform.rotation.y >=0.01)
        {

            transform.Rotate(0, myRotationSpeed * Time.deltaTime, 0);
        }
    }
}


texts:
I am trying to use a compute shader to generate some data in a texture. My compute shader looks something like this:

#version 430
//uniform int u_CurrentMipSize;
const int u_CurrentMipSize = 1024;
layout( r16f ) uniform writeonly image2D u_densityTexture;

bool ContributesSignificantDensity( ivec2 uv )
{
    return uv.x >= ( u_CurrentMipSize / 8 ) && uv.y >= ( u_CurrentMipSize / 8 );
}

//.... in main()
if( ContributesSignificantDensity( targetPosition ) )
{
    imageStore( u_densityTexture, targetPosition, vec4( 1.0 ) );
}
else
{
    imageStore( u_densityTexture, targetPosition, vec4( 0.0 ) );
}

And the calling code looks like this:

glUseProgram( m_DensityGenShader );

glMemoryBarrier( GL_SHADER_IMAGE_ACCESS_BARRIER_BIT );

uniform_loc = glGetUniformLocation( m_DensityGenShader, "u_densityTexture" );
if( uniform_loc != unsigned int( -1 ) )
{
    glBindImageTexture( uniform_loc, m_DensityTexture, 0, false, 0, GL_WRITE_ONLY, GL_R16F );
}
checkOpenGLErrors( "Density Texture Compute Shader" );

uniform_loc = glGetUniformLocation( m_DensityGenShader, "u_CurrentMipSize" );
if( uniform_loc != unsigned int( -1 ) )
{
    glUniform1i( uniform_loc, 1024 );
}
checkOpenGLErrors( "Density Texture Compute Shader" );

int num_to_compute = mip_sizes[ i ] / 16;
glDispatchCompute( num_to_compute, num_to_compute, 1);
checkOpenGLErrors( "Density Texture Compute Shader" );

glMemoryBarrier( GL_SHADER_ACCESS_BARRIER_BIT );

If I use this code, the program executes correctly on my texture of size 1024. I am just storing this result in an image2D. If I use a const float the program executes correctly, and I get a red square in the upper right 7/8ths of the image. (Just rendering this texture onto a quad in another shader). Texture rendered on quad- yay red!

However, if I change the top of my shader to the following by using a uniform instead of a const float:

uniform int u_CurrentMipSize;
//const float u_CurrentMipSize = 1024;

Then the output texture is just garbage, random data: Texture rendered on quad- boo noise!

I'm always sending the uniform from the compiled code (if I get a valid uniform location back from opengl) so the only thing that changed is reading the value from a uniform vs a const float.

Should I be doing something differently with this because it's a compute shader? I've never had issues passing uniform data with vert/frag/geometry shaders?

I had a similar issue trying to do imageLoad operations, so I think I'm not setting up stuff with my compute shader correctly, but it works in the constant hard-coded case, so I'm not sure.

This is my first forray into compute shaders- I've worked with CUDA a bit so I'm familiar with the paradigms, but not sure how to debug if the kernel is crashing or abandoning early or corrupting the texture somehow or what?


texts: Confusion about flow and architecture for basic multiplayer card game state

texts:
As a web developer I'm used to a straightforward flow where all interactions typically correspond to a database read/write and the life-cycle corresponds with a single request.

As a learning exercise I wanted to write a basic multiplayer card game and realized I have a lot of confusion about where to best store active game state.

While I know a card game could easily read/write to a database per action, I was wondering if it is as simple as (in my case, a javascript node server):

Create a global state object
Create an active game object
Push it to an array in the global state
Perform actions on this active game in memory, broadcast new state to frontend via websockets
When the active game is complete, write the results to a database for persistent storage
Remove the active game from the state, thus freeing memory?

My questions:

Is this a reasonable solution or is it a bad practice? (global variables, memory management, state loss on process crash/restart etc...)
Would it make more sense to set up a redis server for handling temporary state?

This is quite different from a frontend perspective where redux/vuex makes handling state a straightforward task, and from what I've read, it is desirable for the backend to be 'stateless' - it just seems weird to me to read/write to a database for things that don't require long-term persistence.

Edit: I also know firebase could be a very suitable solution, I just prefer to avoid vendor lock-in if possible.


texts: which is the best approach or algorithm to calculate real-time ranking

texts:
I want to know the fastest and most efficient way to compute points and ranking in real time.

I'm doing a betting football game (a game where users try to predict the outcome of a game before it). In my country is called "Quiniela".

Players put "predictions" just before the match starts. My question is: from the moment the game starts, which is the most efficient way (not just code level but to the database and server) to calculate the ranking for the players "real time" as their predictions regarding the actual outcome of the game.

For example:

If a Team1 vs Team2 plays, the user U1 predicted that the game would end 0-0, U2 predicted the game would end 1-0, U3 predicted the game would would end 1-1.

When starting the game, the U1 would be to first in the ranking because, if the match ends like this, his prediction would be correct, or at least the most accurate.

Then the score switches to 1-0, and the user U1 would be the last of the ranking (because his prediction is not possible anymore), U2 would be the first and U3 second.

If the score changes to 1-1, U2 would go first, U3 would be second (because he guessed part of the result) and U3 last.

I thought about creating a tree of possibilities with one level (0-0 first node, with 1-0 and 0-1 as child nodes) as you change the score, changes the Ranking "temporarily" and I would keep it in cache.

Once the game is over, I keep the latest Ranking in the database.

There is a more optimal way to solve this problem? It has been proposed before and already solved? I'm using MySQL for database, PHP (Cake Php) for the server and a bunch of mobiles who ask for the ranking once in a while.


texts: how do I create a delay or cooldown timer?

texts:
I want to know if I am in the right tracks in building a  function that gives you 2 secs of rest before you can attack again

int attackRate = 2000;
int timeElapse = 0
public void cooldown() {
      if (timeElapse < attackRate) {
          // do somthing here
          timeElapse++;
        } else {
           timeElapse = 0
      }

when creating this it doesnt seem to work. am i missing something?


texts: Pass and Change Objects Between Scenes in Unity

texts:
I ran into a bit of a problem with organasing object changes as well as storing them and passing to scenes.
By that, I mean that I'm programming a game that has different characters and possibility to customize them as well as their equipment and weapons. It's gonna be a multiplayer game...so, the question is what's the BEST practice of storing and passing customized characters with weapons between scenes and via network connection?

Similarly to Rainbow Six Siege, where all your custom stuff is saved on a user and passed both in single and multiplayer modes into a level.

Just need some refs, tips or maybe articles on the matter. No code needed.
Thanks in advance!


texts: Alternative Font loaders in Monogame Framework

texts: While working on projects of mine, I have been finding that it is a huge pain to switch operating systems just to create a simple spritefont when using Monogame. I saw that the Nuclex Framework can load fonts which are clearer/sharper, and they can be used in a Monogame project as well. They load fonts using the FreeType library, which is very multiplatform and is used widely. Is there a fairly simple way to use the FreeType library or another library to render text suitable for use in a Monogame project, as an xnb file?


texts:
I am trying to make my enemy shoot my player but for some reason the bullets arent showing nor they are shooting at the player I don't even know why, I even draw the bullets on my window  VIDEO

bulls = []
runninggame = True
while runninggame:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            runninggame = False

    for bull in bulls:
        if bull.x < 500 and bull.x > 0:
            bull.x += bull.vel  # Moves the bullet by its vel
        else:
            for enemys in enemying:
                if playerman.x - 100 <= enemys.x <= playerman.x + 100 and playerman.y - 100 <= enemys.y <= playerman.y + 100:
                    bulls.pop(bulls.index(bull))
                    bulls.append(enemybullets(round(enemys.x+enemys.width//2), round(enemys.y + enemys.height//2), 6, (0,0,0), facing))

then I called it below

    for bull in bulls:
        bull.draw(window)

my enemy projectile class

# enemys bullets
class enemybullets(object):
    def __init__(self,x,y,radius,color,facing):
        self.x = x
        self.y = y
        self.radius = radius
        self.color = color
        self.facing = facing
        self.vel = 8 * facing

    def draw(self,win):
        pygame.draw.circle(win, self.color, (self.x,self.y), self.radius)

```


texts: Adding Google IAP License Key into Unity Games

texts:
I have added Google Play Services and AdMob successfully into my app. But I want an in-app purchase button that lets you remove the adverts. (I have the button already but not the billing).

Google Developers Console tells me I need to input my app's specific license key into my app. The Android Manifest.xml to be specific. But it's not the clearest instructions. The Unity guide seems very lacking too, and mostly I can only find stuff about Unity IAP.

The Unity guide I did find tells me it makes the Manifest automatically and only tells me that I can write my own complete Manifest and import it over the top of the auto-made one.

I don't really want to do that if possible as I have just finished adding all the other Google stuff via Unity into the Manifest.xml

I'm sure this is a common feature that lots of devs use, so that makes me think there must be some way to do it via Unity.


texts: Generating face normals with the geometry shader

texts:
I'm trying to visualize the face normals for a mesh, using the geometry shader to generate lines represeting the normal vectors. My intention was to draw that line from the triangles centroid, extenting a certain amount in the normal's direction.

This is the vertex shader's code :

#version 450 core

layout (location = 0) in vec3 vs_in_pos;
layout (location = 1) in vec3 vs_in_normal;
layout (location = 2) in vec2 vs_in_texc;

out VS_OUT_GS_IN {
    layout (location = 0) vec3 pos;
    layout (location = 1) vec3 normal;
    layout (location = 2) vec2 texc;
} vs_out;

void main() {
    gl_Position = vec4(vs_in_pos, 1.0f);
    vs_out.pos = vs_in_pos;
    vs_out.normal = vs_in_normal;
    vs_out.texc = vs_in_texc;
}

This is the geometry shader's code :

#version 450 core

layout (row_major) uniform;
layout (triangles) in;
layout (line_strip, max_vertices = 2) out;

in VS_OUT_GS_IN {
    layout (location = 0) vec3 pos;
    layout (location = 1) vec3 normal;
    layout (location = 2) vec2 texc;
} gs_in[];

out GS_OUT_PS_IN {
    layout (location = 0) vec4 color;
    layout (location = 1) vec3 pos;
} gs_out;

layout (binding = 0) uniform transform_pack {
    mat4 model_view_projection;
};

uniform float normal_length;
uniform vec4 start_point_color;
uniform vec4 end_point_color;

void main() {

    const vec3 avg_normal = normalize(
        gs_in[0].normal + gs_in[1].normal + gs_in[2].normal);

    const vec3 triangle_centroid =
        (gs_in[0].pos + gs_in[1].pos + gs_in[2].pos) / 3.0f;

    {
        gl_Position = model_view_projection * vec4(triangle_centroid, 1.0f);
        gs_out.color = start_point_color;
        gs_out.pos = triangle_centroid;
        EmitVertex();
    }

    {
        const vec3 end_pt = triangle_centroid + avg_normal * normal_length;
        gl_Position = model_view_projection * vec4(end_pt, 1.0f);
        gs_out.pos = end_pt;
        gs_out.color = end_point_color;
        EmitVertex();
    }

    EndPrimitive();
}

My problem is that the line representing the face normal has the origin
at one of the triangle's vertices (not the centroid).

If, however, I change this line

const vec3 triangle_centroid =
    (gs_in[0].pos + gs_in[1].pos + gs_in[2].pos) / 3.0f;

with this line

const vec3 triangle_centroid =
    (gl_in[0].gl_Position.xyz + gl_in[1].gl_Position.xyz
    + gl_in[2].gl_Position.xyz) / 3.0f;

the line representing the normal has the origin at the centroid (as it should).

But I really have no ideea why the first approach does not produce the correct
result.

Some screenshots :

first method (wrong):

second method (correct):


texts: How Plants vs Zombies animation is done?

texts: I really like the plants vs zombies style of animation and it doesn't look complicated yet the result is really good. I doubt it's made of sprites seeing there's a large number of animations, combinations, distortions, outfits. So how that kind of animation is done?


texts: In Unity, how do I make a mesh change its opacity during runtime?

texts:
I'm trying to make a isometric game. I want to make it so that when the player goes behind a wall, the wall's alpha goes down.

How do I go about doing this?

I have this code that I made, but I don't understand what's wrong with it.

I already have the wall that's meant to disappear on the "Wall" layer.

using UnityEngine;
using System.Collections;

public class WallAlpha : MonoBehaviour {

    public LayerMask mask =LayerMask.GetMask("Wall");

    void Update() {

        if (Physics.Raycast(transform.position, transform.forward, 100, mask.value))
        {
            transform.GetComponent<Renderer>().material.SetColor("_Color", new Color(1,1,1,0.1f));
            Debug.Log("Something in the way");
        }

        else
        {
            transform.GetComponent<Renderer>().material.SetColor("_Color", new Color(1,1,1,1.0f));
            Debug.Log("Nothing In the Way!");
        }
    }
}


texts: How would I process accelerometer data to use it for camera rotation?

texts:
I'm using Three.js to make a web-based 3D first-person game.  I would like the player to be able to control the camera rotation with their device's accelerometer.

The sensor data is received via the DeviceMotionEvent event listener. Here is an example of what it returns:

How should I proceed with this?


texts: Parallel rendering in DirectX 9 in WPF application

texts: I want to know if it is possible to have parallel rendering in DirectX 9.0. I am working on a WPF application which uses DirectX 9.0 for rendering. To make my application more efficient I want to have parallel rendering capability in my application if possible. When I try to render from multiple threads, it gives me an Direct3D exception. Is there any way to do this? Any ideas?


texts: Game development equivalent of Movie Director

texts: Is there a job in game development that is equivalent to being a movie director?


texts: Separate shaders from HTML file in WebGL

texts:
I'm ramping up on WebGL and was wondering what is the best way to specify my vertex and fragment shaders.

Looking at some tutorials, the shaders are embedded directly in the HTML. (And referenced via an ID.) For example:

<script id="shader_1-fs" type="x-shader/x-fragment">
  precision highp float;
  void main(void) {
    // ...
  }
</script>

<script id="shader_1-vs" type="x-shader/x-vertex">
  attribute vec3 aVertexPosition;

  uniform mat4 uMVMatrix;
  // ...

My question is, is it possible to have my shaders referenced in a separate file? (Ideally as plain text.) I presume this is straight forward in JavaScript. Is there essentially a way to do this:

var shaderText = LoadRemoteFileOnSever('/shaders/shader_1.txt');


texts:
I want to create a specyfic 2d image effect. It consists in modifying a sprite so it looks like it is being zoomed to a point or "absorbed" by that point. I'm not really sure what is the technical name of this effect so I cannot explain it correctly.

Here you can see a video of what I'm talking about, it is the effect when the character absorbs the three glyphs.

http://www.youtube.com/watch?v=PIo-GddsMcU&t=4m45s

What is the name of this effect?
How can I implement it with XNA for 2D textures/sprites?


texts:
I am making a study for a research project that involves measuring the performance and quality impact of rendering 3d games using a software rasterizer (like WARP).

I wonder if there is a way to force games to use WARP. Maybe something easier would be to just use games that support using warp or the reference rasterizer. Are there any relatively new game (no more than 8 years old) that supports that? I don't remember seeing that option in games in a long time.

If there is no tool or setting to do that, I was thinking I could use something like Detours (http://research.microsoft.com/en-us/projects/detours/) or EasyHook (http://easyhook.codeplex.com/), and perform binary rewriting on the code. For DirectX 10 games I think it should be enough to intercept the CreateDevice call and change the device. For DirectX9 games is it enough to change the D3D9CreateDevice for a D3D10CreateDevice? I tried with samples from the SDK and it seems it is not the case. Any suggestions on what to do there?


texts:
I've some trouble for sending a post request to my nodejs server.
I can receive data from the server with GET method, but when I try to send data with POST, I've an empty bracket on return on this function:
func _on_request_completed(result, response_code, headers, body):
    var json = JSON.parse(body.get_string_from_utf8())
    print(json.result)
    print(response_code)

And empty bracket on my JSON console.log on the server too.
My code:
extends CanvasLayer

func _ready():
    $HTTPRequest.connect("request_completed", self, "_on_request_completed")

func _on_Button_pressed():
    var data = {"name": "Godette"}
    _make_post_request("http://localhost:8080/", data, false)

func _on_request_completed(result, response_code, headers, body):
    var json = JSON.parse(body.get_string_from_utf8())
    print(json.result)
    print(response_code)

func _on_HTTPRequest_request_completed():
    pass

func _make_post_request(url, data_to_send, use_ssl):
    # Convert data to json string:
    var query = JSON.print(data_to_send)
    # Add 'Content-Type' header:
    var headers = ["Content-Type: application/json"]
    $HTTPRequest.request(url, headers, false, HTTPClient.METHOD_POST, query)

And this code return this in my console:
{}
200
Thanks for help :)


texts: How can I add a [MenuItem] to the context menu shown when right-clicking a specific asset type in the Unity Editor?

texts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;

public class Test : Editor
{
    [MenuItem("Assets/Testing")]
    private static void Init()
    {

    }
}

When I right click on the Assets I will see the "Testing" item defined above in the context menu.

But I want to see this "Testing" option only if I right click on a script file (.cs or .js)

For example if I have a script file at Assets > Test > Test.cs, only when I right mouse click on Test.cs should the context menu show the new Testing option.

How can I do this?


texts: Sending state diffs (deltas) and unreliable connections

texts:
We're building a realtime multiplayer game, in which each player is responsible for reporting its state on every iteration of the game loop.

The state updates are broadcasted using unreliable UDP.

To minimize state data sending, we've come up with a system that will send only deltas (whatever state data that was changed).

This method however is flawed, since a lost packet will mean that other players will not receive the delta, making the game behave in an unexpected way.

For example:

Assume that state is comprised of: { positionX, positionY, health }

Frame 1  - positionX changed --> send a packet with positionX only.
Frame 2 - health changed // lost !
Frame 3 - positionY changed --> send a packet with positionY only.

// Other players don't know about health change.

How can one overcome this issue then? sending the entire data is not always feasible.


texts: How should I implement hit detection netcode for AI enemies in a co-op first-person-shooter?

texts:
I'm working on a FPS/sandbox game that has multiplayer but no PvP. Since the game has no PvP, I'm trying to make the networking code favor the player as much as possible.

For example, I allow the game-clients to decide whether a shot hit/missed an enemy, rather than having the game-server verify. I also allow the game-clients to decide where they are on the map -- with no verification from the server.

This opens the doors for cheaters, but in a PvE game I don't care so much.

However, I don't know how to design the enemy AI. If a player is lagging, the server doesn't know that player's real location, so how could I ensure that the player actually saw himself get attacked by an enemy (for example, a Zombie) before the server registered a hit on the player?


texts:
I'm making a 2d game, all is working, I have the characters and the map. The player have 6 different weapons and now I'm trying to make the collisions and the life / destruction system.

I have a character that follows the player. I made two triggers for this character and one for the player. When the player approaches, begins to haunt him, and when are near this character stop walking. To do this I programmed a "OntriggerEnter2d" and all is good, but now, I need to do anything similar with the bullets (or not). I tried OntriggerEnter2d and not works as expected, this detects the enter on the first zone of the bigger trigger, and I only need to detect the collision with the "body" of the characters.

Well, the question is, what is the best way to do the collisions between bullets and characters / objects??

Sorry if I explained bad the situation.


texts: How to get the address of a nearby square on a chess board?


texts:
I've been reading this very nice tutorial on OpenGL, and I encountered a statement which I can't wrap my head around. In Chapter 6, it states:

  Transformation from one space to another ultimately means this: taking the basis vectors and origin point from the original coordinate system and re-expressing them relative to the destination coordinate system. The transformation matrix from one space to another contains the basis vectors and origin of the original coordinate system, but the values of those basis vectors and origin are relative to the destination coordinate system.

This is reaffirmed in Chapter 7:

  ... And this makes sense; a transformation matrix contains the basis vector and origin of the source space, as expressed in the destination coordinate system.

... But isn't it the other way around?

Take a look at this example from the tutorial:

The transformation Matrix to transform from the space on the left to the space on the right is

[1   0   0   1  ]
[0   1   0  -1.5]
[0   0   1   0  ]
[0   0   0   1  ]

The last column of the transformation matrix is the origin of the destination space, expressed relative to the source space.

What am I missing?

Note The above transformation matrix is not from the notes, so feel free to correct it.


texts:
So I've not been able to find much online about how data should be stored for triangle adjacency.

Currently I calculate my adjacent using half-edges (mention in an answer here).

But do I store this data in with my VBO? (Which means twice the vertex data)
Or do I store it in my element array buffer? And if so how do I tell opengl the interleaving I would have in it?


texts:
I'm calculating matrices by hand. Translations are fine:

 void Translate (float x, float y, float z, float[4][4] m) {
     Identity (m);
     m[3][0] = x;
     m[3][1] = y;
     m[3][2] = z;
 }

If I multiply a vector with this matrix, I get the correct transformation. My problem now is Rotations. I copied the definition from the OpenGL reference on glRotation, but I can't get it right. Can you spot my mistake?

void Rotate (float angle, float x, float y, float z, float[4][4] m) {
    float c = cos (angle);
    float s = sin (angle);
    m[0][0] = x*x*(1-c)+c;
    m[0][1] = y*x*(1-c)+z*s;
    m[0][2] = x*z*(1-c)-y*s;
    m[0][3] = 0;
    m[1][0] = x*y*(1-c)-z*s;
    m[1][1] = y*y*(1-c)+c;
    m[1][2] = y*z*(1-c)+x*s;
    m[1][3] = 0;
    m[2][0] = x*z*(1-c)+y*s;
    m[2][1] = y*z*(1-c)-x*s;
    m[2][2] = z*z*(1-c)+c;
    m[2][3] = 0;
    m[3][0] = 0;
    m[3][1] = 0;
    m[3][2] = 0;
    m[3][3] = 1;
}

I don't know what else is relevant, so, if you're kind enough to lend me a hand on this and if I just don't present enough info, just say it.

Thank you for taking the time to read this question.

EDIT
The trouble I'm having is the following: If I do Rotate (180,0,0,0), the vertexes are inverted as intended but the resulting triangle (in this case) is smaller.

Screenshot:


texts: Has anyone successfully created a top down view of a stream/river? I need to also work out how to make it look like a boat is cutting through the water.


texts: Resources of realistic water simulation?

texts:
I want to study water simulation, with a  a demo with source code which using physically-based methods(Eulerian approaches or Lagrangian approaches).

How can I get some examples?


texts:
So working on a 2d fighting game and wondering whats a good method for detecting punch collision.  Ive got a few questions on how to implement the attack stuff.  Im using box2d (and Libgdx) for the movement and collision detection.

Best way to do punch and detection?  Currently thinking of creating a fixture on the body and destroying it after a little time with a Timer
How to do a multipunch combo, basically if they hit the button 3 times in a row it does a combo attack?  Think creating a variable that gets added +1 when they hit the button and a timer resets it back to 0 after a certain amount of time
Prevent attacks during the attack animation to prevent button jamming?  Currently using state status so need to figure out the best way to change the state to/from attacking


texts: How to load a separate map from a text file?

texts:
I have a text file that I am using for my map for the tiles to be allocated. This works fine, but I am running into issues figuring out how I would go about loading in a different part of the map.

For example, say I wanted the character to go into a cave or building, what would be a good way to go about loading this new area?

Right now I have my handler class setting the world in my game state class, and I have tried messing around in the game state class to try and accomplish what I want but have not had much success. In that game state class I have a tick and render method, and in the constructor I have it being set.

The methods that I have tried have resulted in a new map to be loaded in, but the other map is still loaded in under this, and I know this because the character has collisions set up. This also goes along with this issue, but what would be a good way to trigger this loading of the new section of the map?

Below is the code in my GameState class. (changeWorld is based off of the X coordinate when in game, and once you reach a certain point it switches maps; this was just done for testing because it is not an accurate way of doing it).

// Constructor...
    World1 = new Worlds(handler,"resources/Worlds/world1.txt");

    SpawnWorld = new Worlds(handler,"resources/Worlds/world2");

    if(Worlds.changeWorld() == false)
        handler.setWorld(World1);
    }
    else if(Worlds.changeWorld() == true) {
        World1=SpawnWorld;
        handler.setWorld(World1);
        entityManager.setPlayer(new Player (handler, 0,0));
    }
}//end contructor

public void tick() {
    if(Worlds.changeWorld() == false)  {
        World1.tick();
    }
    else if(Worlds.changeWorld() == true){
        World1=SpawnWorld;
        handler.setWorld(World1);
        SpawnWorld.tick();
    }
}//end tick

public void render(Graphics g) {
    if(Worlds.changeWorld() == false) {
        World1.render(g);
    }//end if
    else if(Worlds.changeWorld() == true) {
            World1=SpawnWorld;
            handler.setWorld(World1);
            World1.render(g);
    }
}//end graphics


texts:
I need to start a sprite at a scale .6 (scale1) at a y position 40 (yPos1). Knowing the end y position 560 (yPos2) and the end scale 1 (scale2):

How do I calculate the scale at various y positions between yPos1 and yPos2?


texts: How many "parallel units" does a GPU have?

texts:
I'd like to know how many parallel units for processing vertices a GPU has.

This Wikipedia page provides a GFLOPS and clock speed, for example for the Radeon 5850 "Broadway PRO", you get 1000 GFLOPS.  Assume running a vertex shader is 100 flops, then that means you can process 1000e9 / 100 = 10e9 vertices per second.

Is there a manufacturer published number of number of parallel processing units, or a way to know that number?


texts: How do I deal with collision resolution causing another collision?

texts:
I'm making a simple 2D, top-view simulation of an evacuation, sprites running around, looking for exits, going at it, all that good stuff.

I have no control over them when the simulation is running, I just program their behaviour.

I'm using the simulation space provided by JADEX, but I'm just using the simplest of what it provides, so it comes down to Java and OOP.

I already have collision detection working, each person has a radius and I search for objects within that radius, so my question is focused on the aftermath.

Say two people collide and one gets pushed to the ground while the other keeps going. No problem so far, but in the cicle after the collision they will again register a collision - since they are still close enough to each other - and trigger a confrontation.

Is there any general or already known technique to deal with this?

Or should I instead focus on another way of detecting a collision?

EDIT:

The expected cases are, when two people collide:

They are both up
One is up (D0) and the other one is down (D1).

In case 2, there are two outcomes:

D0 helps D1
D0 tramples D1

In case 1 there are 3 outcomes:

Both are aggressive. Dices are rolled, one keeps going the other one goes down and his physical condition deteriorates.
Both are non aggressive. Physical condition is compared, winner keeps going, loser is pushed but not to the ground, physical condition does not suffer.
Only one is aggressive. He will always be the winner. Rest as in 1).

As suggested, I will start by having people maintain a list of objects they just collided with and add an extra comparison to that list in the collision detection to filter them and also make sure that when they are no longer colliding to remove them from that list and see how far that takes me.


texts: How can I make my LibGDX game persist on android even if it's not the active activity

texts:
I want my android game using LibGDX to continue keeping track of events in the game, even while it's not the active window.

For example, I have a stat that reduces over time even, if the game is not the active activity. When the stat gets to a certain percentage, I want to push a notification to the android platform.

I found some information to push android notifications. However, I could not find one on how to make a stat persist in the game when a different app or activity is on the main screen.


texts: In Unity/UNet: How do you properly spawn a `NetworkPlayer`?

texts:
In Unity/UNet:
How do you properly spawn a NetworkPlayer? Right now, I'm doing it like this from inside a NetworkManager derived class:

   public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId) {
        NetworkPlayer newPlayer = Instantiate<NetworkPlayer>(m_NetworkPlayerPrefab);
        DontDestroyOnLoad(newPlayer);
        NetworkServer.AddPlayerForConnection(conn, newPlayer.gameObject, playerControllerId);
   }

This code snippet works pretty well and both clients can communicate with each other. However, there are a few little issues that arise only on the host:

In Unity's hierarchy-view on the host, there are only two NetworkPlayer instances. Shouldn't there be four NetworkPlayer instances on the host? Two client instances and two server instances? If so, do you have any ideas what could cause the missing NetworkPlayer instances?
The two NetworkPlayer instances have both, their isClient and isServer flags set to true. But only one of the has it's isLocalPlayer flag set. Now I wonder if this behavior is as intended? And if so, how do you distinguish between the client and the server instance of a NetworkPlayer?
Two player behavior: If the remote client sends a [Command] that changes a [SyncVar] on the server, then on the host, the [SyncVar]-hook is called only on the NetworkPlayer instance that represents the remote NetworkPlayer. The [SyncVar]-hook is not called on the host's "isLocalPlayer-NetworkPlayer" instance. Shouldn't the [SyncVar]-hook be called on both NetworkPlayer instances?

Any advise is welcome. Thank you!


texts: Check bounds in 2d platformer level transition

texts:
I have asked How camera works in 2d platformer in level transitions about camera transitions,
in the process I am stuck somewhere else.
I have a targetRoom that is 32 by 32 tiles:
// [x, y, w, h]
let mb = [0, 0, 32, 32];

// bounds
let targetRoom = {
  minX: mb[0] * bs.pxTileSize,
  maxX: (mb[0] + mb[2]) * bs.pxTileSize,
  minY: mb[1] * bs.pxTileSize,
  maxY: (mb[1] + mb[3]) * bs.pxTileSize
};

I have a player object:
let p = {
    x: 0,
    y: 0,
  onEdgeX: (p, bx) => {
    p.x = bx;
  },
};

I allow the player to move within these bounds:
this.checkEdgeX = (p) => {
  let { minX, maxX } = targetRoom;
  let cbox = absCBox(p);

  if (cbox[0] < minX) {
    p.onEdgeX(p, minX - p.cbox[0]);
  }
  if (cbox[0] + cbox[2] > maxX) {
    p.onEdgeX(p, maxX - p.cbox[0] - p.cbox[2]);
  }
};

p.cbox is players local collision box [x,y,w,h]. eg: [-6, -6, 12, 12];
absCbox returns the collision box in world coordinates:
const absCbox = p => {
  let cbox = p.cbox;
  return [
    p.x + cbox[0],
    p.y + cbox[1],
    cbox[2],
    cbox[3]];
};

In checkEdgeX when the collision box exceeds the limit,
p.onEdgeX is called which puts the player inside the bounds again.
The problem is, when I want player to go beyond the edge to the other level.
How do I check if the player is allowed to pass beyond the edge to the next level?
When player goes to the next level, how do I make sure it is within the bounds again?
Because player might go just a little bit to stand in between two levels, never meeting inside the bounds of either level.
I want the transition to be in the image in my linked question above.


texts: How to move/rotate different parts of an entity indepently from each other?

texts:
Background: I am playing around with a simple isomorphic 3D shooter where a player controls a character which can shoot other players. Here's an example scene where you can also see the hierarchy for the game objects and the controlling script:

As you can see, I have created a simple turret which consists of three parts:

Guns
Torso
Bottom

Just to be more clear, here's a screenshot of the turret close up with its armature:

In Unity, I have already created a simple PlayerController.cs script (see beloc) which allows a player to move the entire game object around using W, A, S, D and look using the mouse.

However, I want to rotate the Bottom independently. So if the Player moves left, the bottom should rotate towards that direction but the torso should still focus on the mouse position.

Now the first question is how I can do that. I don't know how to get access to the game objects and rotate them independently. The second question is how I can or should design the player game object s.t. I can exchange models more easily. What I mean by that is: Imagine the player switches the weapon. Obviously, only the guns should change but e.g. not the entire character. Only the mesh etc. should change dynamically.

I am sure this isn't that hard to accomplish but I couldn't find a simple example that kind of explains how to do it.

PlayerController.cs

public class PlayerController : MonoBehaviour
{

    [SerializeField]
    public float moveSpeed = 1f;
    private Vector3 _forward;
    private Vector3 _right;
    public LayerMask layerMask;

    // Start is called before the first frame update
    void Start()
    {
        this._forward = Camera.main.transform.forward;
        this._forward.y = 0;
        this._forward = Vector3.Normalize(this._forward);
        this._right = Quaternion.Euler(new Vector3(0, 90, 0)) * this._forward;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.anyKey)
        {
            this.Move();
        }

        this.MouseLook();
    }

    public void Move()
    {
        var rightMovement = this._right * Input.GetAxis("HorizontalKey");
        var upMovement = this._forward * Input.GetAxis("VerticalKey");
        transform.position += (Time.deltaTime * this.moveSpeed * Vector3.Normalize(rightMovement + upMovement));

        var heading = Vector3.Normalize(rightMovement + upMovement);
        if (Vector3.Magnitude(heading) > 0.0)
        {
            transform.forward = heading;
        }
    }

    void MouseLook()
    {
        Ray castPoint = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(castPoint, out hit, float.MaxValue, layerMask))
        {
            Vector3 direction = hit.point - transform.position;
            direction.y = 0.0f;
            transform.forward = Vector3.Normalize(direction);
        }
    }
}


texts:
I would like to get the shapes of my bodies, but I can't get anything, only null. Why?
Here is the relevant code section:

Body b;
while((b = box2d.physics.PhysicsWorld.world.getBodyList().getNext()) !=null) {
  Shape shape;
  while((shape = b.getShapeList().getNext()) != null) {

    Log.e("name",""+b.getUserData().toString()+" "+shape+" ");

    opengl.saveMatrix();
    Meshes.select(b.getUserData().toString())
              .translate((b.getPosition().x)*RATIO, (b.getPosition().y)*RATIO)
              .rotate((int) ((int) b.getAngle() * (180 / Math.PI)), 0, 0, 1)
              .draw(shape, 1, 1, 1);

    opengl.loadMatrix();

  }
}

shape = b.getShapeList().getNext() always returns null, and the log entry never ran.


texts:
I have written a custom lookAt function based on a lot of posts from all over the net, and it works very nice... except when a rotation (which is stored in a quaternion) crosses some 'threshold'. However, it works flawless when the camera's position is on the same horizontal plane as the model I'm lookingAt

On the below GIF, all I do is hold a key to lookAt the model together with a left arrow key to move the camera along the right vector:

My following understanding about how this function should look like (in a brief):

1 .Calculate a quaternion rotation needed to rotate an object from it's facing vector and a target vector.

1.a. Calculate an angle between those vectors by taking their dot product and a perpendicular axis by taking their cross product.

1.b Convert angle-axis info to a quaternion using this formula.

2 .Multiply the main quaternion rotation by the quaternion received above.

If I'm right, I believe that I may have a bug in my code, but I'm not sure. My code below:

lookAt: function(vec) {
    if (this.position.isEqual(vec)) {
        return;
    }
    this.rotation.multiply(new Quaternion().twoVecToQuat(this.rotation.getForwardVector(), this.position.sub(vec)));
    MVMatrix.setRotation(this.rotation.quaternionToMatrix());
},

// And the twoVecToQuat function based on Ogre3D quaternion library:

twoVecToQuat: function(v0, v1) {
    v0.normalize();
    v1.normalize();

    var dot = v0.dot(v1);
    // If dot === 1, vectors are the same
    if (dot >= 1) {
        return this.makeIdentity();
    }
    // If vectors are opposite
    if (dot < (1.0e-06 - 1)) {
        var fallbackAxis = new vec3().make(1, 0, 0);
        fallbackAxis.crossSelf(this);
        // If collinear, pick another vector
        if (Math.areScalarsSimilar(fallbackAxis.length(), 0)) {
            fallbackAxis.make(0, 1, 0);
            fallbackAxis.crossSelf(this);
        }
        fallbackAxis.normalize();
        this.axisToQuaternion(Math.PI, fallbackAxis);
    }
    else {
        var sDot = Math.sqrt((1 + dot) * 2);
        var invSDot = 1 / sDot;
        var tempVec = v0.cross(v1);

        this.x = tempVec.x * invSDot;
        this.y = tempVec.y * invSDot;
        this.z = tempVec.z * invSDot;
        this.w = sDot * 0.5;

        this.normalize();
    }

    return this;
},

UPDATE: Slin's solutions proved to be working (that one about calculating lookAt matrix), but I still don't know where is the bug in the quaternions library code. Working lookAt function below:

lookAt: function(at) {
    if (this.position.isEqual(at)) {
        return;
    }
    var zAxis = this.position.sub(at).normalize();
    var up = upVec(); // World's up vector instead of camera's up vector will unroll the camera
    var xAxis = up.cross(zAxis).normalize();
    var yAxis = zAxis.cross(xAxis);
    MVMatrix.make(
        xAxis.x,            xAxis.y,            xAxis.z,
        yAxis.x,            yAxis.y,            yAxis.z,
        zAxis.x,            zAxis.y,            zAxis.z,
        this.position.x,    this.position.y,    this.position.z);

    this.rotation.matrixToQuaternion(MVMatrix);
    this.copyEulerAngles();
},


texts: How to export unity project to play in HTC Vive?

texts: I have an Unity project which I want to export and use in HTC Vive. How do I do that and in addition is there any resource online which I can use to refer how do I code to use the controllers for HTC Vive?


texts:
I am making a voxel engine, and I want to make it possible to create and destroy voxels with the mouse. I use C++ and OpenGL, so C++ examples would be best.

So far, I have the camera position and appropriate angle as Vector3 values. I need to find voxels along a ray extending from the camera position along the angle. I tried to solve it myself, and essentially came up with a slow, 3D version of Bresenham's line. This would be okay, but it skips diagonals, meaning if I point toward the edge of a voxel, it usually misses.

The "bad" line skips over where the line crosses diagonals, while the good line hits them. I currently have the bad, but I want the good:

I have tried reading around this, but most of what I find relates to sparse octree rendering.


texts: How can I split my terrain into quads so that each quad would have a renderable vertex/index buffer? (DirectX11, C++)

texts:
I am creating a quad tree to store my terrain in chunks and currently have the implementation working to an extent.

I am currently starting with a grid of triangle pairs that make squares and splitting this down into quads. I have my vertices split into quads, but I'm struggling with the indices.

Here is how I generate the plane

snip

This gives me one list of indices, and one list of vertices. This is taken by the quadtree and split into different vertex lists and stored in different nodes. This works fine and the vertices seem to be correct, however I'm not sure how to create the indices for each vertex list as before I was doing it based on the height and width of the whole terrain. How would I create an indices list for each node in the quadtree or is there a better way to do this?

If I just use the whole list of indices for each node, I get weird results

Edit: There is an issue generating my plane, I am fixing this and seeing if it resolves my problem.

Edit: I have edited the topic title to something more suitable.

I have fixed my issue with the grid generation and I am using a smaller grid to make the issues more clear. I am using a 2x2 grid (9 verts, 24 indices, 8 tris) which is split into 4 quads (4 verts per quad, 2 tris per quad) and it's almost working, just a small issue with one of the sides.

I know this is potentially duplicating verts on a small scale, but on a larger scale with culling, this should actually save performance. Can anyone spot what's going on? Vertex issue? When splitting the quads, should it be by triangle, vertices, or indices? What happens if we split by triangle and a triangle overlaps 2 quads (although  this shouldn't happen)


texts: Why is my model rotating opposite direction around the Y axis?

texts:
I have a simple scenario. I have a simple scene, and in it I'm drawing a grid and a model, with some axis for orientation.

I noticed when I rotate the model about it's local Y axis, if I rotate the model clockwise, the vertices end up rendering as if they've been rotated counterclockwise. I can see this by rendering the model's local forward vector.

Here's a picture of what I mean. Initially, the world forward, local forward, and model all face the same direction.

However, after I begin rotating the object clockwise, I notice the "world forward vector" is rotating clockwise, but my model rotates counterclockwise?

When I export the model from Blender3D I use the coordinate system "Forward: -Z" and "UP: Y Up", which matches the RHS coordinate system I'm using in opengl.

When I "rotate the object", I mean I multiply the object's rotation matrix like so:

float constexpr angle = 1.0f;
glm::vec3 const axis = glm::vec3{0.0, 1.0, 0.0};
object.rotation = glm::angleAxis(glm::radians(angle), axis) * object.rotation;

Here's my vertex shader, I'm just multiplying the vertices by the MVP matrix.

vertex shader:

in vec4 a_position;
in vec4 a_color;

out vec4 v_color;

uniform mat4 u_mvpmatrix;

void main()
{
  gl_Position = u_mvpmatrix * a_position;
  v_color = a_color;
}

The rotation object.rotation 's initial value is the quaternion identity. Here's how I calculate the MVP matrix uniform value:

glm::mat4 const tmatrix = glm::translate(glm::mat4{}, this->translation);
glm::mat4 const rmatrix = glm::toMat4(this->rotation);
glm::mat4 const smatrix = glm::scale(glm::mat4{}, this->scale);
glm::mat4 const model_matrix = tmatrix * rmatrix * smatrix;

// camera_xyz are world-coords for the camera
// target_xyz is world-coords of the object
glm::vec3 const UP = glm::vec3{0.0f, 1.0f, 0.0f};
glm::mat4 const view = glm::lookAt(camera_xyz, target_xyz, UP);
glm::mat4 const projection = glm::perspective(fov, aspect_ratio, near, far);
glm::mat4 const mvp_matrix = projection * view * model_matrix;

Other relavent calculations:

glm::vec3 eye_forward() const { return forward_; }
glm::vec3 eye_up() const { return up_; }
glm::vec3 eye_backward() const { return -eye_forward(); }

glm::vec3 eye_left() const { return -eye_right(); }
glm::vec3 eye_right() const { return glm::normalize(glm::cross(eye_forward(), eye_up())); }
glm::vec3 eye_down() const { return -eye_up(); }

glm::vec3 world_forward() const { return forward_ * orientation(); }
glm::vec3 world_up() const { return up_ * orientation(); }
glm::vec3 world_backward() const { return -world_forward(); }

glm::vec3 world_left() const { return -world_right(); }
glm::vec3 world_right() const { return glm::normalize(glm::cross(world_forward(), world_up())); }
glm::vec3 world_down() const { return -world_up(); }

From what I can tell, it seems like I'm doing everything right. Can someone explain it to me? I also have a video showing this in more detail. This is important, because I move the object "forward" based on it's forward vector, so when I rotate the object and move it "forward" it's not moving in the direction it is facing.

edit: Am I calculating the "local forward" correctly with this calculation?

double edit:
I just noticed I labeled the "World" and "Object space" vectors backwards. The green arrow is the World forward vector (0, 0, -1) and the light blue is the object's local forward vector.

// forward_ is initialized with -Z (0.0, 0.0, -1.0)
glm::vec3 world_forward() const { return forward_ * orientation();
glm::quat const& orientation() const { return object.rotation; }


texts: Unity Custom Inspector Platform dependent property section

texts:
I want to make a custom inspector for one of my scripts that builds UI elements at runtime. This requires small changes to the default values depending on what platform I'm targeting. How do I add something that is similar to the graphics settings where there is a default option but each platform is able to override the
default setting for a platform specific value?

I'm looking for the same kind of thing that Unity has for the player settings (Edit -> Project Settings -> Player). This allows you to set the details for each one but you can override them for each platform if they need to be different.


texts: Material usage, one per model or per object?

texts:
Is it better (memory, time (of developer), space) to use single model that is unwrapped and uses a single material or to break a model down into appropriate bits, each with their own smaller texture/material?

Or does it depend on the target platform as to what is acceptable - ie PC vs tablet?

An example:
Say you have a typical house with a tiled roof.

Model it, make sure everything is attached, unwrap the walls/roof so in your UV template the walls and roof would be in one texture file, side-by-side in say a 512x512 file.
Model the roof/walls as separate objects, unwrap them individually and have two UV templates. You could then have a 256x256 file for each one.


texts: The question is about how to handle data about entities, but not particularly useful to the entity itself. An example of such data may be the external script that controls the entity's behavior or the path to the animation file — such data is gathered when loading the entity and is no longer useful until you save the game; it certainly doesn't belong in the entity object. Any tips on how to handle metadata?


texts:
I'm developing a game using Monogame and the last few days I've been trying to work with keyframe animations without no success so far.

I tried using both Xna Skinned sample from Microsoft and Better skinned sample from this site but still my characters get distorted as seem below:

(Not only my model distorts and only happens within the game, anywhere else is fine)

Both SkinnedSample from Microsoft or the Better Skinned sample  results in the same distortion.

Have any of you any clue of what (importer, processor or my own code) that could be causing this problem and what could be a solution for this?
My code is exactly like the Better Skinning sample mentioned above and uses the default SkinnedEffect.


texts:
I have to use this function to get a Surface of Revolution (homework).

newVertex = (oldVertex.y, someFunc1(oldVertex.x, oldVertex.y), someFunc2(oldVertex.x, oldVertex.y));

As far as I know (FIXME) Surface of Revolution means rotations of a (2D)curve around an axis in 3D.
But this vertex computing gives a 3D plane (FIXME again :D), so rotation of this isn't
obvious.

Am I misunderstanding something?


texts: Random number in a range, biased toward the low end of the range

texts:
I have an input of two values, let's say 1 and 10.
Lesser numbers should overall occur more often in the output than higher numbers, while there is a peak in the probability at #2:

1: very common
2: extremely common
3: very common
4: common
5: somewhat common
...
10: extremely rare

How do I achieve this? My code until now looks like this:

function getValue($min, $max) {
    return random($min, $max);
}


texts: How can I spawn objects in a volume without intersection?

texts: I am generating a 3D scene that involves spawning lots of 3D objects in a finite volume. I need to avoid intersection of objects.


texts: Proper way to divide a 2D climbing animation in Unity3D

texts:
I've got a 2D character that's going to climb up a 2D tile to his left or right and I've got a climbing animation consisting of three parts essentially:

Animation for the character going from walking onto the ground -> climbing on the wall
The actual climbing animation when on the wall
A "climbing over the top" animation for where the character pulls himself over the top of the wall and onto the ledge above.

What is the smoothest way to handle this in Unity? Do I need three separate animation clips for each of the steps, or can I do it with one and simply loop the middle section of the clip?

For example, my initial thought would be to have one clip for the entire animation and do the following:

play the first few "climbing onto the wall" frames when climbing onto the wall
loop the actual climbing animation while the character is on the wall and isn't ready to climb over the top
transition to the final few frames when the character is ready to pull himself over the top

Is this easily doable in Unity? Or is there an easier way to do this that I'm not thinking about? This seems a bit contrived and decently complicated so that's why I'm wondering.


texts: How to restore purchases made with virtual currency from the App Store? (iOS)

texts:
I want to award coins for doing thing in my app and let users purchase things with the coins that are non-consumables. I also want to let users purchase coins as IAPs.

How do I keep track of what has already been purchased between app reinstalls / new device installs?  I know that it's not required to share consumable purchases (coins) between devices.

Do I need to setup my own server to keep track?

Is it possible to do within the Apple ecosystem without the need for my own server?

Can I just use local storage and not worry about it?


texts: Why is my sprite displayed offset from its Box2D body?

texts:
I found out about this using a debug renderer. When the game starts, everything is in order. But when a collision happens, the sprite's rotation is way larger than its body. The sprite and body match when the body is completely horizontal.

The sprite's rotation origin seems far distant from where it should be. Here's my code:

Sprite sprite = data.sprite;
position = body.getPosition();
sprite.setPosition(
    position.x - sprite.getWidth()  / 2,
    position.y - sprite.getHeight() / 2
);
sprite.setOrigin(position.x, position.y);
sprite.setRotation(MathUtils.radiansToDegrees * body.getAngle());

As you can see, I am even trying to set center of its rotation with setOrigin without success. How can I fix this?


texts: Updating code at runtime, without recompiling

texts: Hey guys i was wondering if anyone has come across a c++ ide that you can actively play test the updates without having to recompile all the code.


texts:
I have a custom shader that uses 15 sampler2d. In Unity 5.5 the shader was working perfectly however since updating to Unity 5.6 I am getting the following error:

maximum ps_4_0 sampler register index (16) exceeded at line (on d3d11)

Compiling Fragment program with POINT
Platform defines: UNITY_ENABLE_REFLECTION_BUFFERS UNITY_USE_DITHER_MASK_FOR_ALPHABLENDED_SHADOWS UNITY_PBS_USE_BRDF1 UNITY_SPECCUBE_BOX_PROJECTION UNITY_SPECCUBE_BLENDING UNITY_ENABLE_DETAIL_NORMALMAP SHADER_API_DESKTOP UNITY_COLORSPACE_GAMMA

It appears that the update has added some new samplers. The only Unity post I have found on this is an issue ticket here: https://issuetracker.unity3d.com/issues/regression-5-dot-4-rtp-rtp-terrain-shader-rendering-is-broken-after-upgrading-project-to-5-dot-4

The instructions however are quite unclear and although they do mention that the custom shaders need to be changed manually to accommodate the new samplers, it's unclear exactly how this needs to be done in the shader code. I have tried to add the various suggested #define and #undefine tags as suggested, but the surface of my model is still pink and the error isn't fixed.

Any suggestions how to fix this?


texts: How to create plasma trail for spaceship

texts:
I have seen a lot of great looking space games that all use similar effects. I am really interested in finding out how some of these effects are generally done.

In particular I want to know how some of the trails behind spaceships or missiles are accomplished without using all the available resources.

For examples of the effect I mean see the screenshots for Gimbal, and even the video at that same link. Also the missile trails in Ether Vapor.

Are these both the same techniques? I am mainly interested in 2D, but I can't imagine it would be too different.

So how would I go about creating this kind of effect? Are we talking pixel-shaders, blendmodes/filters, bitmap effects, particle systems, or what? Not really platform specific. I am just looking for the theory, but specific examples or links would be great. And more detail the better.


texts:
I'm making a game in XNA and I want to limit the movement of a sprite to the screen boundaries.
How would I do this?

http://i.stack.imgur.com/ZqH0M.jpg


texts: Component based design, but components rely on each other

texts:
I've begun stabbing at a "Component Based" game system.

Basically, each entity holds a list of components to update (and render)
I inherit the "Component" class and break each game system into it.

Examples:
RenderComponent   - Draws the entity
MovementComponent - Moves the entity, deals with velocity and speed checks
DamageComponent   - Deals with how/if the entity gets damaged...

So, my system has this:
MovementComponent
InputComponent

Now maybe my design is off, but the InputComponent should say things like

if (w key is down)
    add y speed to movement

if (x key is down)
    Trigger primary attack

This means that the InputComponent sort of relies on these other components. I have to do something alone the lines of:

if (w key is down)
{
    MovementComponent* entityMovement = mEntity->GetMovement();
    if (entityMovement != NULL)
        add y speed to movement
}

which seems kinda crappy every update.

Other options? Better design? Is this the best way?

Thanks!