texts:
how am I suppose to apply friction to an object so that when I apply force it decelerates eventually to zero? Here are my physics objects:

Rigid Body "Sphere"

Collision shape: btSphereShape(0.50)
Mass: 1.0 kg
Restitution: 0.5
Friction: 10.0

Rigid Body "Platform"

Collision shape: btBoxShape( btVector3(23.0, 0.5, 23.0) )
Mass: 0.0 kg
Restitution: 0.75
Friction: 1.0

I apply central force of btVector3(0,0,-100) on key press 'W' to the sphere. The sphere moves but never stops. Is there anything else I should take into consideration? The sphere is not rolling (the force is to the center) and the damping cannot be used because it slows the object down on any force, even gravity.

What I have tried:

Added mass to the platform. I set linear and angular factors to (0,0,0) so the platform didn't move by any applied force.
Applied the negative of the total applied force. I get a working result but not how I wanted. If I had friction the object would slow down more realistically


texts:
This photo illustrates the environment: http://i.imgur.com/V4wbp.png

I'll shoot the cannon, it'll bounce off the wall and it's SUPPOSED to stick to the bubble. It does at pretty much every other angle.  The problem is always reproduced here, when hit off the wall into those bubbles. It also exists in other cases, but I'm not sure what triggers it.

What actually happens: The ball will sometimes set to the wrong cell, and my "dropping" code will detect it as a loner and drop it off the stage.

**There are many implementations of "Frozen Bubble" on the web, but I can't for the life of me find a good explanation as to how the algorithm for the "Bubble Sticking" works. **

I see this:
http://www.wikiflashed.com/wiki/BubbleBobble
https://frozenbubblexna.svn.codeplex.com/svn/FrozenBubble/

But I can't figure out the algorithims... could anyone explain possibly the general idea behind getting the balls to stick?

Code in question:

    //Counstruct our bounding rectangle for use
    var nX = currentBall.x + ballvX * gameTime;
    var nY = currentBall.y - ballvY * gameTime;
    var movingRect = new BoundingRectangle(nX, nY, 32, 32);
    var able = false;

    //Iterate over the cells and draw our bubbles
    for (var x = 0; x < 8; x++) {
        for (var y = 0; y < 12; y++) {
            //Get the bubble at this layout
            var bubble = bubbleLayout[x][y];
            var rowHeight = 27;

            //If this slot isn't empty, draw
            if (bubble != null) {
                var bx = 0, by = 0;

                if (y % 2 == 0) {

                    bx = x * 32 + 270;
                    by = y * 32 + 45;

                } else {
                    bx = x * 32 + 270 + 16;
                    by = y * 32 + 45;
                }

                //Check
                var targetBox = new BoundingRectangle(bx, by, 32, 32);
                if (targetBox.intersects(movingRect)) {
                    able = true;

                }
            }

        }

    }

   cellY = Math.round((currentBall.y - 45) / 32);

if (cellY % 2 == 0)
    cellX = Math.round((currentBall.x - 270) / 32);
else
    cellX = Math.round((currentBall.x - 270 - 16) / 32);

Any ideas are very much welcome.

Things I've tried:

Flooring and Ceiling values
Changing the wall bounce to a lower value
Slowing down the ball

None of these seem to affect it. Is there something in my math I'm not getting?


texts: Collision detection via adjacent tiles - sprite too big

texts:
I have managed to create a collision detection system for my tile-based jump'n'run game (written in C++/SFML), where I check on each update what values the surrounding tiles of the player contain and then I let the player move accordingly (i. e. move left when there is an obstacle on the right side).

This works fine when the player sprite is not too big: Given a tile size of 5x5 pixels, my solution worked quite fine with a spritesize of 3x4 and 5x5 pixels.

My problem is that I actually need the player to be quite gigantic (34x70 pixels given the same tilesize). When I try this, there seems to be an invisible, notably smaller boundingbox where the player collides with obstacles, the player also seems to shake strongly. Here some images to explain what I mean:

Works:
Doesn't work:
Another example of non-functioning:   (the player isn't falling, he stays there in the corner)

My code for getting the surrounding tiles looks like this (I removed some parts to make it better readable):

std::vector<std::map<std::string, int> > Game::getSurroundingTiles(sf::Vector2f position)
{
    // converting the pixel coordinates to tilemap coordinates
    sf::Vector2u pPos(static_cast<int>(position.x/tileSize.x), static_cast<int>(position.y/tileSize.y));
    std::vector<std::map<std::string, int> > surroundingTiles;

    for(int i = 0; i < 9; ++i)
    {
        // calculating the relative position of the surrounding tile(s)
        int c = i % 3;
        int r = static_cast<int>(i/3);
        // we subtract 1 to place the player in the middle of the 3x3 grid
        sf::Vector2u tilePos(pPos.x + (c - 1), pPos.y + (r - 1));

        // this tells us what kind of block this tile is
        int tGid = levelMap[tilePos.y][tilePos.x];

        // converts the coords from tile to world coords
        sf::Vector2u tileRect(tilePos.x*5, tilePos.y*5);

        // storing all the information
        std::map<std::string, int> tileDict;
        tileDict.insert(std::make_pair("gid", tGid));
        tileDict.insert(std::make_pair("x", tileRect.x));
        tileDict.insert(std::make_pair("y", tileRect.y));

        // adding the stored information to our vector
        surroundingTiles.push_back(tileDict);
    }

    // I organise the map so that it is arranged like the following:
    /*
     * 4 | 1 | 5
     * --  -- --
     * 2 | / | 3
     * --  -- --
     * 6 | 0 | 7
     *
     */
    return surroundingTiles;
}

I then check in a loop through the surrounding tiles, if there is a 1 as gid (indicates obstacle) and then check for intersections with that adjacent tile.

The problem I just can't overcome is that I think that I need to store the values of all the adjacent tiles and then check for them. How? And may there be a better solution?
Any help is appreciated.

P.S.: My implementation derives from this blog entry, I mostly just translated it from Objective-C/Cocos2d.


texts: In unity, how do I rotate a vector in relation to the player?

texts:
I am making a radar script in a unity FPS game project I am making for class. I already have a working example of a radar script that works in relation to the player's position. However the rotation is in relation within the world map, not the player's view.

In code I have it kinda like this (not actually my code, as I don't have it with me right now, but basically the same algorithm)

if (isPlayerInViewRange(otherPlayer[i]){
    //these are both normalized Vector
    dir = getDirectionFromPosition(player, otherPlayer);
    dir = rotateDirectionInRelationshipToPlayer(player, dir); //problem here
    dir = new Vector3(dir.x, dir.z, 0);

    dir.Scale(MapToRadarPosition, 0, MapToRadarPosition);
    radarDot[i] = dir;
    radarDot[i].setActive(true);
} else {
    radarDot[i].setActive(false);
}

Any ideas what I am missing, I feel like I am missing some obvious function to do it.


texts: Is there any working C++ source code for a lightmap generation algorithm using Radiosity or any other GI system? I've found technical papers only, but I can't really find any implementation.


texts:
I'm trying to implement Heap into my A* algorithm, However I'm having trouble with implementing one method. The Contains method. Which checks if the heap array has a specific node in it or not. I don't know how to implement that. If I just make a for loop and check every item in the heap that would be very very slow and defeat the purpose of a heap.

So my question is, How do you check if an item exist in a OpenSet of type Heap? What is the fastest way to do it?

This is my heap code:

namespace AI
{
public interface IHeapItem<T> : IComparable<T>
{
    int HeapIndex { get; set; }
}

class Heap<T> where T : IHeapItem<T>
{
    T[] Items;
    int count;
    public int Count { get { return count; } }

    public Heap(int MaxSize)
    {
        Items = new T[MaxSize];
    }

    public T this[int Index]
    {
        get
        {
            if (Index > count)
                Index = count - 1;

            return Items[Index];
        }

        set { Items[Index] = value; }
    }

    public void Push(T Item)
    {
        Item.HeapIndex = count;
        Items[count] = Item;
        SortUp(Item);
        count++;
    }

    public T Pop()
    {
        T FirstItem = Items[0];
        count--;
        Items[0] = Items[count];
        Items[0].HeapIndex = 0;
        SortDown(Items[0]);
        return FirstItem;
    }

    public bool Contains(T Item)
    {

    }

    void SortDown(T Item)
    {
        while (true)
        {
            int LeftChildIndex = Item.HeapIndex * 2 + 1;
            int RightChildIndex = Item.HeapIndex * 2 + 2;
            int swapIndex = 0;

            if (LeftChildIndex < count)
            {
                swapIndex = LeftChildIndex;

                if (RightChildIndex < count)
                    if (Items[LeftChildIndex].CompareTo(Items[RightChildIndex]) < 0)
                        swapIndex = RightChildIndex;

                if (Item.CompareTo(Items[swapIndex]) < 0)
                    Swap(Item, Items[swapIndex]);
                else
                    return;
            }
            else
                return;
        }
    }

    void SortUp(T Item)
    {
        int ParentIndex = (Item.HeapIndex - 1) / 2;

        while (true)
        {
            T ParentItem = Items[ParentIndex];
            if (Item.CompareTo(ParentItem) > 0)
                Swap(Item, ParentItem);
            else
                break;

            ParentIndex = (Item.HeapIndex - 1) / 2;
        }
    }

    void Swap(T ItemA, T ItemB)
    {
        Items[ItemA.HeapIndex] = ItemB;
        Items[ItemB.HeapIndex] = ItemA;
        int itemAIndex = ItemA.HeapIndex;
        ItemA.HeapIndex = ItemB.HeapIndex;
        ItemB.HeapIndex = itemAIndex;
    }
}
}


texts:
Okay, so this is where I am now. My game largely consists of textures drawn through spritebatch. Now I have to draw a dynamic number of triangles. I cannot say in advance where or how many I have to draw, because I have to generate their positions on the fly. The number will never top 3-400 though, and is often much lower.

When testing though, I noticed that at random moments the game became a bit laggy. I'm quite confident the vertex-drawing was the problem, if I commented it out, the lag was gone.

This is the code I have currently (I removed as much clutter as possible):

// loop through the grid
    VertexPositionColor[] vertices;
    int vertexcounter = 0;

    RasterizerState state = new RasterizerState();
    state.CullMode = CullMode.None;

    for(int i = startx; i < endx; i++)
        for (int j = starty; j < endy; j++)
        {

            //////
            vertices = new VertexPositionColor[3];
            vertexcounter = 3;
            vertices[0] = new VertexPositionColor(Vector3.Zero, Color.Black);
            vertices[1] = new VertexPositionColor(new Vector3(width / 2, 0, 0), Color.Black);
            vertices[2] = new VertexPositionColor(new Vector3(0, height / 2, 0), Color.Black);
            //////

            // Create a buffer to use
            vertexBuffer = new VertexBuffer(device, typeof(VertexPositionColor), vertexcounter, BufferUsage.WriteOnly);
            vertexBuffer.SetData<VertexPositionColor>(vertices);

            // Draw the triangles
            basicEffect.World = world;
            basicEffect.View = view;
            basicEffect.Projection = projection;
            basicEffect.VertexColorEnabled = true;

            device.SetVertexBuffer(vertexBuffer);
            device.RasterizerState = state;

            foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
            {
                pass.Apply();
                device.DrawPrimitives(PrimitiveType.TriangleList, 0, vertexcounter / 3);
            }

            vertexcounter = 0;
            vertexBuffer.Dispose();
        }

Again, I removed as much clutter as possible. The basicEffect and matrices are created in the constructor. The for loop doesn't really make sense probably, but the part between the ////'s used to be for retrieving the vertices from objects in a grid (which is what the coordinates were for).

As you can see I removed that part and instead draw one single triangle. The game still lags though, so I think I'm doing something else wrong. Are you not really supposed to create VertexBuffers on the fly? Or am I forgetting to dispose of certain data?

Also, maybe it is worth noting that this is done in the Update part of the object. This is because the image is drawn to a RenderTarget, and in my project it's just more convenient to do it in the Update method.

Thanks in advance :)


texts: How to prevent Rigidbodies with restricted movement from clipping

texts:
My player is a rigidbody cube with a box collider that can push other "NPC" rigidbody cubes that also have a box collider. These NPC cubes have restricted movement either in horizontal or vertical direction. If the player pushes a cube that can only move horizontally into a cube that can only move vertically, the cubes start clipping. I recorded the whole situation in this video. Note that the NPC cube on the left has frozen X position, while the one on the right has frozen Z position.
I know that one way of preventing this would be to increase the mass of the NPC cubes, but that would only resolve the problem proportionally to the increased mass (the higher the mass, the lower the clipping), and at some point my player is not strong enough to move the NPC cubes anymore.
How can I solve this?


texts: How to determine size of art assets for Unity UI?

texts:
Previously when I made games, I used ui assets from the asset store. Working with those assets was easy as the backgrounds were plain. However, I'm now working on a game where custom graphics are used for UI. So, I need to specify size of backgrounds,icons etc to the art team. I understand how aspect ratio works with regards to unity camera, but having trouble understanding the relation between camera size and Canvas. For example, for a camera size of 4.6, an image size of 517X920 will cover the whole screen in 9:16 aspect. However, the same image is considerably larger when used as UI image under the Canvas.
Can someone please help me understand how Canvas deals with image sizes?


texts: How can I optimise a Minecraft-esque voxel world?

texts:
I found Minecraft's marvelous large worlds extremely slow to navigate, even with a quad core and meaty graphics card.

I assume Minecraft's slowness comes from:

Java, as spatial partitioning and memory management are faster in native C++.
Weak world partitioning.

I could be wrong on both assumptions. However, this got me thinking about the best way to manage large voxel worlds. As it is a true 3D world, where a block can exist in any part of the world, it is basically a big 3D array [x][y][z], where each block in the world has a type (i.e BlockType.Empty = 0, BlockType.Dirt = 1, etc.)

I assume that to make this sort of world perform well, you would need to:

Use a tree of some variety (oct/kd/bsp) to split all the cubes out; it seems like an oct/kd would be the better option, as you can just partition on a per cube level not a per triangle level.
Use some algorithm to work out which blocks can currently be seen, as blocks closer to the user could obfuscate the blocks behind, making it pointless to render them.
Keep the block object themselves lightweight, so it is quick to add and remove them from the trees.

I guess there is no right answer to this, but I would be interested to see peoples' opinions on the subject.  How would you improve performance in a large voxel-based world?


texts: How to implement ECS architecture in C#?

texts:
As C# is a strongly-typed language, I'm  having great difficulties associating all my data types together so that I can have a clean, if not performant, game loop.

Example #1: Keeping Components Together

Keeping components together means I need an interface or base class to store them in an array, which would require keeping track of each type separately so that it can be converted back to the derived type before being consumed. The constant type conversion seems like a bad idea in an ECS?

To compound the problem, I would prefer to use structs instead of classes for my components, which when cast to an interface will cause boxing. In some simple stop watch tests I've run it seems the casting/boxing is 16x slower than just looping over the raw type. (Pseudo code below)

IComponent sprite = new SpriteComponentStruct() // boxing

for(int i=0; i<iComponents.Length; i++)
{
    var type = GetComponentTypeByIndex(i);
    var system = GetSystemWithType(type);
    SpriteComponent sprite = Convert.ChangeType(...);
    system.Execute(sprite);
}

Example #2: Keeping Components Separate

To keep components separately in their own classes/managers/systems I would likely need a generic class to cut down on the code duplication. The problem I run into here is that looping over each class will require a base class or interface, which at the very least would force me to cast the component types again. (Pseudo code below)

ComponentManager<T>() where T : struct
{
    T[] components;

    // can't use with non-generic interface to put manager into a list
    public void AddComponent(T component) {...}

    // won't compile; type "T" will not cast to type "T"
    public void AddComponent<T>(T Component) {...}

    // requires casting and/or boxing, which defeats
    // the purpose of keeping components separate
    public void AddComponent(object component) {...}

}

It seems every which way I try to implement a ECS in C# ends with hacky/non-performant code, that's assuming I can get it to compile in the first place. From studying other ECS systems around the net, it seems some side-step these issues by using void/int pointers or storing component bytes directly in memory (like I believe the new ECS in Unity 2018 does). Either way those are unsafe operations in what's supposed to be a managed memory language.

So is C# the wrong tool for the job? Am I approaching this incorrectly? I'd love to hear some opinions as this just seem impossible...


texts: Projecting world coordinates to screen coordinates issue - points disappear when origin not in view

texts:
I am trying to implement a 2d line drawing effect on a 3d mesh using Ogre. In order to do so, I perform silhouette detection on the lines of the object (this works) and then project these lines from world to screen coordinates.

Here is the code I use for converting the coordinates:

            bool toDeviceCoordinates(Ogre::Vector3 &result, Ogre::Vector3 &point,Ogre::Camera *camera)
            {
                if(!camera->isVisible(point))
                {
                    return false;
                }
                Ogre::Vector4 p(point.x,point.y,point.z,1);

                p = camera->getViewMatrix()*p;
                p = camera->getProjectionMatrix()*p;

                result = Ogre::Vector3(p.x,p.y,p.z);
                result /= p.w;

                return true;
            }

To draw these points to the screen I just pass them through the shader like so:

            gl_Position = gl_Vertex;

This works fine except when the origin of the scene is not visible.

Any idea where I am going wrong?


texts: How big a transition from programmer to modeler/level designer/creator

texts:
So I think I may take a break from the programming side, I have put in 6 hard months learning C++ and graphics theory, I have learned a huge amount but over the last few days have been studying level design and modeling and think that is maybe more suitable to me.

So how would programming compare in a learning curve sense, C++ takes a while to grasp the core language never mind writing 100,000s lines of game engine code which you would eventually have to do.

Without being arrogant the modeling/level creation side seems a much faster progression, is that a fair thing to say?


texts: Why the MoveTowards make the transform moving nonstop?

texts:
In the Update in the else part, I'm trying to move the transform up from its current position on the exit more up by offset.
When the flag bool exit is true I want the transform to move up more by the offset for example if the offset is 7 then move up on the Y more 7. but it's moving up non-stop.
I tried to like this with exitPosition variable for storing at exit: but still, it's moving up non-stop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Testing : MonoBehaviour
{
    public float speed;
    public float offset;

    private bool exited = false;
    private Vector3 exitPosition;

    private void Start()
    {
        Debug.Log("Position : " + transform.position);
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.name == "Cube")
        {
            Debug.Log("Exited !");
        }

        exitPosition = new Vector3(transform.position.x,
                transform.position.y + offset, transform.position.z);

        exited = true;
    }

    private void Update()
    {
        if (!exited)
        {
            transform.position += Vector3.up * speed * Time.deltaTime;
        }
        else
        {
            transform.position = Vector3.MoveTowards(transform.position, exitPosition, speed * Time.deltaTime);
        }
    }
}


texts:
I'm making a mobile game and had the idea of using transfer codes for taking one account to another device.

Lately, I've seen this function being used in a lot of mobile games, you go to the game settings, issue a transfer code, input it in the new device and the game account is transferred. However it's not clear for me as to how this works? since many games I have seen with this function can't transfer premium currency between different OS, for example. Or some of them, after transferring the game disable the old device from transferring back the same account before certain time has passed.

I have been looking for some information about this system but haven't been able to find out anything. So I was hoping if anyone could point me into the right direction, specially in the point about currency transfer between different OS.

Edit: I'll try to be a little more clear about the issue. I want to have a feature where the user cas generate a code to transfer his account or progress to another device, that's it.

The other question I had was because this kind of systems do exist actually. Mostly on games developed in Asia. They allow you to transfer your progress this way to any other device BUT if you do this from one OS to another normally you can keep your progress intact but not the in-game currency. So I was wondering why


texts: How to make an object move again after being stopped by collision in Unity?

texts:
I have a player object which position is always centered on the main camera's viewport. This object has a Rigidbody 2D, a box and circle collider. The player moves around a level, the level has a polygon collider attached.

I move the camera until the object hits against the collider, which stops the movement of the camera by setting its speed to 0. The problem happens when I want to move the camera / player object away from the collider. As the speed is already at 0, it cannot move away from the collider.

The script attached to the player object, checks for collisions and applies the speed to 0 on the main camera's test script.

using UnityEngine;
using System.Collections;

public class move : MonoBehaviour {
public float speed;
public test testing;
// Use this for initialization
void Start () {
     speed = 10F;
    testing = Camera.main.GetComponent<test>();
}

// Update is called once per frame
void FixedUpdate () {
    Vector3 p = Camera.main.ViewportToWorldPoint(new Vector3(0.5F, 0.5F, Camera.main.nearClipPlane));
    transform.position = new Vector3(p.x, p.y, -1);

}

void OnCollisionEnter2D(Collision2D col) {

    testing.speed = 0;

}
void OnCollisionExit2D(Collision2D col) {

    testing.speed = 10F;

}

}

This is the script attached to the main camera; just a simple script that changes the camera's position.

using UnityEngine;
using System.Collections;

public class test : MonoBehaviour {
public float speed;
public float translationY;
public float translationX;
// Use this for initialization
void Start () {

    speed = 10F;
}

void FixedUpdate () {
     translationY = Input.GetAxis("Vertical") * speed * Time.deltaTime;
     translationX = Input.GetAxis("Horizontal") * speed * Time.deltaTime;

    transform.Translate(translationX, translationY, 0);
}

}

The player object isn't kinematic and is a fixed angle, the colliders aren't triggers and the polygon collider isn't a trigger either.

The player is the red square, the collider is the pink area.

-- EDIT --

From the latest change the collider set up for the player

So if the X speed was disabled. It wouldnt move into the side of the polygon colider which is good, but yet you couldnt move away from it. And moving down would move inside the colider.


texts: Does pausing the canvas draw restores the FPS to higher value in a HTML5 game?

texts:
I set Frame Per Second of 60 for my game. But after 1 minute it gets to a significantly lower value - around 8 FPS.

Does pausing the canvas drawing restores the FPS to higher value? If it does, how much time is enough to pause the game in order to get 60 FPS again?


texts: Why does Unity call certain methods "messages"?

texts:
I just surprised that the Unity documentation calls methods like Update or Start or Awake "Messages" rather than methods.

Does that mean those methods are used to send a message to something?


texts: Techniques for incorporating physics engines like Box2D into a Component-based Entity System

texts:
Currently i'm working with my own physics engine, however given the fact that the emscripten ports have gotten incredibly good, i wanted to try and incorporate Box2D into my entity system for the next project (and Bullet for future ones). Currently though, my own physics engine works on components directly, like Position (x, y), Dynamic (mass, velocity, drag) or Collidable (friction, restitution), which allows the user to pick an choose what kind of a body the entity is dynamically and fiddle with the variables directly, this isn't possible with Box2D, so i'll somehow have to create a component out of the Box2D objects.

Do you guys have any experience with this? Incorporating OOP engines like Box2D or Bullet seems daunting when i try to think about it, for example the physics component would hold the position, so my rendering system would require a physics component, which isn't desirable, since not every sprite i render is a physics object, etc. To solve issues like these, i thought about just creating a Position component and having the rendering system hold entities with a Position or Box2DBody and Sprite components, but i'm not sure if this is the most robust solution. I'd love to hear some input from people that have experience with these things.

EDIT: This isn't just for Javascript, the question should be language agnostic.


texts: How can I manage resources in memory, and dispose of them at appropriate time with the Ashley framework?

texts:
I have been working on libGDX and the Ashley framework, and I have not been able to find any information on resource control in memory.

I would like to know if there is any way to control those entities that are in memory before and after closing the application or change the screen. Mainly to add the dispose() methods where necessary to avoid unnecessary resources loaded into memory.


texts: Getting access violation because of ID3D11Buffer

texts:
I try to create a simple class store my model variables vertex array and vertexbuffer. So I create an array of myclass to create and manage object dynamically. But when

 hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &pieces[counter].g_pVertexBuffer);

this line run I get the error "Access violation reading location". I try to many things but I never success. If I don't use class and array I don't get this error. Porgram runs without error.

MyClass:

class Piece
{
public:
  double positionX, positionZ,
    red, green,blue;
  bool renderable;
  int type, color, vertexCount;
  XMMATRIX g_WorldPieces;
  ID3D11Buffer* g_pVertexBuffer;
  SimpleVertex* vertices;
  Piece();
  void create(int, int, double, double);
};
Piece::Piece()
{
   g_pVertexBuffer = NULL;
}
 void Piece::create(int t, int c, double pX, double pZ)
{
   g_pVertexBuffer = NULL;
   renderable = true;
   type = t;
   color = c;
   red=green=blue=0.0f;
   if(color == 1)
     red=green=blue=1.0f;
   positionX = pX;
   positionZ = pZ;
   vertexCount = 0;
}

  Piece *pieces;//Global variable which define after defining "ID3D11Device*                       g_pd3dDevice = NULL"

and using objects of myclass:

for(int x=0;x<4;x++)
{
if(x==2)
{
    c=0;
    positionZ = 12.5;
}

for(int y=0;y<8;y++)
{
    pieces[counter].create(typeArray[x][y],c,positionX,positionZ);
    positionX += 5;
    switch(pieces[counter].type)
    {
         //Switching object txt. All cases and breaks are fine.
    }
    fin >> pieces[counter].vertexCount;
    pieces[counter].vertices = new SimpleVertex[vertexCount];
    for(int i=0; i<vertexCountpiyon; i++)
    {
        fin >> pieces[counter].vertices[i].Pos.x >> pieces[counter].vertices[i].Pos.y >> pieces[counter].vertices[i].Pos.z;
        fin >> pieces[counter].vertices[i].Tex.x >> pieces[counter].vertices[i].Tex.y;
        fin >> pieces[counter].vertices[i].Normal.x >> pieces[counter].vertices[i].Normal.y >> pieces[counter].vertices[i].Normal.z;
    }
    fin.close();
    bd.ByteWidth = sizeof( SimpleVertex ) *pieces[counter].vertexCount;
    ZeroMemory( &InitData, sizeof(InitData) );
    InitData.pSysMem = pieces[counter].vertices;
    hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &pieces[counter].g_pVertexBuffer);//THIS LINE IS MY PROBLEM!
    if( FAILED( hr ) )     return hr;
    counter++;
}
positionX = -17.5;
positionZ += 5;
}

When I get access violation counter is 0.

Source code of my project: http://1drv.ms/1nKdoUf


texts: OpenGL: Does it make sense to use an Index Buffer With GL_TRIANGLE_FAN?

texts:
When trying to draw circles in webGl (You can answer the question even in openGl terms, I'll understand both), I came across the TRIANGLE_FAN flag when calling either glDrawArrays (with only a vertex buffer) or glDrawElements (with a vertex and index buffer). Since TRIANGLE_FAN expects the first point to be the 'hub" or "center" of the polygon and all other points are the outside points.
      So, the first thing that came to mind is to break out of my index buffer habit, as there seems not to be a lot of data that can be saved. But, does it make sense to use an index buffer in my case? Can you even use one? Which one saves more data and is more efficient? Any feedback would be appreciated.
- Thank you


texts: Do I need any knowledge of Objective C to port a game to iOS using Unity3D?

texts:
I have no experience with Objective-C and I know iOS simply as a user of iphone and ipad devices.

Now, I know that Unity3D can port my game to iOS without needing to know Objective C (that's what their docs say). But is it as simple as that? Click to compile, then use distribution profile and upload binaries to iTunes - as simple as that?

I need to know if should I start this process and publish my game this way. I am afraid that I may come across platform-dependent things (like when I code in cocoa-2dx using C++ and I come across hardware specific things).

If anyone has such experience, I would appreciate they share it with me.


texts: How to make an event happen only at the first start of the game?

texts:
I want to know how to make something happen only once like a tutorial in a game which appears only when you first start your game and then when your game got saved to a further point it never appears again even when you close your game and start again.

I want to give players some amount of gold when they first got their hands on my game ... but I do not want to give them that again and again whenever they restart the game ...

So I want to know how to make something happen only once in a game application..

I hope you get my point ... thanks ..


texts: Why when saving a game it's writing the saved game only if I leave the editor window and then coming back?

texts:
It's not saving in runtime for some reason.  Only when I stop the game and only when leaving the editor window then when coming back to the editor window I see it's writing the saved game file on the hard drive.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public static class SaveSystem
{
    private static readonly string SAVE_FOLDER = Application.dataPath + "/Saved Games";
    private static string content;

    public static void Init()
    {
        if (!Directory.Exists(SAVE_FOLDER))
        {
            Directory.CreateDirectory(SAVE_FOLDER);
        }
    }

    public static void Save(string saveString)
    {
        string fileName = Path.Combine(SAVE_FOLDER, "savegame.txt");
        File.WriteAllText(fileName, saveString);
    }

    public static void Save(string SaveString, string FolderToSave, string FileName)
    {
        if (!Directory.Exists(FolderToSave))
        {
            Directory.CreateDirectory(FolderToSave);
        }

        string fileName = Path.Combine(FolderToSave, FileName);
        File.WriteAllText(fileName, SaveString);
    }

    public static string Load()
    {
        content = "";
        string fileName = Path.Combine(SAVE_FOLDER, "savegame.txt");

        if (File.Exists(fileName))
            content = File.ReadAllText(fileName);

        return content;
    }

    public static string Load(string FolderToLoadFrom, string FileName)
    {
        content = "";
        string fileName = Path.Combine(FolderToLoadFrom, FileName);

        if (File.Exists(fileName))
            content = File.ReadAllText(fileName);

        return content;
    }
}

It should make the whole saving and writing the file in runtime.


texts: Why is my canvas being rendered underneath everything?

texts:
I'm currently trying to implement a UI that will overlay a scene and follow a scene's main camera, but I'm running into some issues. When I set canvas's mode to Screen Space - Camera, the Z position of the canvas is always set to 89.5, which is behind all of the objects that are generated into my scene, making the canvas and the UI elements on it completely invisible to the player.

This is the game preview before running the game, with the UI elements clearly visible:

This is the game while it's running in the editor, with the UI elements not visible at all:

This is what my hierarchy looks like:

This is what the properties for the canvas look like:

Why is my UI not visible when I run my game? How can I fix this?


texts:
How to make an Area2D drawn after another one only in certain situations?

The boat
+ Area2D
|_ AnimatedSprite

The stone
+ Area2D
|_ AnimatedSprite

Correct

Not correct

Do I have to use 3D?


texts: How can I record and replay axis input accurately for testing?

texts:
I want to do integration testing for an old C#/Unity project. The project uses its own input system, so I can't use inputEventTrace or any other convenient Unity class. So I subscribed a new game object to the custom input system so that it records any input detected in each frame.
But when I replay, because of the difference in frame times, the replays are not quite equal to the original playthrough (especially because of the axis input). My understanding is that input in Unity is not event-based, so I can't think of any way to perfectly mimic the input given different frame times. Does anyone know of a way to do this?


texts: Mario like jumping and landing in box2d, help

texts:
I've been trying to get Mario type jumping/landing in a Box2d game and it's been giving me some trouble.

Results: Player loses velocity on landing

Desired Results: When player lands it will continue at the same velocity it was in the air.

[edit] Player loses velocity on impact, but quickly regains its set max speed.

I know this is an issue with friction and I've tried setting the friction to 0 when the user is pressing Left and Right movement keys and back to normal friction when the player is not pressing those keys. This however, does not work as the state does not get changed until the collision is over and the player will be stuck sliding until the collision state has changed.

My next best guess is to set friction to zero all together for the player and simulating an opposing force on the player.

Solution? Tips? Heck... maybe there's a tutorial out there I missed.

Thanks in advance.

Example
http://www.guioui.com/saxattack/box2d_landing.png

        Vector2 a = entityBody.getLinearVelocity();
        float force = 0;

        if(Gdx.input.isKeyPressed(Keys.D)){
            if(a.x < 5) force = 25;
            //entityBody.getFixtureList().get(0).setFriction(0);
            //floor.entityBody.getFixtureList().get(0).setFriction(0);
            //entityBody.resetMassData();

            //entityBody.applyLinearImpulse(new Vector2(0f,1f), entityBody.getWorldCenter());
            //entityBody.applyForce(new Vector2(0f,50f), entityBody.getWorldCenter());
        }
        else if(Gdx.input.isKeyPressed(Keys.A)){
            if(a.x > -5) force = -25;
            //entityBody.getFixtureList().get(0).setFriction(0);
            //floor.entityBody.getFixtureList().get(0).setFriction(0);
            //entityBody.resetMassData();

            //entityBody.applyForce(new Vector2(0f,50f), entityBody.getWorldCenter());
        }
        else{
            entityBody.getFixtureList().get(0).setFriction(.4f);
            floor.entityBody.getFixtureList().get(0).setFriction(.4f);
        }

        if(Gdx.input.isKeyPressed(Keys.W)){
            a.y = 5;
            entityBody.setLinearVelocity(a);
        }

        entityBody.applyForce(new Vector2(force, 0), entityBody.getWorldCenter());


texts: How do I implement corner correction in a platformer?

texts:
I'm writing a platformer in Unity and I'm trying to make it so that when the player jumps up to a ledge but barely misses (imagine they hit their toe on the ledge, or maybe even their foot, I'll play with the values) they are nudged up onto the ledge instead of not making the jump (as it is now in my game). There's a thread showing that Celeste does this in a few ways here.

My player character uses a dynamic Rigidbody2D and I move the character by setting the velocity directly.


texts: How can I implement a futuristic "barrier field" that reacts to hits?

texts:
I want to implement a "shield" that reacts to projectile hits. Currently, my colliders are mapped to the animated sprite's outline on all frames.

I'm looking for something like the image below. For example, what shader could I use?


texts:
I would very much like to host my monogame window inside a Form so that I can take advantage of the nice gui elements in the C# framework when creating a simple level editor. I have looked online, but I am unable to find any working examples on how to do it. What is the state of this? Is it possible? I am using window 8.

Regards,


texts: Game Maker Studio 2, Shaders not working as intended in webbrowsers on mac

texts:
The shader output of my html5 game in Game Maker Studio 2 looks wrong on  webbrowsers on MacOS. Sometimes the shaders lack completely and at other times the shader colors look completely different. How can I make the shaders work like they are intended to for safari webbrowsers?

See images below:

Mac webbrowser lacking shaders on squares

Other browsers not lacking shaders on squares

Mac webbrowser  different color hexagon

Other browsers intended colors


texts: How can I modify a static humanoid asset?

texts:
I am new to Unity 3D. I bought an asset from the Unity Asset Store recently. It came in a "walking" stance. I was wondering if it was possible to modify this stance to become fully supine; so can I modify the legs so that they are straight and next to each other?

I am not sure if I can do this or not in Unity, or if I have to download Blender or Maya to do this.

I have already tried forcing a stance change, through vertex snapping, but I am not having any luck with that. I have also tried editing the Character Joint settings, but I think that is if I wanted to animate the model, which I don't.

This is what my character looks like currently:

I edited the character as per DMGregory's suggestion, but I am having trouble reimporting it back into my scene:


texts: How can I move number of objects between two points with random speed?

texts:
In the Hierarchy I have a Cube and the script is attached to the cube.
And I also have in the Hierarchy two spheres as waypoints.

public class WP : MonoBehaviour
{
    public Transform[] waypoints;
    public float movingSpeed;

    GameObject[] allLines;
    GameObject[] duplicatedPrefabs;

    private void Start()
    {
        allLines = GameObject.FindGameObjectsWithTag("FrameLine");

        DuplicatePrefabEffects(allLines.Length);
        duplicatedPrefabs = GameObject.FindGameObjectsWithTag("Duplicated Prefab");
    }

    private void DuplicatePrefabEffects(int duplicationNumber)
    {
        for (int i = 0; i < duplicationNumber; i++)
        {
            var go = Instantiate(prefabEffect);
            go.tag = "Duplicated Prefab";
            go.name = "Duplicated Prefab";
        }
    }

    private void MoveDuplicated()
    {
        for (int i = 0; i < duplicatedPrefabs.Length; i++)
        {
           duplicatedPrefabs[i].transform.position = Vector3.Lerp(pointA.position, pointB.position, movingSpeed *Time.deltaTime);
        }
    }

    void Update()
    {
     MoveDuplicated();
    }
}

The duplicatedPrefabs are moving very very fast no matter what value I put for movingSpeed and then they are all stuck in the second waypoint and seems like moving on very specific small area on the second waypoint.

What I want to do is to move them smooth slowly between the two waypoints and with random speed range from each object. For example one will move at speed 1 the other on speed 20 third on speed 2.


texts:
In my 2D physics engine, I can detect AABB vs AABB collisions, and resolve them by finding the shortest penetration vector and adding it to the AABB's position.

Doing this "pushes" the first AABB outside of the second AABB, but doesn't deal with velocity/acceleration changes at all.

If I add gravity acceleration to my simulation, the velocity of the first dynamic AABB keeps growing even when it is resting on top of the second static AABB. Eventually, the velocity will become too big and the collision won't be detected (the dynamic AABB will fall through the static one).

I tried setting the velocity to zero after resolution, but it obviously didn't work well, and created unrealistic simulations.

I read online that resolving collisions by manually working on the position or the velocity is not correct.
I tried implementing forces (mass is an "hardcoded" 1 for now):

void Body::applyForce(sf::Vector2f mForce) { acceleration += mForce; }

void Body::integrate(float mFrameTime)
{
    velocity += acceleration * mFrameTime;
    position += velocity * mFrameTime;

    acceleration = {0, 0};
}

If I apply the shortest penetration vector as a force during collision resolution, the dynamic AABB will get "pushed out" from the static one, but its velocity will never decrease in a simulation without gravity and it will keep moving forever.

Is there a way to apply a "temporary" force? A force that deals with pushing the first AABB out of the second AABB, then stops when the AABB doesn't collide anymore?

Entire source code  available here: https://github.com/SuperV1234/SSVSCollision


texts: Is it possible to serialize both abstract and reference types in the same field of a generic class?

texts:
Say you have the following code:
[Serializable]
public abstract class AbstractBase { }

[Serializable]
public abstract class GenericSubclass<T> : AbstractBase
{
    public T Data;
}

[Serializable]
public class OtherClass
{
    // contains mixture of value and reference type fields
}

And say you need the following instantiations of GenricSubclass:
[Serializable]
public class ConcreteSubclass : GenericSubclass<OtherClass> { }

[Serializable]
public class ContainerSubclass : GenericSubclass<List<AbstractBase>> { }

Is there any way for both ConcreteSubclass and ContainerSubclass to be serializable at the same time? As far as I can tell, you can make ContainerSubclass at least serializable (if not fully editable in the inspector) by adding a [SerializeReference] attribute to Data, but that seems to break the serialization of ConcreteSubclass, and otherwise seems kind of fragile (ie, two MonoBehaviours can't share an object serialized by reference).
As for motivation, I'm using this structure to implement a virtual filesystem. Files have certain shared members regardless of what kind of data they hold, but any actual file must have a type in order to be associated with data of that type. ConcreteSubclass is a stand-in for files that hold reference types as their data, while ContainerSubclass is a stripped down version of how I'm handling directories. I'm using Unity 2019.4.


texts:
I'm currently coding a AI for a risk-like game, but I'm not sure how I put even the base classes together. I've read a lot about game design patterns, entity component designs and such, but I've trouble translating it to an actual architecture of my own.

My original layout feels weird, I have too many reference cycles and store most objects in multiple places. I know how to remove those, but that would make it (in my mind) a lot more complicated to get simply lists, for example the amount of Units a player possesses, or which units are in Zones next to the current one.

I had a bit more classes and something that kinda worked, but it was a mess and worse than this design. I wanted to start over and design it right. I feel really dumb having problems that should be much more easier to solve. And I wouldn't even know how to begin plugging in the AI.


texts: Magnitude of a vector in Generalized Balanced Ternary?

texts:
Generalized Balanced Ternary is a fairly obscure but very elegant method of indexing a hex grid, using only a single integer coordinate. Operations like addition and multiplication on these coordinates have intuitive effects: translation and rotation respectively.

The only difficulty with GBT is calculating the magnitude of a vector given its coordinate, or alternatively, of decomposing it into a series of one-unit steps. Is there a standard method of doing this?


texts: C# Item system design approach, should I use abstract classes, interfaces or virutals?

texts:
I'm working on a Resident Evil 1/2/3/0/Remake type of game. Currently I've done a big part of the inventory system (here's a link if you wanna see my inventory, pretty outdated, added a lot of features and made a lot of enhancements)

Now I'm thinking about how to approach the items system, If you've played any Resident Evil game or any of its likes you should be familiar with what I'm trying to achieve. Here's a very simple category I made for the items:

So you have different items, with different operations you could perform on them, there are usable items that you could use, like for example herbs and first aid kits that 'using' them would affect your health, keys to unlock doors, and equipable items that you could 'equip' like weapons. Also, you can 'combine' two items together to get new one, like for example mixing a green and red herb would give you a new type of herb, or combining a lighter with a paper, would give you a burnt paper, or ammo with a gun, would reload the gun or something. etc. You know the usual RE drill.

Not all items are 'transformable', in that, for example: lighter + paper = burnt paper (it's the paper that 'transforms' to burnt paper and not the lighter, the lighter is not transformable it will remain as it is) green herb + red herb = newHerb1 (both herbs will vanish and transform to this new type of herb) ammo + gun = reload gun (ammo state will remain as it is, it won't change but it will just decrease, nothing will happen to the gun it just gets reloaded)

Also a key note to remember is that you can't just combine items randomly, each item has a 'mating' item(s).

So to sum up, different items, and different operations on them. The question is, how to approach this, design-wise?

I've been learning about interfaces, but it just doesn't quite get into my head, I mean, why not just use classes with the good old inheritance?
I know the technical details of interfaces and that the cool thing about them is that they don't require an inheritance chain, but I just can't see how to use them properly, that is, if they were the right thing to use here.

So should I go with just classes and inheritance? just like in the tree I showed you? or should I think more about how to use interfaces? (IUsable, IEquipable, ITransformable) - why not just use classes UsableItem, Equipable item, TransformableItem?

I want something that won't give me headaches in the long run, something resilient/flexible to future changes. I'm OK using classes, but I smell something better here.

The way I'm thinking is to possibly use both inheritance and interfaces, so that you have a branch like this: item -> equipable -> weapon. but then again, the weapon has methods like 'reload' 'examine' 'equip' some of them 'combine' so I'm thinking to make weapon implement ICombinable?... not all items get used the same way, using herbs will increase your health, using a key will open a door, so IUsable maybe?

Should I use a big database (XML for example) for all the items, items names, mates, nRowsReq, nColsReq, etc?

Thanks so much for your answers in advanced, note that demo 3 is coming after I'm done with items :D


texts:
I am new to direct x and following this tutorial : brayzarsoft (part 14) I was able to display text. However, using this method the text is rendered to a texture.

When you look at games that have chat/consoles, you can select/copy/paste the text. How do they achieve this effect? Is it by using the winapi or do they code the whole system to be able to do this with texture?


texts: Unity WebPlayer : WWW GET Requests fail in webplayer only, not in editor

texts:
My question is about my game requesting data from my server-side cloud-based storage (I have the option of free public Dropbox or Amazon S3) via GET and the WWW class, and it not working only in the WebPlayer (works fine in the Editor).  By not working, I mean that the request is sent successfully, authorized and responded to by the cloud-service, but that WWW shows an error in the logs.  In the case of using Amazon S3, the Web Player even crashes, otherwise it just fails gracefully and the user is unable to move forward.

The Error log left by the webplayer says the following:

  WWW Error: Error when creating request. GET request with custom
  headers is not supported. for URL:
  https://my-storage.s3.amazonaws.com/myDir/myFile.json

Here's when I use a similar request to a public directory on Dropbox.  There is no crash, but the request also fails.

  WWW Error: Failed downloading
  dl.dropboxusercontent.com/u/7782207/spare-change/weapons/0.json for
  URL: dl.dropboxusercontent.com/u/7782207/spare-change/weapons/0.json

Try it for yourself: http://webroleplay.appspot.com   (currently using Dropbox, so not crashing the player)

username: test1

password: t


texts: LibGDX Efficient way to reduce a vector's value gradually until it reaches 0,0

texts:
I can manage to achieve this but the code seems to be much longer than it should be. Velocity is given an initial value, either positive or negative and then is gradually reduced until it is 0,0.
Vector2 velocity = new Vector2(4,-3);
private float decSpeed = .2f;

public void update(float delta) {
velocity.x = setVel(velocity.x);
velocity.y = setVel(velocity.y);
}

private float setVel(float vel) {
    if (vel > 0) {
        if (vel - decSpeed <= 0)
            vel = 0;
        else
            vel -= decSpeed;
    } else if (vel < 0)
        if (vel + decSpeed >= 0)
            vel = 0;
        else
            vel += decSpeed;
    return vel;
}

I simply want to decrease the vector value for both x and y by a fixed amount, but of course you have to take into account that the vector can be either positive or negative.


texts: how to add different class items to the same list C# XNA

texts:
I am trying to make a modular ship system, where parts can be added or removed to the ship entity.

I am using a class I made called ModuleManager and it has a list of ShipModules. this works fine for very basic block building ships, but I want to add a ThrusterModule that has thrust capabilities, and possible a GunMountModule for obvious reasons.

the problem is that I cannot do this.

List<ShipModules> modules = new List<ShipModules>();
ThrusterModule engine = new ThrusterModule();
modules.Add(engine);

I know that I cannot do this because they are different types.

Question: How can I add all these modules to the module manager? because I don't want to have to deal with having several different type modules that need several different variables to hold them

I have an idea of what to do, but I want to know if it would be the best route, I have heard of Class Composition. would that be beneficial for what I have explained? thanks.


texts: How do I render a rounded rectangle in libgdx?

texts:
I've been thinking of ways to render a rounded rectangle in libgdx. I haven't found a pre-built way in the documentation. I've looked at:

ShapeRenderer, but that's apparently quite expensive performance-wise and I'll have to compose it of a polygon perhaps or use circles and rectangles.
The Mesh class, which would probably perform well but is complex to use for such a simple shape. Again, I'd have to create the polygon myself with an algorithm for different sizes of rounded rectangles.

Can someone point me in the right direction?


texts: Best way to implement achievement system?

texts:
I'm currently trying to implement achievement system for my game. However, I can't find a better way to realize some complex ones like: The player has collected x coins, complete level with time least than x seconds, Kill over x enemies etc. Can you share your experiences please?

Secondly, Why don't we just implement achievement system as local only instead of using server like Scoreloop or OpenFeint? Or put it in another way, What are the advantages of using server for managing player's achievement?


texts:
There are some games where you need to make special movement with your mouse (spell casting or any other action).

Something like this

So basically, how can I compare mouse movement to my pattern (let's say defined by series of points (x, y). I assume there's no need to track the position every frame, there must be an interval.

But in terms of technique, how can I do it?


texts: Handheld video playback pauses when going to the home screen

texts:
Put an MP4 movie in your StreamingAssets folder and play it with

Handheld.PlayFullScreenMovie("MyMovie.mp4", Color.black, FullScreenMovieControlMode.CancelOnInput);

Then, in the middle of the movie, go to the home screen and then go back to the game. The video is paused.

You can't resume it because upon tapping the screen the video will disappear because of the CancelOnInput parameter (which I want to keep).

So - how can I make it so when the player returns to the game, the video resumes? I don't want to show video controls.

I am using Unity Pro 5.4.2, running on an iPhone 7 with iOS 10.1.


texts: OpenGL fixed function - WASD 2D movement

texts:
I need to make a simple object (like a turtle) move on a 2D scene. The keys w, s, a and d, respectively, make a positive and negative translate on x-axis (move to forward and backward), and rotate 1 degree (a and d).
The problem is the simple object, will initially rotate and translate correctly (because initially the object is at the origin). But after that the commands don't work like I intend them to.
Which are the best practices to make this?
Anyone can help me?
To compile (assuming this code is saved in a file named movement2D.cpp):
g++ movement2D.cpp -o movement2D -lGL -lglut
To execute, use : ./movement2D 500 500
Here's the code:
#include <GL/glut.h>

struct point {
    int x;
    int y;
};
typedef struct point t_point;

struct object {
    int width;
    int height;
    t_point pose;
    float angle;
};
typedef struct object t_object;

void display(void);
void keyPress(unsigned char, int, int);
void initialize(int, int);
void exit(void);
void draw(void);

t_object *head, *body;

int
main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(atoi(argv[1]), atoi(argv[2]));
    glutInitWindowPosition(10, 10);
    glutCreateWindow("Movement");
    initialize(atoi(argv[1]), atoi(argv[2]));
    glutDisplayFunc(display);
    glutKeyboardFunc(keyPress);
    atexit(exit);
    glutMainLoop();
}

void
display(void) {
    glClear(GL_COLOR_BUFFER_BIT);

    glPushMatrix(); {
        glLoadIdentity();
        glRotatef(body->angle, 0.0f, 0.0f, 1.0f);
        glTranslatef(body->pose.x, body->pose.y, 0.0f);
        draw();
    }
    glPopMatrix();

    glutSwapBuffers();
}

void
keyPress(unsigned char key, int x, int y) {
    switch (key) {
    case 'a':
    case 'A':
        body->angle += 1;
        break;
    case 'd':
    case 'D':
        body->angle -= 1;
        break;
    case 'w':
    case 'W':
        body->pose.x += 5;
        break;
    case 's':
    case 'S':
        body->pose.x -= 5;
        break;
    case 27:
        exit(1);
    }
    glutPostRedisplay();
}

void
initialize(int width, int height) {
    head = (t_object*) calloc(1, sizeof(t_object));
    body = (t_object*) calloc(1, sizeof(t_object));

    body->width = body->height = 100;
    head->width = head->height = 20;
    body->pose.x = body->pose.y = 0;

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glMatrixMode(GL_PROJECTION);
    glOrtho(-width / 2, width / 2, -height / 2, height / 2, -100, 100);
    glMatrixMode(GL_MODELVIEW);
}

void
exit(void) {
    free(head);
    free(body);
}

void
draw(void) {
    glColor3f(1.0f, 0.0f, 0.0f);
    glBegin(GL_QUADS);
        glVertex2i(-body->width / 2, -body->height / 2);
        glVertex2i(-body->width / 2, body->height / 2);
        glVertex2i(body->width / 2, body->height / 2);
        glVertex2i(body->width / 2, -body->height / 2);
    glEnd();
    glTranslatef(body->width / 2 + head->width / 2, 0.0f, 0.0f);
    glColor3f(0.0f, 0.0f, 1.0f);
    glBegin(GL_QUADS);
        glVertex2i(-head->width / 2, -head->height / 2);
        glVertex2i(-head->width / 2, head->height / 2);
        glVertex2i(head->width / 2, head->height / 2);
        glVertex2i(head->width / 2, -head->height / 2);
    glEnd();
}


texts: What determines which key combinations register in a Flash game?

texts:
Many times when I'm working on Flash games I'll find that a particular combination of keys held at the same time doesn't register, e.g. LEFT, DOWN and SPACEBAR.

I know from my days playing Doom this can be caused by the keyboard hardware, but surely technology has moved on since those spongy beige PS2 keyboards?

So my question: are these problems caused by Flash, by the hardware, by the operating system, or something else?


texts: Admob for Unity: clarification on use needed

texts:
I'm following this documentation by Google on how to integrate Admob ads into my game and I'm confused because of the following:

This documentation says I build by game and then I mess around with ads. (Section Unity plugin API tells me how to add ads and that's after the build instruction). Shouldn't it be vice versa? That I place those ads and build last?

Or, if I really do build first, where do I add those ads?


texts:
I need to import a few sprites (background platform and sky) into my game scene but it seems that their quality after importing into Unity is too bad (they are blurred). The original resolution of this two images is big enough (2048 X 400 for background) and they are looking very nice in standard Windows image viewer. Here are the settings for these two textures:

maxSize = 2048
Format = truecolor
TextureType = Sprite(2d)/nGUI
FilterMode - point

I am using Unity2D 4.5 Target resolution of my project is 1280*800.

Can anyone help me to solve these problem?
As you can see the grass on foreground looks very bloory (1 picture)
Texture settings (2 picture)
Original image (3 picture)


texts: simple adventure game mechanics stored in database

texts:
I plan to code a little adventure-like game. To be able to build multiple episodes without deploying new code I want to store any information possible in the database.

This includes stuff like

  if player examines item [cell phone], the contact [xxx] is added into his phone book and the item [cell phone] is replaced by [old nokia phone with scratches]

So something like "SCUMM lite".

Of course, [cell phone], [xxx] and [old nokia phone with scratches] are objects that already exist in the database. But while [cell phone] is of type [inventory-item], [xxx] is of type [contact], so there can't just be no simple link between some database-tables

I got a very basic idea about how I could achieve this but wonder if anyone has done that before and can give me a hint or even best practice


texts: In Box2D, how can I SetTransform of a body without getting an IsLocked assertion error?

texts:
I've created a bullet body and stored a reference to it in herobody:

bDef.type = b2_dynamicBody;
bDef.position.Set(herobody->GetPosition().x, herobody->GetPosition().y);
b = world->CreateBody(&bDef);
b2FixtureDef fixturebDef;
b2CircleShape circlebShape;
circlebShape.m_radius = 0.05;
fixturebDef.shape = &circlebShape;
b->CreateFixture(&fixturebDef);

I'm trying to change the current position of the bullet. I tried to use SetTransform but I get an error Assertion failed: (IsLocked() == false) during world->step in my update method.

// This doesn't work. Causes the above assertion.
/*
b->SetTransform(
  b2Vec2(
    herobody->GetPosition().x,
    herobody->GetPosition().y
  ),
  0
);
*/

// This works, but doesn't set position directly.
b->ApplyLinearImpulse(b2Vec2(5, 0), b->GetWorldCenter(),true);

How do I do this correctly?


texts: How do I disable fog on specific camera/s

texts:
I'm building an FPS with fog and I want to include a dynamic minimap, showing the locations of player and enemies in real time.
This is utilized by a second camera which is orthographic and looks at the scene from above.

In the minimap, I don't want to see the fog of course.
I've hidden other things from the minimap by using layers and culling masks, however the fog does not belong into any specific layer.

So, how do I disable the fog on just one (or some) camera?


texts: Calculating correct normal direction from multi-variable function

texts:
I am working with a plane model which I am offsetting the vertices on the up axis to look like waves by using the function:

Sin(vertex.x * frequency) * amplitude + Cos(vertex.y * frequency) * amplitude

Previously, I did this with a single variable and was able to confirm my normal directions were correct by getting the derivative, taking the tangent direction from that, and getting the perpendicular direction to the tangent in order to get my normal direction. I then just flipped them so they were facing the right way.

Now that I have added in the second, y, variable I have tried to take a similar approach. Where I take the two partial derivatives, get the tangent direction for each, get the normal for each from that, and then add the normals together to get my final normal direction. However, it seems that the results I am getting are different from those of the Unity calculation, which is correct.

Here is an image comparing my results to the correct Unity calculation:

Does anyone know where about I am going wrong in my calculation? I think it may be related to where and when I am normalizing, but I have tested out a bunch of different options and can't seem to get it to look correct and am now questioning if perhaps my method for combining the two normals is wrong. Thanks for any input. Below is a snippet of the code I am using to do this.

offsetAmount = Mathf.Sin(vertices[i].x * _Frequency) * _Amplitude + Mathf.Cos(vertices[i].y * _Frequency) * _Amplitude;

private void DifferentiateNormals()
{
    // Loop through every normal and calculate it manually
    for (int i = 0; i < vertices.Length; i++)
    {
        // The derivative is also an equation for the slope of a tangent line
        float offsetAmountDerivative = Mathf.Cos(_Frequency * vertices[i].x) * (_Frequency * _Amplitude);
        float offsetAmountDerivative2 = Mathf.Sin(_Frequency * vertices[i].y) * -(_Frequency * _Amplitude);

        // Rise / Run => Rise is the derivative function, run is 1
        Vector2 tangent = new Vector2(1, offsetAmountDerivative);
        tangent.Normalize();
        Vector2 tangent2 = new Vector2(1, offsetAmountDerivative2);
        tangent2.Normalize();

        // The perpendicular of tangent direction (x,y) is (y,-x)
        Vector3 normal = new Vector3(tangent.y, 0, -tangent.x);
        normal.Normalize();
        Vector3 normal2 = new Vector3(tangent2.y, 0, -tangent2.x);
        normal2.Normalize();
        // Flip the normals to be the correct direction (up)
        normal = -normal;
        normal2 = -normal2;

        Vector3 finalNormal = normal + normal2;
        //Vector3 finalNormal = new Vector3(_Amplitude * _Frequency * Mathf.Cos(_Frequency * vertices[i].x), -(_Amplitude * _Frequency) * Mathf.Sin(_Frequency * vertices[i].y), -1);
        finalNormal.Normalize();
        //finalNormal = -finalNormal;

        if (direction == ModelUpDirection.Y_Up)
        {
            // Works for Unity Plane
            normals[i] = new Vector3(finalNormal.x, finalNormal.z, 0.0f);
        }
        else if (direction == ModelUpDirection.Z_Up)
        {
            // Works for 100x100 Plane
            normals[i] = new Vector3(finalNormal.x, 0.0f, finalNormal.z);
        }
    }
    mesh.normals = normals;
}


texts: How to animate abstract 2d top down water texture?

texts:
I currently implement a game with a top down view of the ocean. I use the following, a little abstract texture:
The actual texture is transparent, I added the green-like color for clarity.
The problem I now have is, that I don't know how to animate this texture so the water looks nice. I tried to move the texture with a sin wave:  texture.y += sin(angle). Of course now the whole texture is moving which looks kind of unrealistic. The next thing I tried is to add another layer and implement a parallax effect. So that reflections under the water surface would also move, but much slower. It looks a little better but still not... nice enough.
I think the best looking animation would be, if the individual cells would expand and contract, kind of like a web or piece of cloth. Imagine if someone would slightly pull at one vertex of these cells and the neighbored cell would expand and the cell I pull towards to (or push to) would contract. Kind of like a web of springs(?). But I have no clue how to implement something like this:

Whats the math-model for this? Something with springs, where forces push/ pull?
And if so, how do I map this model to the given texture? Keeping all the curves and what not...

(I'm also open to different ideas/answers on how to animate the given texture.
Realism is not the point here, just some nice looking water like movements...)
Solution from DMGregory
I posted a libgdx example in this post: 2d water animation is jagged and not smooth (see answer about texture filtering)


texts: Do I require a game engine  when I want to make a game?

texts:
I started making a 2D game in C# and realized that I could also use a game engine or XNA. For the moment everything works fine but I'm afraid I will have problems in the future.

So do I actually need a game engine or XNA? Or will it also works without.

PS: I don't know anything of XNA so I would learn it.


texts: How do I create a cel-shaded cartoon look?

texts:
I am interested in everything related to this kind of effect (modeling, game engine, animation). What sort of stuff is needed?

Here are some sample images of what I mean:


texts: Do I need more than one UDP socket on the server?

texts:
I'm trying to make a UDP game server using the SDL_net library. This library offers SocketSets which are, according to the documentation, an analogy to the select function. Right now I have successfuly made a simple server which has just one UDPsocket and dumps every message to stdout.

Can I use those SocketSets somehow to make the server responsive, or am I just fine using only one UDPsocket for everything?


texts: Incorporating HttpSession into libGDX communication

texts:
I wrote my server-side code prior to learning libGDX and writing my client-side code.  Gdx.net provides for the http get communication I designed for, except for session authentication.  I say that based on not finding sessions mentioned in the API, and a couple heavies confirming it on the libGDX discord.
Are there any libraries / examples out there of libGDX developers who mirrored session authentication functionality?  The key limitation here is I want to stay with http request/response communication.

Minus any such direction, my next step will be to try using the "javax.servlet" libraries I used server-side on the client, and forgo the http classes that come included in the Gdx.net package.  I'm reluctant to take this step noting that libGDX has its own versions of lots of classes, for efficiency and to prevent memory leaks given how libGDX programs execute.  It'll be a while yet before my programming skills can detect and address such subtle issues.  Also, I think that browsers and the server servlets run on participate in session architecture.  With neither component in a libGDX PC app for "javax.servlet" to collaborate with, I'm doubtful this solution can work.
If it doesn't work, I'll think about moving up my goal of researching and learning how to use cloud hosting services. Some of these were recommended to me on discord as having frameworks with built-in support for authentication.


texts: I have an "amoeba" game mechanic. Any idea on how to implement it?

texts:
Outside of a tetris clone, a crappy 2D top-down shooter, and some messing around with stuff like Unity and Flixel, I realize that I have yet to complete a single, polished, bells-and-whistles game. I want to change this, and I have an idea for my next project.

The idea is that you're an amoeba. Amoebas have these eye-like cores (or something like that, I don't know biology), and you have two of 'em. You control one with WASD and the other with IJKL. There has to be a constant radius of stuff around each of the cores:

And the area of the amoeba has to stay constant. So if you move a core in one direction, you increase the amoeba's area, but that increase is compensated by a decrease somewhere else:

Aaaaaand I'd like to implement a vagination mechanic. You absorb things by engulfing them, like a boss. Maybe even an extra core, or a needle that pops you and causes all your inner stuff to start gushing out:

But here's the problem: I don't know how to make this. However, I would like some ideas on how to implement it. Should I explore physics libraries like Box2D? Or maybe something involving fluid physics? Any help would be much appreciated.

P.S. Feel free to steal this idea. I have plenty of ideas. If you do, please tell me how you made it so I can try it myself.


texts:
Im currently developing my first little android game. Its a casual game, which people can play when they are waiting for the bus or something like that.

All the other games in the playstores are looking very simple and still beautifull or addicting. So how can i improve my UI ? Are there any guidelines ?

The gallery contains several images of my GUI. Some are the same, but with other colors. Thats because i have an ingame shop, where the user can unlock new color themes.

Open Imgur Gallery


texts: Make the texture array node work with cubemaps?

texts:
I am working on a procedural interior mapping shader in Unity's Shader Graph. Ideally, I'd like to feed it a set of cubemaps it can pick from semi-randomly.
However, it seems that by default the texture array asset one can provide to a graph does not support reading cubemaps.
Does anyone have a way to use this, or perhaps a clever custom node or alternate texture mapping, so that I can read a number of cubemaps into the shader semi-randomly? Preferably an arbitrary number, but even a fixed number would be somewhat of an improvement.


texts:
I've gotten a basic Minecraft clone working (thanks to gamedev.stackexchange's help! ^_^), but know I have no idea how to save the file.

Minecraft itself uses a naive list of block ids as far as I can tell, but there are three problems with this:

There appears to be a 4096 block limit.
My game uses strings to represent block ids, not integers.
Extra data for blocks, like washing machines holding their state and contents.

Of course, (b) can be easily solved with a map generated at runtime, but that sounds really dirty. And Minecraft's solution to (c), NBT data, looks really quirky too.

How would I avoid these three problems when saving a Minecraftian world?


texts: Difference between Object.Destroy() and GameObject.Destroy() in Unity

texts:
What is the difference between using Object.Destroy() and GameObject.Destroy() in Unity?

I found the following info about that: here and here, but it did not answer my question.

So, could someone explain the matter foolproof, please?


texts: Precise exposition of an image for set number of frames (Vsync?)

texts:
I need to make a simple enough program in C#, but it seems to be impossible via usual WinForms means. I need to show something (a string of text, an image) on the screen for very small time interval. Since typical monitors are 60Hz, this interval would be 1 or 2 frames (16,6 or 33,3 ms). I tried doing this with usual WinForms, and it is not possible because, apparently, there is no way to know how many frames were output to the monitor since some point in time. I can only draw on the controls, and monitor output is totally independant.

So even if I run the timer, say, for 17 ms, between showing and hiding the image, it still sometimes manages not to draw a single frame of my image on the screen (even though theoretically it should, because 17ms > 16,6ms). Moreover, even 20ms seems to slow (even though i should be more than enough).

I did some game development as a hobby in the past (Delphi X, XNA) and I know that you usually draw the whole screen by yourself, each frame. Also, I know that there is an option called Vsync in most modern games, that allows you to synchronize your framerate to your monitor's frame rate.

So, is it possible? I mean, to actually know how many frames were sent to the monitor with w/e I want to show?

EDIT:

After doing some study, I guess there really is no way to check when monitor is updated. All you can do is use vsync - and all that does it just pauses your double-buffer-flipping until right after monitor refresh. Which would achieve what I want... if only it would be possible to guarantee that it will actually work! Turns out, it works only if it was not disabled previously in one of the million ways to disable it (like, in the driver, in the driver-bundled software, and wherever else).

I guess there is no way from your software to check if vsync is disabled in the driver either...  Or is there? I guess only outputting several frames and checking timestamps between them - like, does outputting a blank screen and swapping buffers takes 16,(6)ms or 0,1 ms.

Anyways, I think I'll be using C# SDL and try to somehow do it via setting double buffering and swap control... If someone has useful information to add though, please do!


texts: Tutorials for shadow mapping with multiple point lights in XNA

texts:
I've been trying to crack this problem for a while now and I'd like to know if there's a tutorial or two out there that can help me with this.  I know how to do shadow mapping with a single light, and I know how to implement multiple lights.  What I can't seem to do is put them together, despite my many attempts.

So yeah, does anyone know of any XNA tutorials that can baby-step me through this?

EDIT: This is for a 3D environment


texts: Vector3 Array serialization ReorderableList

texts:
I've been working on a ReorderableList, but it's given me quite the headache. I've come to the point where I want to define a "drawElementCallback" -callback, which looks like this:

list.drawElementCallback = (rect, index, active, focused) => {
    EditorGUI.PropertyField(rect, list.serializedProperty.GetArrayElementAtIndex(index), GUIContent.none);
};

What it's supposed to draw is one Vector3 object from an array of Vector3 objects. I get this property like this: ("property" is a SerializedProperty that contains the property that I need)

SerializedProperty locationsProperty = property.FindPropertyRelative("locations");

The array is declared as follows:

public Vector3[] locations;

Inside a container class that is marked as "Serializable".

The problem I kept getting with different code is that the ReorderableList shows all the Vectors correctly but it doesn't allow me to reorder any of the items, nor delete them (I can add new Vector3 objects and change them as expected).

With this code, I wanted to fix that issue. However, now I keep getting the following error:

"InvalidOperationException: The operation is not possible when moved past all properties (Next returned false)"

I wanted to make a reorderable list because it seemed easy, but I can't figure out the problem and I honestly wish I hadn't started working on it. It's taken up most of the past 3 days.

If anyone knows how to fix this, I would be very grateful.

To clarify, this code shows the array properly:

list.drawElementCallback = (rect, index, active, focused) => {
    SerializedProperty item = locationsProperty.GetArrayElementAtIndex(index);

    EditorGUI.BeginChangeCheck();
    item.vector3Value = EditorGUI.Vector3Field(rect, string.Empty, item.vector3Value);
};

But doesn't allow me to remove or reorder items. I thought I should show the code to demonstrate that there are indeed array items.


texts: XNA seams between 3d primitives in tiled terrain

texts: Every time I draw two primitives side by side, in this case two quads, I always get this seam-like tearing effect right along the sides of them. I'd like to think there is just an easy fix, but the only way I can think of would be reworking my indices, which I think would compromise my ability to draw textures. If anyone reading this can think of any fix, that would be great. Thanks in advance.


texts: Is there a convenient way to port a .apk file to a .swf file?

texts:
My friend just made a game and has a bunch of installs on the Android/Google Play.

I'm curious if it's possible at all to port said game to a flash game.  I've seen tutorials on how to port an .swf to an .apk, but I haven't seen anything yet that would make it seem to go backwards.

I'd love to help my friend get extra exposure for his game.  Is there any way he can port it?


texts:
I need to be able to compile a shader ".hlsl, .fx" in my DirectX app but here is the issue I can only specify 6 textures by there default path directory I don't want this I want to be able to set one path for all textures all 50 of them and then compile them and see the shader effect on all textures all 50 of them that's my issue thanks?
I am using DirectX June 2010 and using Direct3D11 and visual studio 2015.

#define NUM_TEXTURES 7
DETAIL_TESSELLATION_TEXTURE_STRUCT DetailTessellationTextures[NUM_TEXTURES +
1] =
{
//    DiffuseMap              NormalHeightMap                 DisplayName,
fHeightScale fBaseTextureRepeat fDensityScale fMeaningfulDifference
{ L"Textures\\rocks.jpg",    L"Textures\\rocks_NM_height.dds",  L"Rocks",
10.0f,       1.0f,              25.0f,        2.0f/255.0f },
{ L"Textures\\stones.bmp",   L"Textures\\stones_NM_height.dds", L"Stones",
5.0f,        1.0f,              10.0f,        5.0f/255.0f },
{ L"Textures\\wall.jpg",     L"Textures\\wall_NM_height.dds",   L"Wall",
8.0f,        1.0f,              7.0f,         7.0f/255.0f },
{ L"Textures\\wood.jpg",     L"Textures\\four_NM_height.dds",   L"Four
shapes", 30.0f,       1.0f,              35.0f,        2.0f/255.0f },
{ L"Textures\\concrete.bmp", L"Textures\\bump_NM_height.dds",   L"Bump",
10.0f,       4.0f,              50.0f,        2.0f/255.0f },
{ L"Textures\\concrete.bmp", L"Textures\\dent_NM_height.dds",   L"Dent",
10.0f,       4.0f,              50.0f,        2.0f/255.0f },
{ L"Textures\\wood.jpg",     L"Textures\\saint_NM_height.dds",  L"Saints" ,
20.0f,       1.0f,              40.0f,        2.0f/255.0f },
{ L"",                       L"",                               L"Custom" ,
5.0f,        1.0f,              10.0f,        2.0f/255.0f },
};
DWORD                               g_dwNumTextures = 0;
ID3D11ShaderResourceView*
g_pDetailTessellationBaseTextureRV[NUM_TEXTURES+1];
ID3D11ShaderResourceView*
g_pDetailTessellationHeightTextureRV[NUM_TEXTURES+1];
ID3D11ShaderResourceView*
g_pDetailTessellationDensityTextureRV[NUM_TEXTURES+1];
ID3D11ShaderResourceView*           g_pLightTextureRV = NULL;
WCHAR
g_pszCustomTextureDiffuseFilename[MAX_PATH] = L"";
WCHAR
g_pszCustomTextureNormalHeightFilename[MAX_PATH] = L"";
DWORD                               g_bRecreateCustomTextureDensityMap  =
false;


texts: Why players who join late can't see other people data?

texts:
I want to show the name of the players above their head but I have a problem where people joining late doesn't get other players' name.
For example:

Player 1 joins to the server with the name Peter.
Player 2 joins to the server with the name Josh.
Peter (Player 1) sees Josh's name perfectly, but when Josh joins Peter's name is not synchronized correctly.

My sync code looks something like this:
[SyncVar] private string NAME;
public override void OnStartClient(){
    if(networkPlayerData is null)
    {
        networkPlayerData = BTNetworkController.Controller.playerData;
        NAME = BTNetworkController.Controller.playerData.Name;
    }
    SendPlayerNameToServer(NAME);
}
[Command]
private void SendPlayerNameToServer(string name)
{
    RpcSetPlayerName(name);
}

[ClientRpc]
void RpcSetPlayerName(string name)
{

    gameObject.GetComponentInChildren<TMP_Text>().text = name;
}

So my question is how can I sync data to newly joined players and refresh player names accordingly.


texts: What to do after detecting OBB-OBB intersection

texts:
I'm using this code to detect intersections between two OBBs. The problem is that i don't know what to do after detecting it. I tried using a simple algorithm:

    if (collision detected) {
        move character back to its position on previous frame
    }

But this is not what i need, because the character is rotating and moving to certain points (usually to mouse click position). When it's close to an object with OBB and it rotates to a point, its OBB updates (the position of all OBBs corners is recalculated) and most of the time the updated OBB intersects with an object that is near, so the charecter gets stuck at its position.

How can i deal with the rotation problem or what other methods can you offer for stoping character when its OBB itersects with another?


texts: How to rotate and move an object in precise time frame

texts:
My task is to rotate and move an object into a new position and rotation in a given time. Say I have to move a cube from (0,0,0)|(0,0,0) to (1,1,1)|(0,90,0) in 5 seconds. Could anyone explain to me please how to achieve that?
My experiment is:
private IEnumerator DoMove(/*float time, Vector3 targetPosition*/)
{
    foreach(WayPoints wp in tposes)
    {
        float counter = 0;
        float duration = wp.timeStamp;
        while (counter < duration)
        {
            counter += Time.deltaTime;
            Vector3 curpos = cube.transform.position;
            Quaternion crot = cube.transform.rotation;
            float time = Vector3.Distance(curpos, wp.position.position) / (duration - counter) * Time.deltaTime;
            cube.transform.position = Vector3.MoveTowards(curpos, wp.position.position, time);
            cube.transform.rotation = Quaternion.Lerp(crot, wp.position.rotation, time);
            yield return null;
        }
        Debug.Log("Reached position: " + wp.position.position + " in time: " + Time.time);
    }
}

The cube gets to its position in time, but rotation is late. The end position of the cube should be (2,2,2)|(0,120,0), but it stops moving at (2,2,2)|(0,~110,0).
There are two positions I want the cube to be in:

(1,1,1)|(0,90,0) in 5 seconds
(2,2,2)|(0,120,0) in next 4 seconds


texts: Best way to initialize values on 32-bit FP framebuffer in OpenGL

texts:
I have a framebuffer bound to 32-bit FP texture:

glGenTextures(1, &texColor);
glBindTexture(GL_TEXTURE_2D, texColor);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, w, h, 0, GL_RGBA, GL_FLOAT, (GLvoid*)NULL);
glBindTexture(GL_TEXTURE_2D, 0);

glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texColor, 0);

What's the best way to initialize framebuffer to a value 1000.0?

The problem is that

glClearColor(1000.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);

clamps values to [0,1] interval, and clearing the texture texColor would require memory allocation of w * h * sizeof(float) bytes of memory and manual filling of that buffer with value 1000.0 which is slow (I would inject it using glTexImage2D).

I'm using OpenGL 3.2 Core profile.

Thanks,
Josip


texts: How can I be sure that the tileset used in making a Tiled map remains as a multiple of 2, since this is a requirement of phaser when loading JSON tiled maps? I have tileset images which I got for free and they are not exactly up to phaser specs to be used.


texts: How does one usually go about this? Is this something that generally an artist has to do manually, or are there decent procedural methods (such as with normal mapping where one can look for gradients in the texture) to generate specular maps for textures?


texts: snapping an angle to the closest cardinal direction

texts:
I'm developing a 2D sprite-based game, and I'm finding that I'm having trouble with making the sprites rotate correctly. In a nutshell, I've got spritesheets for each of 5 directions (the other 3 come from just flipping the sprite horizontally), and I need to clamp the velocity/rotation of the sprite to one of those directions. My sprite class has a pre-computed list of radians corresponding to the cardinal directions like this:

protected readonly List<float> CardinalDirections = new List<float>
                           {
                               MathHelper.PiOver4,
                               MathHelper.PiOver2,
                               MathHelper.PiOver2 + MathHelper.PiOver4,
                               MathHelper.Pi,
                               -MathHelper.PiOver4,
                               -MathHelper.PiOver2,
                               -MathHelper.PiOver2 + -MathHelper.PiOver4,
                               -MathHelper.Pi,
                           };

Here's the positional update code:

if (velocity == Vector2.Zero)
            return;

        var rot = ((float)Math.Atan2(velocity.Y, velocity.X));
        TurretRotation = SnapPositionToGrid(rot);

        var snappedX = (float)Math.Cos(TurretRotation);
        var snappedY = (float)Math.Sin(TurretRotation);
        var rotVector = new Vector2(snappedX, snappedY);

        velocity *= rotVector;
        //...snip

private float SnapPositionToGrid(float rotationToSnap)
    {
        if (rotationToSnap == 0)
            return 0.0f;

        var targetRotation = CardinalDirections.First(x =>
                (x - rotationToSnap >= -0.01 && x - rotationToSnap <= 0.01));
        return (float)Math.Round(targetRotation, 3);

    }

What am I doing wrong here? I know that the SnapPositionToGrid method is far from what it needs to be - the .First(..) call is on purpose so that it throws on no match, but I have no idea how I would go about accomplishing this, and unfortunately, Google hasn't helped too much either. Am I thinking about this the wrong way, or is the answer staring at me in the face?

EDIT: Thanks Gregory for the answer. Only thing I really had to modify from the answer  was to re-construct the velocity vector to the new snapped rotation (I'm sure there are further optimizations that I can do, but for now it's enough that it works!):

        var snappedX = (float)Math.Round(Math.Cos(TurretRotation), 3) *
                           velocity.Length();
        var snappedY = (float)Math.Round(Math.Sin(TurretRotation), 3) *
                           velocity.Length();
        var rotVector = new Vector2(snappedX, snappedY);

FOLLOW-UP EDIT:
The initial answer worked very well as a naive implementation, but suffered from inaccuracies of up to 45 degrees when dealing with negative angles; -3.14 snapped to -2.356 for instance. To correct that, I added a check to account for those situations.  Below is a complete implementation of a SnapToGrid method. Some optimizations have been made, like pre-computing the various divisors of Pi to avoid the division. Further optimization could possibly be achieved by looking for short-circuit scenarios, i.e. if rotationToSnap ~=0, but if anyone has further optimizations, I'd be curious to see them!

public static float SnapPositionToGrid(float rotationToSnap)
{
    if (rotationToSnap == 0)
        return 0.0f;

    var modRot = rotationToSnap  % MathHelper.PiOver4;

    float finalRot;

    if (modRot < RoundedPiOver8)
    {
        if (modRot < -RoundedPiOver8)
            finalRot = rotationToSnap + -MathHelper.PiOver4 - modRot;
        else
            finalRot = rotationToSnap - modRot;
    }
    else
        finalRot = rotationToSnap + MathHelper.PiOver4 - modRot;

    return (float)Math.Round(finalRot, 3);
}


texts: I am trying to develop an Enemy AI with vision cone in unity 2d top down game, can you please suggest me some approach or sample script, so I can get an idea.


texts: Animation timeline organization for Unity 5

texts:
I create stuff for AssetStore and use 3ds max and Unity 5.

Can someone tell me how I need to work with timeline?

When I create animation for several objects, I need to animate them one by one? (Example: from Frame 0 to Frame 60 object 01 rotates 360 degrees, then from Frame 60 to Frame 120 object 02 rotates 360 degrees) OR I need to animate every one object in same time. (Every one rotates from Frame 0 to Frame 60).

I know that I need to assign animation controllers in Unity, and if I create all animations in same time, I need only one controller for many objects.

If there, any benefits to animate objects one by one and have multiple controllers later in game development?


texts: Is there any way in open-gl to "bit crush" everything on the screen?

texts:
I am making an educational game and am looking for options for a visual effect to show when something is "incorrect".  So, I am looking to see if there's an easy way in openGL to temporarily distort everything on the screen (all sprites, everything), like pixelate it or something...

Does anyone know if this is possible?

I'm using cocos2d by the way...

Edit: here is an example of what I am looking for:

On the left, the original, on the right the pixelated / bitcrushed version:

The thing is, I don't want to just do this to a single texture / sprite, I want to take the entire display output, and perform this pixelated effect on it and then revert back to normal after a second or something.


texts: What OpenCL video cards (or FPGAs) features are needed for high speed multiplication?

texts:
I'm benchmarking some cryptographic related software and am looking for video cards that are better at parallel multiplication vs parallel addition.

Is there any prior work that would graph video card performance against math operations (calculating large digits like 256^2048, calculating the modulus etc.)
What GPU features should I look for?


texts:
I was wondering if my 2D Pixel Art platformer HTML5 game(a lot of words there..) should have loading screens for maps.

My game has different maps and I don't know if a loading screen should be implemented to transition to those maps, they are already loaded when the page finished loading right?

The framework I am using is Phaserjs.

Thanks for your help :')


texts: Large 2D Arrays Causing Garbage Collection

texts:
I've been working on a game in Java that, for this post's sake, looks like Terraria and has random  world generation. I've been using Vectors to contain my tile/block objects, but recently due to the nature of the calculations I perform on them fairly often, I've switched my system to 2D arrays, using 'chunks.'

Each 2D array (chunk) of blocks is 256x256. That's a lot of data, and considering that's only for one chunk (the player will probably have 30-50 chunks generated by the end of the game), the amount of live objects increases quickly.

Today I started getting lag spikes in-game when I generated about 15 chunks or so. After a few print statements, it was clear that the spikes were pretty inconsistent, and although I have no knowledge of the Java garbage collector, I can only assume it is the culprit.

I read that the more live objects you have (the ones that are still referenced somewhere), the more the GC will lag when it does its thing. Plus, all these blocks are taking up huge blocks of memory which is causing the GC to start in the first place.

I have tried saving the unloaded chunks to a file for later use, but as you can imagine, saving that much data isn't exactly efficient. I'm stumped here.

Does anyone have any suggestions on how to reduce the amount of live objects in-game?


texts: Improve appearance of neon LineRenderer at sharp corners

texts:
I followed the answer given in how to make 2d neon using linerender and get neon effect nicely, but when I draw a line with a tight circle or overlap nearby lines, I get unsightly triangle artifacts and discolouration:

I'm using this alpha image:
And I apply this shader on the LineRender:
Shader "Trail/Neon"
{
    Properties
    {
        [PerRendererData] _MainTex("Sprite Texture", 2D) = "white" {}
    _Color("Tint", Color) = (1,1,1,1)
        _MainTexture("Sprite", 2D) = "white" {}
    [MaterialToggle] PixelSnap("Pixel snap", Float) = 0
    }

        SubShader
    {
        Tags
    {
        "Queue" = "Transparent"
        "IgnoreProjector" = "True"
        "RenderType" = "Transparent"
        "PreviewType" = "Plane"
        "CanUseSpriteAtlas" = "True"
    }

        Cull Off
        Lighting Off
        ZWrite Off
        Blend One OneMinusSrcAlpha

        Pass
    {
        CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 2.0
#pragma multi_compile _ PIXELSNAP_ON
#pragma multi_compile _ ETC1_EXTERNAL_ALPHA
#include "UnityCG.cginc"

        struct appdata_t
    {
        float4 vertex   : POSITION;
        float4 color    : COLOR;
        float2 texcoord : TEXCOORD0;
        UNITY_VERTEX_INPUT_INSTANCE_ID
    };

    struct v2f
    {
        float4 vertex   : SV_POSITION;
        fixed4 color : COLOR;
        float2 texcoord  : TEXCOORD0;
        UNITY_VERTEX_OUTPUT_STEREO
    };

    fixed4 _Color;

    v2f vert(appdata_t IN)
    {
        v2f OUT;
        UNITY_SETUP_INSTANCE_ID(IN);
        UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT);
        OUT.vertex = UnityObjectToClipPos(IN.vertex);
        OUT.texcoord = IN.texcoord;
        OUT.color = IN.color * _Color;
#ifdef PIXELSNAP_ON
        OUT.vertex = UnityPixelSnap(OUT.vertex);
#endif

        return OUT;
    }

    sampler2D _MainTexture;
    sampler2D _AlphaTex;

    fixed4 SampleSpriteTexture(float2 uv)
    {
        fixed4 color = tex2D(_MainTexture, uv);

#if ETC1_EXTERNAL_ALPHA
        // get the color from an external texture (usecase: Alpha support for ETC1 on android)
        color.a = tex2D(_AlphaTex, uv).r;
#endif //ETC1_EXTERNAL_ALPHA

        return color;
    }

    fixed4 frag(v2f IN) : SV_Target
    {
        //standard sprite shader, only this part is different.
        //takes the sprite in
        fixed4 s = SampleSpriteTexture(IN.texcoord);

        //makes a colored version of the sprite
        fixed4 c = s * IN.color;

        //makes the grayscale version
        fixed n = (s.g + s.r + s.b) / 3;

        //So, I've scrapped the previous calculation in favor of this I'll leave the previous one in too, just for reference
        c = (c*3 + n*c.a)*c.a;
        //Adds the grayscale version on top of the colored version
        //The alpha multiplications give the neon effect feeling
        //c.g = (c.g + n * c.a) * c.a;
        //c.r = (c.r + n * c.a) * c.a;
        //c.b = (c.b + n * c.a) * c.a;
        // You can add c.a multiplications of colors
        //(i.e. turn  c.g to c.g*c.a) for less color in your effect
        //this saturates the insides a bit too much for my liking

        return c;
    }
        ENDCG
    }
    }
}

How can I improve the appearance of these corners, so they look smooth?