texts:
While developing a reasonably simple RTS-like game, I noticed my distance calculations were causing an impact in performance.

At all times, there are distance checks to know if a unit is in range to its target, if the projectile has reached its target, if the player has run over a pickup, general collision, etc. The list goes on, and checking for distance between two points is used a lot.

My question is exactly about that. I want to know what alternatives game developers have for checking distances, other than the usual sqrt(x*x + y*y) approach, which is fairly time consuming if we are performing it thousands of times per frame.

I'd like to point out I am aware of the manhattan distances and squared distance comparisons (by skipping the sqrt bottleneck). Anything else?


texts: Collision detection - player gets stuck in platform when jumping

texts:
So I'm having some problems with my collision detection with my platformer. Take the image below as an example.

When I'm running right I am unable to go through the platform, but when I hold my right key and jump, I end up going through the object as shown in the image, below is the code im using:

if(shapePlatform.intersects(player.getCollisionShape())){

     Vector2f vectorSide = new Vector2f(shapePlatform.getCenter()[0] - player.getCollisionShape().getCenter()[0],
             shapePlatform.getCenter()[1] - player.getCollisionShape().getCenter()[1]);
            player.setVerticleSpeed(0f);

            player.setJumping(false);
            if(vectorSide.x > 0 && !(vectorSide.y > 0)){
                 player.getPosition().set(player.getPosition().x-3, player.getPosition().y);

            }else if(vectorSide.y > 0){
                player.getPosition().set(player.getPosition().x, player.getPosition().y);

            }else if(vectorSide.x < 0 && !(vectorSide.y > 0)){
                 player.getPosition().set(player.getPosition().x+3, player.getPosition().y);
            }

}

I'm basically getting the difference between the centre of the player and the centre of the colliding platform to determine which side the player is colliding with. When my player jumps and walks right on the platform he goes right through. The same can also be observed when I jump on the actual platform, should I be resetting the players y in this situation?


texts: How can I find the perpendicular to a 2D vector?

texts:
I'm making a top down game where the player moves forwards towards the position of the mouse cursor. As part of the player's movement code, I need to determine a vector that is perpendicular to the player's current facing vector (to implement strafing behavior).

How can I compute the perpendicular vector of a given 2D vector?


texts: Disposing only certain resources in XNA?

texts:
The ContentManager in XNA 4.0 only has one Unload() method that Unloads all Assets.

I want to have some "global" Assets that are always loaded, but then I want per-Level Assets which should be Unloaded when the level is changed.

Should I create a second Instance of the ContentManager as part of the Level.cs Class? Or should I use Game.Content and then call .Dispose on the Assets I load? Or should I create my own ContentManager on top of the ReadAsset function as outlined here?


texts: Handling AI with ECS in a turn based roguelike

texts:
I am trying to implement the Entity Component System pattern to use in a roguelike game. Right now, I have 3 systems. Input, AI, and Action. The input system basically is just a system used by the player to get input from the keyboard. The AI system is for the NPCs. The action system processes anything with an Action component, which is used to describe either a move, an attack, an item usage, basically anything that advances the game time.

However, I am having trouble with implementing the correct behaviors. It is clear that the player should have a turn, getting his input. If the input is invalid, he repeats his turn, again and again until he makes a turn that passes time. Then the enemies should get their move from the AI system, and initiate it. So what the behavior should be like is this:

while(!input.passesTime())
    input.getInput()
    draw()
action.do(Player)
for all Entities with AI
    AI.think(Entity)
    action.do(Entity)
draw()

Notice how everything is intertwined and doesn't really make sense as a single (or multiple) system. How can I design this better? Note especially that I need to update the screen everytime, even with invalid inputs since they may write something out (e.g. "Nothing interesting happens").

After some thinking it seems clear that the renderer should also be a system, but this doesn't really clear up the requirements.


texts: What does Steam require from a Greenlight submission?

texts:
I'm an indie developer getting ready to submit my game to Steam Greenlight, but have hit a road block. I don't know what to submit.

I've been searching and I haven't found anything detailing whether I should submit the game's files and let Steam do the rest or an installer to install the resource files and the executable in a certain spot?

Do I need to make any Steam-specific optimizations/additions to my game before it can be submitted?


texts: Calculating projectile velocity from moving object

texts:
I'm working on a top down space shooter and am having trouble with calculating/understanding the physics for projectiles launched from the space ship.

The ships have a velocity vector and a turret with rotation independent from the body of the ship. Currently projectiles are launched based on the turrets rotation by making a normalized vector then multiplying each component by a speed. However, this doesn't work when the ship is moving faster than the speed scalar.

Right now if the ship is going faster than the projectile speed scalar and the turret is aimed in the same direction as the ship's velocity, the projectile goes backwards (away) from the ship. Assuming there is no drag/gravity (very deep space), how should I go about handling projectiles?


texts: DirectX11 - AlphaBlending Rendering problem

texts:
So.. I completed this tutorial on the following site rastertek.com/dx11tut12.html. The tutorial is all about rendering Text in an orthographic space. Basically just 2D rendering on DirectX 11.

Now that I finished i wanted to experiment with it. In the original tutorial he uses a Black background texture with the different letters in white, then he uses AlphaBlending to make the pipeline omit the background when drawing to the backbuffer saying that the alpha value for when the sample color is black is 0.

//Initializing the AlphaEnabledBlendingState
D3D11_BLEND_DESC blendStateDescription;
ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC));

blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f;
blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;

result = this->m_device->CreateBlendState(&blendStateDescription, &this->m_alphaEnableBlendingState);
if (FAILED(result))
{
    return false;
}

_

//Setting the AlphaEnabledBlendingState as the active AlphaBlendState
float blendFactor[4];

blendFactor[0] = 0.0f;
blendFactor[1] = 0.0f;
blendFactor[2] = 0.0f;
blendFactor[3] = 0.0f;

this->m_deviceContext->OMSetBlendState(this->m_alphaEnableBlendingState, blendFactor, 0xffffffff);

And the PixelShader I'm using to render the Text.

Texture2D shaderTexture;
SamplerState SampleType;

cbuffer PixelBuffer
{
    float4 pixelColor;
};

struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
};

float4 main(PixelInputType input) : SV_TARGET
{
    float4 color;

    color = shaderTexture.Sample(SampleType, input.tex);

    //If the color is black on the texture then treat this pixel as transparent
    if (color.r == 0.0f)
    {
        color.a = 0.0f;
    }
    //If the color is other than black on the texture then this is a pixel in the font so draw it using the font pixel color
    else
    {
        color.a = 1.0f;
        color *= pixelColor;
    }

    return color;
}

This is the result

So i said, let's change the background of the texture to green, (0, 255, 0). So i did and changed the shader to look for a green color to set his alpha value to 0.

Looking for Green instead of black

//If the color is green on the texture then treat this pixel as transparent
if (color.r == 0.0f && color.g == 1.0f && color.b == 0.0f)
{
    color.a = 0.0f;
}

But the result is not what i expected. There's also the prove that the texture background is green.

This is the result

So, the question is... What am I doing wrong? what step am I skiping? I see that the color is totally transparent, as it should be.

Thank you for the time and help you can provide!


texts: Porting to Android...what is the equivalent of Properties.Settings.Default?

texts:
I'm porting my MonoGame/OpenGL app to Android.  My game uses Properties.Settings.Default to store user preferences.

What is the equivalent of this in Android?


texts: How can I gain access to a player instance in a Minecraft mod?

texts:
I'm creating Minecraft mod with a pickaxe that takes away experience when you break a block. The method for taking away experience from a player is addExperience on EntityPlayer, so I need to get an instance of EntityPlayer for the player using my pickaxe when the pickaxe breaks a block, so that I can remove the appropriate amount of experience.

My pickaxe class currently looks like this:

public class ExperiencePickaxe extends ItemPickaxe {

public ExperiencePickaxe(int ItemID, EnumToolMaterial material){
    super(ItemID, material);
}

public boolean onBlockDestroyed(ItemStack par1ItemStack, World par2World, int par3, int par4, int par5, int par6, EntityLiving par7EntityLiving)
{
    if ((double)Block.blocksList[par3].getBlockHardness(par2World, par4, par5, par6) != 0.0D)
    {
        EntityPlayer e = new EntityPlayer(); // create an instance
        e.addExperience(-1);
    }

    return true;
}
}

Obviously, I cannot actually create a new EntityPlayer since it is an abstract class. How can I get access to the player using my pickaxe?


texts: How to write testable MonoBehaviour and test scripts in Unity?

texts:
I had problems with decoupled scripts and exposing interfaces in Unity, and these answers helped me a lot. But now, since I don't have hard-coded references in my scripts, I wanted to write unit tests for my code.

This presented a problem - I can't instantiate MeonoBehaviours using new
because of how the engine works. What is more, I can't mock out anything from the Unity API.

I found a great blog post by Tomek Paszek. He suggests using the Humble Object pattern, and it seems reasonable. Still, maybe thats just me, because I haven't used that pattern too much, when using the Humble Object pattern even simple code seems to be very complex.

Are there other ways to write testable MonoBehaviors?


texts: Stuttering movement when approaching boundary

texts:
I'm trying to limit my movement in the y-axis by checking if the position will be within the boundaries after the Translate. If it is, only then do I translate the Player.

public class Player : MonoBehaviour {

    private float speed = 5.0f;
    private float bottomY = -4.37f;

    void Start () {
        transform.position = new Vector3(0, -4, 0);
    }

    void Update () {
        Movement();
    }

    void Movement () {
        // vertical movement
        Vector3 yTranslateVector = Vector3.up * Input.GetAxis("Vertical") * speed * Time.deltaTime;
        float newYPos = (transform.position + yTranslateVector).y;
        if (newYPos > bottomY && newYPos < 0) {
            transform.Translate(yTranslateVector);
        }

        // horizontal movement
        Vector3 xTranslateVector = Vector3.right * Input.GetAxis("Horizontal") * speed * Time.deltaTime;
        transform.Translate(xTranslateVector);
    }
}

However, when I do this, the Player kind of pauses when approaching the boundary and then stutters forward towards the absolute limit upon releasing the key. I tried putting the Movement function in the Update and FixedUpdate method, but neither made any difference. Can anyone give me any insight into this?


texts: Working with Blender (Model individual objects or scenes?)

texts: I've been working in Unity for awhile but I'm pretty new to making my own models. I'm using Blender since it seems like a pretty good tool for the job. Let's say I am making a simple scene in Unity with a table that has a cup and plate on it and some chairs. Assume I want to be able to move each of these objects around independently from the other objects. Does this mean that when modeling in Blender, I have to model each object individually and import them separately in Unity? It would be nice sometimes to be able to model entire scenes in Blender, but if stuff in the scene isn't intended to be static, then there is no way to treat parts of these scene as objects and manipulate them individually in Unity right?


texts: What is the proper strategy to manage vertex buffers?

texts:
I have created a large variety of shaders for my game engine for different use cases. The vertex input for the shaders depend on what I want to do with them. For example, if I want to just render the wireframe of a mesh, I do not need texture coordinates, normals, etc. because I just need basic vertex information. However, when I render animated meshes (I use Skinned Animation), then I need additional information like joint link weights for each vertex.
My question is: What is the best way to manage Vertex Buffers? Do I create a Vertex Buffers for each use case when I create the model and store them for later use, i.e. I select at run-time which of the stored Vertex Buffers to use for rendering? Do I create the Vertex Buffer I need at run-time in each render cycle? What is the best way to do it?
I am using DirectX 11 and C# (using SharpDX as wrapper).


texts: Where do I write code in my minecraft modding environment?

texts:
So this is probably a stupid question but I'm just beginning so I hope someone can help. I set up my whole modding environment in eclipse but the problem is that I don't know where to start writing code that will be run while playing the game. I'm used to there being a run method that will constantly loop and run the code within that method but there doesn't seem to be such a thing. I tried putting stuff in my main class under the init event handler but that just crashed my game. I was just testing stuff out and tried putting this code in the init area which caused the game to crash when I tried running the client:

Entity player = Minecraft.getMinecraft().player;
if(player.posX>100.0)
{
 player.posX = 12.0;
}


texts: What is the alternative to Time.time for scrolling texture?

texts:
In my game, I'm using the standard SetTextureOffset method to smoothly scroll texture on background quad.

However, on game over, instead of reloading the scene, I'm just reseting all values initial position to give illusion that scene was reloaded. With this approash, i'm unable to use Time.time or Time.timeSinceLevelLoad because, the level was not reloaded and this value stays high. So scrolling is too fast right in the beginning.

Are there any time independent methods to smoothly scroll texture? Thanks.


texts: 2D AABBs and resolving multiple collisions

texts:
Okay, so this is a problem I've been trying to figure out for quite some time. Mine is a 2D platformer game with a world made up of (usually) immobile tiles and mobile sprites, both of which use AABBs to represent their hitboxes. This game is NOT grid-based due to some complications with moving layers of tiles.

I can detect collisions and easily figure out the depth of the collision. I use the "shallowest axis method" to determine which way to resolve a collision between the sprite and the tile. If the sprite is deeper horizontally than vertically, the direction to resolve is either up or down. If the sprite is deeper vertically than horizontally, the direction to resolve is either left or right.

This is simple enough, and it works pretty well. That is, until you have a sprite colliding with more than one tile. As, by their nature, each collision has to be checked separately, different collisions may have different direction to resolve in. For example, if a sprite is trying to walk across a row of tiles, for one frame they will intersect the next tile such that the horizontal depth is shorter than the vertical depth. As the collision says "resolve left", it will be pushed back and will be stuck on the corner.

I've been mulling this problem over, on and off, for quite some time, and several solutions have come to me, but all have flaws. I could mark certain sides as unreachable, but without a grid-based engine, determining "unreachability" is remarkably complex, especially with moving layers of tiles always a possibility.

Another possible method would be to predict collisions before they happen and "work back" the movement to the point of the collision, I suppose, but I'm not sure how the math on that works.

I feel that I'm missing something incredibly obvious, especially since games from the 80s have already solved this problem.


texts: Why doesn't the Camera.pixel(Height/Width) match the Canvas size?

texts:
I am making an app that has a custom viewport Rect like so:

When I check the sizes of this viewport rectangle in pixels with Camera.pixelHeight; Camera.pixelWidth, I get the following values: 743px, 770px.

This looks correct.

Now when I check my canvas in the Editor, I see the following values for the width and height:

Now I have a script that gets the width and height of the canvas. This is correct: I get again the 743px and 770px. But when I position my UI element, it is outside because the positioning refers back the the incorrect values displayed in the canvas rectangle transform properties.

What is happening here and how do it make the canvas use the correct values?


texts: What are some good books which detail the fundamentals of graphics processing?

texts:
The best book on the nitty gritty of graphics that I've found is Computer Graphics: Principles and Practice http://www.amazon.com/Computer-Graphics-Principles-James-Foley/dp/0201121107

However, as this was written in the early 90s, it is a little out of date.

Are there some similar books which go over the more recent developments?


texts:
Hi I am using opengl and I am having a problem if I go further from the skybox with the camera I get black areas, a smaller radius of the skybox will make the camera too close to the object to stay inside the skybox and increasing it obviously doesn't help.
:

Here is the code for the skybox:

  glEnable(GL_TEXTURE_2D);
    glPushMatrix();
    qobj = gluNewQuadric();
    glTranslated(50,0,0);
    glBindTexture(GL_TEXTURE_2D, underwater);
    gluQuadricTexture(qobj,true);
    gluQuadricNormals(qobj,GL_SMOOTH);
    gluSphere(qobj,100,100,100);
    glPopMatrix();


texts: What's the difference between displacement mapping and height mapping?

texts: What's the difference between displacement mapping and height mapping and what is the connection to adaptive tessellation?


texts: How to invert a Tilemap's coordinate system?

texts:
The Tilemap object in Unity uses a coordinate system that grows up-right from (0,0). (ie. with the Origin at the bottom-left of the screen.)  I'm trying to represent a mapping system that has the origin at the top-left of the screen and grows down-right instead, but I can't figure out how to do it.

Scaling the tilemap's Y transform by -1 draws everything upside-down.  Trying to set the object's Tilemap component to custom orientation and setting its Y scale to -1 appears to have no effect, and the editor doesn't accept it anyway, changing what I entered, setting the Y scale back to 1 and the X scale to -1 instead.

Is there any way to fix the Tilemap so that everything draws like normal, except for Y growing downward instead of upward?


texts:
I am trying to brainstorm how to create customizable input.  Any help would be greatly appreciated, but here's my best guess so far.

I could create a custom 'Input' class, with Methods to call for each input.  Like public bool IsRight()", "public bool IsJump()", etc.  Then I could call these methods from any other class.

However, I cannot figure how I would assign these different methods to different keys such that:

public bool IsRight(){
    if (keyboardState.IsKeyDown(Keys.Right)){
        return true;
        }
    return false;
}

works, but I could change the input from 'Right' to 'D', or so on.


texts: Better way to position objects in a Matrix/Grid shape

texts:
I am working on space a invader game and I'm trying to build levels such that in each of them, the aliens are positioned in a different shape.
I have a rectangle shape, circle shape, and a grid-like shape.

I need help to find a better algorithm to position the aliens in the grid shape.

example of the grid shape:

X X X X X X X

X X X X X X X

X X X X X X X

the "algorithm" I made doesn't feel smart enough and I want some guiding.

Here is my code:

//3 Line Formation
     private void setMonsterLinesFormation()
     {
         int spaceX = monsters[0].AreaRect.Width + 10;
         int spaceY = monsters[0].AreaRect.Height + 10;

         int newLinePoint = 7;

         monsters[0].Location = new Point(0, 50);
         Point lastMonsterLoc = monsters[0].Location;

         for (int i = 0; i < monsters.Count; i++)
         {
             Monster currentMonster = monsters[i];
             currentMonster.Location = new Point(
                 x: lastMonsterLoc.X + spaceX,
                 y: lastMonsterLoc.Y);

             if (i == newLinePoint)
             {
                 currentMonster.Location = new Point(monsters[0].Location.X, spaceY * 2);
             }

             if (i == newLinePoint * 2)
             {
                 currentMonster.Location = new Point(monsters[0].Location.X, spaceY * 3);
             }

             lastMonsterLoc = currentMonster.Location;
         }
     }

how should I improve this code?
(if it helps, I will not use more than 30 aliens at a time, here I am using 21)


texts:
I'm trying to create a camera like in Fortnite or Gears of War. It's focus must be to the right side from the character:

But when I rotate the camera, the character slightly shivers. Lerping and multiplying by Time.deltatTime doesn't help.

This is my code:

    using UnityEngine;

    [RequireComponent(typeof(Camera))]

    public class ThirdPersonCamera : MonoBehaviour
    {
        [Header("Sensitivity")]
        [SerializeField] private float xSensitivity;
        [SerializeField] private float ySensitivity;

    [Header("Limit angles")]
    [SerializeField] private float upLimit;
    [SerializeField] private float downLimit;

    [Header("Positioning")]
    [SerializeField] private Vector3 offset;
    [SerializeField] private float maxDistanceFromPlayer;
    [SerializeField] private Transform player;

    private float rotationAboutX;
    private float rotationAboutY;

    // Start is called before the first frame update
    void Start()
    {
        rotationAboutX = transform.localEulerAngles.x;
        rotationAboutY = transform.localEulerAngles.y;
    }

    void Update()
    {
        rotationAboutX -= Input.GetAxis("Mouse Y") * ySensitivity;
        rotationAboutY += Input.GetAxis("Mouse X") * xSensitivity;

        rotationAboutX = Mathf.Clamp(rotationAboutX, downLimit, upLimit);
    }

    // Adjust camera position.
    void LateUpdate()
    {
        Vector3 direction = new Vector3(0.0f, 0.0f, -maxDistanceFromPlayer);
        Quaternion rotation = Quaternion.Euler(rotationAboutX, rotationAboutY, 0);
        // Point to look at in the runitme.
        Vector3 focus = player.position + transform.TransformDirection(offset);

        // Rotate vector according to mouse inputs.
        transform.position = focus + rotation * direction;

        transform.LookAt(focus);
    }
}

It shivers only if offset is not zero. Otherwise it's ok.


texts: How to set a global alpha-blending value in Direct3D 9?

texts:
Is it possible to set an alpha value globally in Direct3D 9, which modulates the pixel alpha values of every subsequent draw?

I would like to let a whole scene fade in/out. I know that for example ID3DXSprite::Draw() lets you set this in the Color parameter, but I'm using pixel shaders to draw 2D circles and rectangles as well, so I would have to pass the alpha value to each of them.


texts: How can I read the smallest mipmap back to the CPU after calling generateMips?

texts:
I'm implementing an adaptive tonemapper based on the standard "scale down the luminance map to a 1x1 texture" approach.

This is my code following the rendering of the luminance map:

 //Average the luminance map by creating a 1x1 mipmap.
    m_pImmediateContext->GenerateMips(m_lumShaderResourceView);

    m_pImmediateContext->CopyResource(m_cpuLumTex, m_lumTexture);

    float* lumMap;
    D3D11_MAPPED_SUBRESOURCE texture;
    m_pImmediateContext->Map(m_cpuLumTex, 0, D3D11_MAP_READ, 0, &texture);
    lumMap = (float*) texture.pData;
    m_avgLuminance = lumMap[0]; // Should work? ^^;
    m_pImmediateContext->Unmap(m_cpuLumTex, 0);

    float lastLum = m_timedAvgLuminance;
    float currentLum = exp(m_avgLuminance);
    float adaptedLum = lastLum + (currentLum - lastLum) * (1 - exp(-.1 * 0.5));

    m_timedAvgLuminance = adaptedLum;

I'd like to read back the calculated average luminance to the CPU for reasons, but what I'm finding is that when I set m_avgLuminance to the mapped-back texture, it's grabbing the pixel at 0,0. If the map were a 1x1 texture, this wouldn't be an issue, but it seems I'm not getting the 1x1 texture, but instead the full-sized luminance texture (screen-sized), so what I wind up with is an image tonemapped by the 0,0 pixel instead of the overall average luminance of the scene.

What am I doing wrong here? How can I read the 1x1 generated mip map texture instead of the full-sized texture?


texts: What format(s) does Blender 2.6 support well enough to use with my game?

texts:
I'm using Blender 2.6 to create meshes to be loaded by my engine while in development. I've noticed that Blender 2.6 has very few exporters compared to previous versions of Blender (but a MUCH improved UI). I was using the FBX exporter since there is the FBX SDK to keep the model loading code from being too large (as opposed to a Collada parser). It seems that FBX wasn't such a good choice since I've started to notice that the exporter is terrible (It doesn't export light DecayType, material colors/intensity and many other things, it leaves them at zero).

What exporter in Blender DOES work well? I'd prefer one that exports to XML since it can be opened in a text editor to fix the paths.


texts: XNA Sprite Clipping Incorrectly During Rotation

texts:
I'm having a bit of trouble getting my sprites in XNA to draw when near the edge of the screen.

Seemingly if you use SpriteBatch to draw then XNA will not draw it if for example (mPosition.X + mSpriteTexture.Width < 0) as it assumes it is offscreen.

However, it seems to make this decision before it applies a rotation. This rotation can mean that, even though (mPosition.X + mSpriteTexture.Width < 0), some of the sprite is still visible on screen.

EDIT: The rotation being a part of the problem is only a hypothesis but to clarify, as the sprite moves towards the edge of the screen at a steady rate (applying a small constant velocity) it will suddenly disappear when it is still partially (usually about half of the sprite) on screen.

My question is, is there a way to get it to draw further outside the viewport or temporarily disable sprite clipping during a certain spriteBatch.draw(...)?

sb.Draw(mSpriteTexture, mPosition,
                new Rectangle(0, 0, mSpriteTexture.Width, mSpriteTexture.Height),
                Color.White, Globals.VectorToAngle(mOrientation), new      Vector2(halfWidth, halfHeight), scale, SpriteEffects.None, 0);


texts: How to use array texture as a replacement for a texture atlas given thousands of block types in minecraft style game?

texts:
I've been trying to figure out how texture atlassing works, only to see people say that you shouldn't do it, and instead use array textures (provided you can target people with that capability, which I can).  What I don't understand is how this is at all a replacement for texture atlas, given a texture atlas can hold many textures at once, only bounded by max texture size, where as an array texture can only handle min 256 on old opengl versions, and min 4096 on newer versions.

In a minecraft style game, you may have all blocks using a separate texture per face, which means 256/6 = 42 max block types, similarly 4096/6 = 682 max block types for the newer opengl versions.   Clearly this is not a good model if you want to have large support for many textures.  Using a texture atlas on modern cards mandates 2^14 size texture minimum,  which with 16x16 square texture, gives 1,048,576 different textures/ or worst case 174,762 max type of blocks per texture.

Given the great disparity between the amount of block types that can be stored via atlassing vs array textures, it seems like one shouldn't use array textures for this type of thing, is there away around this limitation that I don't understand?


texts:
I am making my own UI for my game, no libraries used, basic UI with simple controls and I am almost done. Now, let's say I need to display lots of information, controls or items which obviously won't fit in the screen space. I must use a scroll bar to achieve this task. But how does one make a scroll bar?

I just don't understand how to do it. The concept for vertical and horizontal scrollbars is the same. Virtually there is a huge plain with data, but we can only display cut of it all in a such by such screen space. We use scrollbars to move that viewable rectangle across our giant plain. The scrollbar itself is a displayed line/texture/sprite on the side of the screen which has a button inside that we can interact with by moving it across the scrollbar. The button is dynamic, its size is relative to total item count and possible item count that can be shown in given space. Our button shrinks when there are more items added, expands when items are getting removed and the whole scrollbar disappears when all the items can be successfully displayed at once.

I can't seem to find online tutorials on this matter. Perhaps it's so basic for everyone except me? Still can't wrap my head around it...


texts:
i'm building a car game, and currently working on the steering.

i would like to change the motion of Z rotation so that the car rotates around the Z axis when the wheels are turned. I can't set the rotational motion to equal the steering angle as the car should be able to spin out of control in the game.

This works until the car has an external rotational force put onto it:

Car_Z_rotation_Motion = Car_Steering_Angle;

i was going along the lines of this:

Car_Z_rotation_Motion = Car_Z_rotation_Motion + Car_Steering_Angle;

but this obviously, this causes the turning circle to increase as over time.

What is the best way to control the cars Z rotation with the car steering angle given the possibility of the car spinning out due to external forces that set the Car_Z_rotation_Motion.

sorry if this doesn't make much sense...


texts: If statements seem to act as though the condition is always true

texts:
I have other scripts in the same project using boolean if statements that work fine, but I've tried multiple methods of testing if the if statements below are working and none of them worked!

I don't really know what to ask because I don't know whats going on. I've tried placing theae statements in Update and Start, and in both instances the if statement completely ignored the check and just executed the contents of the block as though the check evaluated to true.

void OnTriggerEnter(Collider other) {
    if(other.gameObject.CompareTag("Player")); {
        working = true;
    }

    Extremity = false;
    if(Extremity); {
        Instantiate(Cannon, transform.position, transform.rotation);
        Extremity = !true;
    }
}

The false statement is only in there to show that even when the bool is set to false immediately before the check, it still runs the Instantiate method inside as though it were true.


texts: Does using the XNA Content Pipline eliminate the overhead caused by file IO when working with a large number of files?

texts:
I'm working on a game in XNA with my goal being that it is fairly data driven so that I can easily tweak the system without having to update code. The research I've done shows that using XML files combined with the content pipeline should provide me with what I need to accomplish this.

That being said, being a developer that really has only been exposed to object oriented programming I have this "one class per file" mindset that I really like because it makes finding and updating what I want to change very easy. This leads me down a path of wanting to set up a system where instead of a large, heavily nested XML file that defines everything (like the web.config files I am used to), I want to go with a folder structure with files that define individual objects - or at the very least something in between. At this point in time I'm not entirely sure how many files I could end up having but I believe it could escalate to a point where it could cause a performance problem if done wrong and if I discover a performance problem because of it, redesign and consolidation of it all could be a big enough chore that I definitely want to try my best to make the right decision up front.

Usually I would see the above mentioned approach being a big performance hog because of the large amount of file IO that would have to be done when loading up the game. Based on my experience with images in the content pipeline, I am assuming that XML files are also combined into a single XNB file when compiled. From this my questions become:

If it is true that all XML files become a single XNB file should I still expect a notable performance loss when loading the data from these "files" or has that overhead disappeared since its all within a single XNB file?

If yes I am sure there tools out there that can make managing / updating a single and very large XML file more manageable which I will begin researching and am open to suggestions on.


texts: Creating charging particles using Shuriken

texts:
I've been trying to create a charging effect using the Shuriken Particle system for the longest time, and I've had little to no luck with it. I've tried setting different curves for the Force over Time and Color over Time, but I always come up empty. However, I've seen examples all over the place for charging particles. The most recent example of charging particles I've seen is from the Space Cowboy game jam entry LOS CUERVOS.

The game has a ship with a laser that requires the player to hold a button down before it fires. It looks like this when charging and firing. I'm specifically talking about the particles surrounding the ball of light that's slowly growing in size over time.

I was wondering if anyone here knew what I may be doing wrong when going about setting up the particle system. Any suggestions relative to the question would be much appreciative.


texts: Does gimbal lock occur only when a combination of local and world rotation axis are used?

texts:
In all the explanations I've seen of gimbal lock, they always refer to the fact that when performing a series of rotations on all axes, it is possible that one rotation might end up aligning an axis with another which causes us to lose a degree of freedom. This never made sense to me since a rotation around e.g. the LOCAL_RIGHT axis will rotation the whole LOCAL_BASIS, no alignment happens. The only explanation I've seen that made sense was this one by DMGregory where it clearly explains that gimbal lock occurs when we e.g. change the yaw using the local basis and the pitch using a world basis.
My question is: Is that the only scenario where gimbal lock occurs or am I missing something? I also thought that quaternions help avoid gimbal lock but again, I'm missing something here because it seems to occur regardless of the rotation representation method (euler/quaternion).


texts:
Whenever I try to install devkitPro, I get these command prompt windows for short periods of time with the following errors:
error: msys: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" is unknown
error: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" could not be looked up remotely
:: Synchronizing package databases...
 msys                                           206.2 KiB   729K/s 00:00 [#######################################] 100%
 msys.sig                                       438.0   B   214K/s 00:00 [#######################################] 100%
error: msys: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" is unknown
error: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" could not be looked up remotely
error: failed to update msys (invalid or corrupted database (PGP signature))
 dkp-libs is up to date
 dkp-windows is up to date
error: failed to synchronize all databases

error: msys: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" is unknown
error: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" could not be looked up remotely
error: database 'msys' is not valid (invalid or corrupted database (PGP signature))

error: msys: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" is unknown
error: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" could not be looked up remotely
error: database 'msys' is not valid (invalid or corrupted database (PGP signature))

error: msys: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" is unknown
error: key "4A6129F4E4B84AE46ED7F635628F528CF3053E04" could not be looked up remotely
error: database 'msys' is not valid (invalid or corrupted database (PGP signature))

Interestingly enough, when I go to the C:/devkitPro folder, I find that I have no devkitpro related files in there whatsoever - just an msys2 folder. I did manage to find a repository online with the files that would have been installed... but when I try to build a project, it says that it can't find the appropriate .specs file.
I would like to know if there is any way I can properly install devkitPro on my windows 10 device. Thanks in advance


texts: Cursor is locked and hidden, and can't click UI

texts:
I have a player with a third person character controller component. I have a problem with the cursor lock: it hides the cursor so I cannot click UI buttons.
protected virtual void CharacterInit()
{
    cc = GetComponent<vThirdPersonController>();
    if (cc != null)
         cc.Init();

    tpCamera = FindObjectOfType<vThirdPersonCamera>();
    if (tpCamera) tpCamera.SetMainTarget(this.transform);

    Cursor.visible = false;
    Cursor.lockState = CursorLockMode.Locked;
}


texts: How to synchronize a parent and child position?

texts:
When watching this video of Unity development, I was following along trying to learn Unity and for the most part understood everything conceptually.

Where I got lost was when I tried using some of the same code and setup in Unity. I got the code working fine, but I got in trouble when I tried to implement the parent-child behavior seen in the video at around 7 minutes regarding the Enemy objects.

The solution described is set up as follows (someone correct me if I didn't understand it properly from the video).

Parent Object

Contains the script which drives behavior and movement
Is located at the origin of the scene (reset the transform in other words)

Child Object

Contains the graphics renderer which draws the actual sprite or 3D object
Is located at the enemy spawn point

For me to get this setup working, I had to run the Translate function explicitly against the child object:

transform.GetChild(0).Translate(dir.normalized * distThisTurn)

However, in the video, it appears to work just fine with only:

transform.Translate(dir.normalized * distThisTurn)

Once he fixes the rotation issue, at about 7 minutes in, this works beautifully, and the enemy travels the path exactly as expected. When I tried this exact same approach, my enemy sprite jumps all over the place. It took me several hours to figure out that I needed to add the .GetChild(0) part. The behavior I saw with the setup from the video is that the invisible parent object moved correctly along the path, and the child went crazy and followed some alternate version of the same path, as if the origin was different or offset, or the path was reflected across some axis.

My question is: what did I do wrong? Can anyone spot how my setup is different than the one used in the video? Did I miss some detail of how he set up his parent-child objects, particularly for the enemies? Or could this be some different behavior due to the version of Unity he is using (I believe mine is newer as I installed it just this week). I think it could also be some small gizmo or feature he neglects to mention that allows you to synchronize the movement of a parent object with its children.

The reason for this setup (at least as given in the video) is it allows you to easily swap out the graphics. The scripting is tied to the parent, so all you have to do is exchange the child for one with different graphics and you're done. That part makes sense, I just don't understand why the exact same code he uses did not work for me. I'm talking only about the Enemy object here - the creeps that move along the path (it's a tower defense game).

I just want to know because I may have to use this extra GetChild call quite a bit, and I feel like it shouldn't be necessary, especially after seeing it work so well in the video. Doing this would also make my scene design a little easier.

I have already read the comments on that video for additional info, as well as looked through Unity forum posts, other posts here on Game Dev.SE, and Google results. It would seem as if this is either old behavior, or there is some small detail neglected to explain in the video of how to synchronize movement of parent and child objects.


texts: How to convert world coordinates to grid movement

texts:
I'm producing a tactical 3D RPG game and I have the following issue:

I want the NPC to move through the grid. The grid is formed by tiles and each tile has a script attached to it. In this script, there is a variable called TilePosition which is a Vector2Int, that I use it to stores its X and Y values in the grid. The NPC character has a script attached to it called NPCPlayer, where a use a Vectir2Int named NPCGridPosition to stores its position in the grid.

Also regarding the NPC, he has a script called NPCMovement. In this script, I've set a raycast that starts from the NPC feet and goes down. I use the raycast to take the TilePosition variable as it is written in the code:

public void MoveNPC()
    {
        if (Physics.Raycast(transform.position, Vector3.down * MaxDistance, out hitDown))
        {
            if(hitDown.transform.tag == "Tile")
            {
                Tile TilesPosition = hitDown.transform.gameObject.GetComponent<Tile>();
                NPCPlayer NPCPosition = this.GetComponent<NPCPlayer>();
            }
        }
    }

However, when I try to move the NPC through the grid, 3 rows ahead, he goes away, because he moves according to the world position, rather than moving according to his tile position.

I'm using these lines of code to make him move:

public void MoveNPC()
    {
        if (Physics.Raycast(transform.position, Vector3.down * MaxDistance, out hitDown))
        {
            if(hitDown.transform.tag == "Tile")
            {
                Tile TilesPosition = hitDown.transform.gameObject.GetComponent<Tile>();
                NPCPlayer NPCPosition = this.GetComponent<NPCPlayer>();

                targetPosition.x = TilesPosition.TilePosition.x + 3 ;
                targetPosition.y = TilesPosition.TilePosition.y;

                this.transform.position = Vector3.MoveTowards(this.transform.position, targetPosition,velocity);
            }
        }
    }

How could I make the NPC to move according to its position in the grid?

I'll be glad if someone can help me a little bit with this.


texts: Shortcut Not Found (installing game created in GameMaker)

texts:
I tested the game I created on 4 computers (ALL Windows 7) and had the following problem at installation time.

The shortcut created by the installer itself came like this:

When I click the following message appears:

Clicking in search appears this:

By clicking the application Bet on Man the shortcut would work correctly. However, not that the players have that task.


texts: Why is the IntelliSense not working when I open a new script in Visual Studio?

texts:
The strange thing is that opened scripts or newly opened ones are working fine. It's the new created C# scripts that are not working.

With not working, I mean the MonoBehaviour is not in light blue color it's in black color.
In this screenshot I took, I marked it with a red circle.

What have I tried so far? I have closed Visual Studio and started over again.
Since it didn't solve it, I closed the unity editor and started it over again, to no avail.

I pressed 'clean solution', I pressed 'rebuild solution', I pressed 'build solution'.

What else can I do ? And why are the other scripts working fine? If I type gameo...it will auto complete it to GameObject but in this specific script it's just not working.

This is a screenshot of the editor. I have in the Hierarchy a Ladder object.
In the Assets I created a folder name Ladder and a script name Ladder. But this Ladder script is not working.

This is the Ladder script and this script was working before but once I created another script inside the ladder folder name Raise empty script the Raise script didn't work and now the Ladder is not working either. But other scripts are working fine.

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

public class Ladder : MonoBehaviour
{
    public Transform charcontroller;

    private bool inside = false;
    private float heightFactor = 3.2f;

    private void OnTriggerEnter(Collider other)
    {
            inside = true;
    }

    private void OnTriggerExit(Collider other)
    {
            inside = false;
    }

    private void Update()
    {
        if (inside == true && Input.GetKey("w"))
            charcontroller.transform.position += Vector3.up / heightFactor;
    }
}


texts:
I'm working on a tilesheet builder tool for my game to speed up tile creation, and I need to save a generated texture2D as a png. I've tried using the .SaveAsPng function but it isn't implemented in Monogame.

Is there any way around this in monogame?

EDIT:
I've tried this:

private void SaveTextureData(RenderTarget2D texture, string filename)
    {
        byte[] imageData = new byte[4 * texture.Width * texture.Height];
        texture.GetData<byte>(imageData);

        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(texture.Width, texture.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        System.Drawing.Imaging.BitmapData bmData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, texture.Width, texture.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);
        IntPtr pnative = bmData.Scan0;
        System.Runtime.InteropServices.Marshal.Copy(imageData, 0, pnative, 4 * texture.Width * texture.Height);
        bitmap.UnlockBits(bmData);
        bitmap.Save(filename);
    }

but it's giving a weird output, and I don't know why:
http://i.imgur.com/XT9Dnjj.png

Thanks for any help!


texts: Unity, Does camera ALWAYS render to RenderTexture?

texts:
I have a camera that renders a simple model to a RenderTexture. I then use that RenderTexture as a texture for my UI with a RawImage component. However, sometimes I disable my UI and therefore you can not see the RenderTexture.

My question is: Does the camera continue to render to the texture in the background even when the texture is not visible?

If I understand how this works I believe it should. If so, simply disabling the camera should prevent it from rendering in the background?

Thanks.


texts: How can I use Editline for an in-game console?

texts:
I'd like to add an in-game console to a C++ game that I am creating.  Although rendering the console and parsing the commands I'm fine with, the text input and editing aspect (e.g. handling left / right keys, backspaces etc...) seems like a lot of effort that I'd rather spend on more interesting things.

I've managed to find a library called Editline that handles the nitty-gritty of console-style text input complete with history and auto-completion, however I'm unsure of how to interface this with my game - in particular all of the examples that I've found use the standard input and output handles and readline() itself is a blocking call.  I need to be able to provide my own input and render the console to my own output, and I also need to make sure that my game loop continues running.

How should I go about doing this?


texts: Resolving prediction error from client side prediction and server reconciliation

texts:
I am writing a network game based on Gabriel Gambetta's articles on client-side prediction/server reconciliation. I have client-side prediction down (using Box2D for prediction) as well as server reconciliation (setting the predicted entity's physics state back and stepping up to the current client time, applying forces from input every step).

This, of course, results in desync; prediction error. My trouble is figuring out how to correct the prediction error. I've tried snapping 100% to the position from reconciliation, but this looks very jumpy. I've also tried changing the percent of the snapping (10%, 80%, 50%, 30%), but these look jumpy after a short time (since the error keeps increasing, the snap distance increases as well).

I've read that you are supposed to interpolate the current position with the position from reconciliation. But what are you supposed to interpolate between? Prediction occurs every frame, so there's no visual time to interpolate the position unless I send the entity back in rendering time, but that defeats the purpose of client-side prediction. Am I approaching this wrong?


texts: How to get image/icon/texture of asset from project window

texts:
I want to get image of any asset from code. Unity can display assets as with images of those assets. Is there a way to get that image from code? I need it to be able to display it in the inspector.

public class AssetIconDisplayAttribute : MultiSupportPropertyAttribute
{
#if UNITY_EDITOR
    public override void DrawInInspector(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUILayout.ObjectField(new GUIContent(property.displayName), property.objectReferenceValue, property.GetContainingObjectFieldType(), true);

        EditorGUI.DrawPreviewTexture(position, @that asset image here@);
    }
#endif
}

Is there a better way to achieve this? The ideal result I want is object field that is displayed like a Texture2D field in inspector but is not a type of Texture2D but stays its own type.

An example of Texture2D:

EDITS:

With AssetPreview.GetMiniThumbnail:

With AssetPreview.GetAssetPreview:

Gives null if the object reference is a component, you have to pass GameObject in order to get the value.

Fix:

AssetPreview.GetAssetPreview((serializedProperty.objectReferenceValue as Component).gameObject)

With AssetDatabase.GetCachedIcon:

@EDIT - note: the code won't work out of the box as some elements which are not important/related for/to this task are custom made.
This is what I currently have and what has been working for me before in the old project. Because of some non-related errors after upgrading to new unity version I can't get an example of how it looked but anyway I wanted to share it.

public class AssetIconDisplayAttribute : MultiSupportPropertyAttribute
{
#if UNITY_EDITOR
    public override float GetPropertyExtensionHeight()
    {
        if (this.serializedProperty != null && this.serializedProperty.objectReferenceValue != null)
        {
            return EditorGUIUtility.singleLineHeight + 80f;
        }

        return EditorGUIUtility.singleLineHeight;
    }

    public override void DrawInInspector(Rect rect, SerializedProperty serializedProperty, GUIContent label)
    {
        EditorGUI.PropertyField(new Rect(rect.position, new Vector2(rect.size.x, EditorGUIUtility.singleLineHeight)), serializedProperty);

        if (serializedProperty.objectReferenceValue != null)
        {
            if (AssetPreview.IsLoadingAssetPreview(serializedProperty.objectReferenceValue.GetInstanceID()))
            {
                EditorGUI.DrawPreviewTexture(new Rect(new Vector2(rect.max.x - 82f, rect.position.y + EditorGUIUtility.singleLineHeight * 1.5f), new Vector2(64f, 64f)), AssetPreview.GetMiniThumbnail(serializedProperty.objectReferenceValue), null, ScaleMode.ScaleToFit);
            }
            else
            {
                EditorGUI.DrawPreviewTexture(new Rect(new Vector2(rect.max.x - 82f, rect.position.y + EditorGUIUtility.singleLineHeight * 1.5f), new Vector2(64f, 64f)), AssetPreview.GetAssetPreview((serializedProperty.objectReferenceValue as Component).gameObject), null, ScaleMode.ScaleToFit);
            }
        }
    }
#endif
}


texts: Unity animation plays in preview but not in playing mode

texts:
I create a simple animation and an override controller for it with code.

//AnimationScript.cs
public Vector3 direction;
public float distance;

void Start()
{
    direction = direction.normalized;
    Vector3 posA = transform.position;
    Vector3 posB = posA + (direction * distance);

    AnimationClip clip = new AnimationClip();
    AnimationCurve curve = AnimationCurve.Linear(0.0f, posA.y, 1.0f, posB.y);
    clip.SetCurve("", typeof(Transform), "localPosition.y", curve);

    Animator anim = GetComponent<Animator>();
    AnimatorOverrideController animatorOverrideController = new AnimatorOverrideController(anim.runtimeAnimatorController);
    // "loop" is the name of clip not name of state
    animatorOverrideController["loop"] = clip;
    anim.runtimeAnimatorController = animatorOverrideController;
}

When I preview animation it works perfect, but when I export and play it, it does not start but camera motion works. What is the reason for that and how do I correct it?

Here are my object settings and controller:


texts: What's the difference between UnityEngine.Random and System.Random?

texts:
What's the different between this

int randomNumber = UnityEngine.Random.Range(0, 10);

and this

// on top of the class
private System.Random _rnd = new System.Random();

// inside a methode of the same class
int randomNumber = _rnd.Next(0, 10);

I know System.Random must always be initialized on the top of your class what's by UnityEngine.Random is not needed. I know also that System.Random works with a intern "clock" and the "random" number is based on that.

My question is now are there some other difference between UnityEngine.Random and System.Random and witch code is better to use for an Unity project?


texts: Can I use an AI engine written in C++ in my Unity game? If yes, how can I do this?

texts:
I am studying some chess and others AI algorithms and the majority of these implementations are made in C and C++, my question is, if I make a chess board and all the graphic thing in Unity, can I make it run with my algorithm written in C++? And how can I make this interface?

Sorry if is it a noob question, I'm just starting at this whole gamedev world.


texts:
How is the typical login, loading the level and spawning handled?
For example:

Client sends "iwanttologinwithcharacterx"
Server does some validity checks and instantiates characterx
Server sends back "loadlevelx"
Client sends "iaminloadingscreen", when finished sends "finishedloading"
Server sends "spawnyourcharacterx"

OR just after the "iwanttologinwithcharacterx" the server tells the client to handle steps 3, 4, and 5 without interaction?

I'm confused about what would be the ideal approach with the least room for errors.

Some info: The level in which players begin is always the same. Players can have multiple characters and during the game they often switch levels (this would be linked to my first question, how would I handle that cleanly? Don't destroy the playerobject between level load and just change their positions accordingly?)


texts: Saving an interface instance into a Bundle

texts:
All

I've have an interface that allows me to switch between different scenes in my Android game. When the home key is pressed, I am saving all of my states (score, sprite positions etc) into a Bundle.  When re-launching, I am restoring all my states and all is OK - however, I can't figure out how to save my 'Scene', thus when I return, it always starts at the default screen which is the 'Main Menu'.

How would I go about saving my 'Scene' (into a Bundle)?

Code

import android.view.MotionEvent;

public interface Scene{

void render();
void updateLogic();
boolean onTouchEvent(MotionEvent event);

}

I assume the interface is the relevant piece of code which is why I've posted that snippet.

I set my scene like so: ('options' is an object of my Options class which extends MainMenu (Another custom class) which, in turn implements the interface 'Scene')

 SceneManager.getInstance().setCurrentScene(options);  //Current scene is optionscreen


texts: What are the implications of not owning the IP of a character graphic in my game?

texts:
I'm currently talking with a design studio for the artworks of my game. They are saying they want to still own the IP of their chracter graphic in my game as they want to sell merchandise with my character idea and their artwork.

I'd like to know what kind of stuffs should I look out for in such an agreement. Does owning the character graphics mean, later they can come up and say me I can't use it in my game?


texts:
So im programming a raytracer at the moment and Im passing a 3d texture from the cpu to the gpu but the gpus texture has not the same values
The uniform part  (its made in Unity):
RayTracingShader.SetTexture(0, "_VoxelPosTexture", tex);

The shader part:
Texture3D<float4> _VoxelPosTexture;

float4 color = _VoxelPosTexture.SampleLevel(sampler_VoxelPosTexture, int3(mapPos), 0);


texts: Nearest neighbor search in 2D to find circles that interacts with point

texts:
I need to store big number of object that every object have range, then I need to find objects that the point are in their range.
So basically I need to store circles and then check who interacts with some point.

R*-tree is very slow at the insert (again I need huge number of objects).
kd-tree and quadtree doesn't allow to store shapes.
another problem with quadtree is that there are no bounds.

There is another algorithms that meet the requirements?


texts: How can I fix this code to spawn multiple types of enemies on the same point with the Corona SdDK?

texts:
I have this code to spawn a simple enemy outside the window:

local function spawnGrupo1()
  local color01 = display.newImage("assets/img/enemigos/blue.png")
  color01.x = 40
  color01.y = -50
  physics.addBody( color01,{density = 5.0, friction = 0.0, bounce = 0} )
end

timer.performWithDelay( 1000, spawnGrupo1, 0)

But I want to be able to spawn multiple enemies from that point, and I can't figure it out.

I tried this, but it doesn't work:

local function spawnGrupo1()
  local numero = math.random(1, 3)

  if numero == 1 then
    local color01 = display.newImage("assets/img/enemigos/blue.png")
  end
  if numero == 2 then
    local color01 = display.newImage("assets/img/enemigos/yellow.png")
  end
  if numero == 3 then
    local color01 = display.newImage("assets/img/enemigos/red.png")
  end
  color01.x = 40
  color01.y = -50
  physics.addBody( color01,{density = 5.0, friction = 0.0, bounce = 0} )
end

timer.performWithDelay( 1000, spawnGrupo1, 0)

How can I approach the problem?


texts: Efficient approaches to updating adjacent grid tiles when one tile is disabled?

texts:
I'm trying to update the surrounding grid of tiles if one of them is disabled (not removed). For example,  imagine we have a grid of tiles each with x representing one texture:

x, x, x, x, x, x
x, x, x, x, x, x
x, x, x, x, x, x
x, x, x, x, x, x
x, x, x, x, x, x
x, x, x, x, x, x

Now if some of these tiles are disabled, I need to update the surrounding tile textures to a different texture:

x, x, x, x, x, x
x, y, y, y, x, x
x, y,  , y, y, y
x, y,  , y,  , y
x, y, y, y,  , y
x, x, x, y, y, y

I'm trying to find the most efficient way of doing this. At present all of the tile data is stored in a dictionary with the key as a vector2.

I'm using C#/Unity 3D, however, I'm not necessarily looking for code but more or less logic on how to do this efficiently so I can program it in.

Any suggestions, examples, or what not would be helpful.

Thanks.


texts: Breakout clone, how to handle/design for collision detection/physics between objects?

texts:
I'm working on a breakout clone, and I wish to create some realistic physics effects for collision - angles on the paddle should allow the ball to bounce, as well as doing curve balls etc. I could use per-pixel based collision detection, but then I thought it might be easier with line/circle intersection testing.

So, then I naturally consider making a polygon class for the line-based objects and use the built-in circle class for the circular objects. That sounds like an OK approach, right? And then just check for collision using the specified algorithm based on the objects that might be within each other's range?


texts: What is the difference between a sprite sheet and a texture atlas?

texts:
I wondering what the difference is between a sprite sheet and a texture atlas?

Aren't both the same? In a sprite sheet you have some Sprites and in a texture atlas you also have some sprites, so what's the difference?


texts:
I need examples of how to read an xml from a server, using Unity3D..

I think it's something like this.. but I can not retrieve the information from the nodes..

An example would be of great help..
thank you..

var url = "http://server.com/test2.xml";

var www : WWW = new WWW (url);
  yield www;

var xml : XmlDocument = new XmlDocument();


texts:
it seems as though i cannot get the draw method to work???
it seems as though the bullet.draw(batcher)
does not work and i cannot understand why as the bullet is a sprite.
i have made a Sprite[] and added them as animation.
could that be it?

i tried

batcher.draw(AssetLoader.bulletAnimation.getKeyFrame(runTime), bullet.getX(), bullet.getY(), bullet.getOriginX() / 2, bullet.getOriginY() / 2, bullet.getWidth(), bullet.getHeight(), 1, 1, bullet.getRotation());

but that dont work, the only way it draws is this

batcher.draw(AssetLoader.bulletAnimation.getKeyFrame(runTime), bullet.getX(), bullet.getY());

below is the code.

// this is in a Asset Class

texture = new Texture(Gdx.files.internal("SpriteN1.png"));
texture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);

bullet1 = new Sprite(texture, 380, 350, 45, 20);
bullet1.flip(false, true);

bullet2 = new Sprite(texture, 425, 350, 45, 20);
bullet2.flip(false, true);

Sprite[] bullets = { bullet1, bullet2 };
bulletAnimation = new Animation(0.06f, bullets);
bulletAnimation.setPlayMode(Animation.PlayMode.LOOP);

// this is the GameRender class

public class GameRender() {
private Bullet bullet;
private Ball ball;

public GameRenderer(GameWorld world) {
myWorld = world;
cam = new OrthographicCamera();
cam.setToOrtho(true, 480, 320);

batcher = new SpriteBatch();
// Attach batcher to camera
batcher.setProjectionMatrix(cam.combined);

shapeRenderer = new ShapeRenderer();
shapeRenderer.setProjectionMatrix(cam.combined);

// Call helper methods to initialize instance variables
initGameObjects();
initAssets();
}

private void initGameObjects() {
ball = GameWorld.getBall();
bullet = myWorld.getBullet();
scroller = myWorld.getScroller();
}

private void initAssets() {
ballAnimation = AssetLoader.ballAnimation;
bulletAnimation = AssetLoader.bulletAnimation;
}

public void render(float runTime) {

Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);

batcher.begin();
// Disable transparency
// This is good for performance when drawing images that do not require
// transparency.
batcher.disableBlending();

// The ball needs transparency, so we enable that again.
batcher.enableBlending();

batcher.draw(AssetLoader.ballAnimation.getKeyFrame(runTime), ball.getX(), ball.getY(),         ball.getWidth(), ball.getHeight());

batcher.draw(AssetLoader.bulletAnimation.getKeyFrame(runTime), bullet.getX(),     bullet.getY());

// End SpriteBatch
batcher.end();
}
}

// this is the gameworld class

public class GameWorld {

public static Ball ball;
private Bullet bullet;
private ScrollHandler scroller;

public GameWorld() {
ball = new Ball(480, 273, 32, 32);
bullet = new Bullet(10, 10);
scroller = new ScrollHandler(0);
}

public void update(float delta) {
ball.update(delta);
bullet.update(delta);
scroller.update(delta);
}

public static Ball getBall() {
return ball;
}

public ScrollHandler getScroller() {
return scroller;
}

public Bullet getBullet() {
return bullet;
}
}

is there anyway so make the sprite work?


texts:
I have 200 prefabs and a scene with an infinite flat plane.

I want to allow user to edit the scene - add, remove, rotate, place that prefabs and save/load resulting "scene" in some custom format.

How can I implement this?


texts:
I am to make a project involving virtual reality for college, I have a budget of $800, the original idea is to get a VR camera (this camera https://www.stereolabs.com or any other similar camera) and program it with Unity to display objects in the environment and or hide real objects in the room by first recognizing it by the camera.

However while searching I found this product (vuforia) and made a simple demo on unity which accomplishes displaying objects on a certain position, I am not sure if I will need the VR camera after this since this can run on any camera. My expereince with unity is good mainly making games, but I have little information about both VR camera hardware and vuforia.

some features that I need to implement include:

Displaying objects (virtual avatar)
hiding objects (real objects that are there like a table)
be able to control avatar using button (adding button as well)

So, the questions I have:

1- can these VR hardware camera be programmed with unity) ?

2- should I just use vuforia and forget about the VR camera, or are there some feature the VR camera can do that I can integrate with vuforia and unity?

3- is unity personal edition able to handle face recognition ?

Thank you


texts:
What type of support/format do you use to store and diffuse your game design documentation?
Wiki? Doc files? Files in Repository? Shared folder? Google Doc?

Please provide pros and cons for each one.


texts:
I have been looking for a list of VR devices that unity supports (or that you can use to develop VR games with).

However i have been unable to find a list. Currently im looking at BOBO VR Z4

But to make sure i do not make any incorrect purchases so it would be really helpful to know supported devices.

Also it is worth noting i'm going to be using the newest version of Unity. (which is currently version 5.6)


texts: Is there any method for mouse or ray to detect object doesn't have collider ? If no, what also can I use ?


texts: Breaking up List into sublists by multiple values

texts:
I'm trying to break up a C# List<InventoryItem> into multiple lists based on two different values: InventoryItem.name and InventoryItem.isStackable.

I want the list to be broken up into multiple lists for the purpose of populating my UI with the data - while keeping non-stackable items in their own list (one item per item slot in UI terms.)

If this is the input:

{
   InventoryItem - name:apple,  stackable:true
   InventoryItem - name:apple,  stackable:true
   InventoryItem - name:carrot, stackable:true
   InventoryItem - name:knife,  stackable:false
   InventoryItem - name:knife,  stackable:false
 }

I should get this output:

{
   InventoryItem - name:apple, stackable:true
   InventoryItem - name:apple, stackable:true
 }
 {
   InventoryItem - name:carrot, stackable:true
 }
 {
   InventoryItem - name:knife, stackable:false
 }
 {
   InventoryItem - name:knife, stackable:false
 }

I'm successfully separating by name alone (see below), but I'm not sure how to take isStackable into account. I'm also using LINQ which I'd prefer to avoid if possible.

var itemsByType     = new List<List<InventoryItem>>();
var inventoryByItem = inventory.GroupBy(x => x.name);
foreach(var v in inventoryByItem)
{
    var itemList = v.ToList();
    itemsByType.Add(itemList);
}


texts: Is it possible to achieve gazing or lip syncing in Unity 5.2 at all, similar to Locomotion done through MecAnim?


texts:
I'm doing shadow mapping for directional lights and I'm trying to get 8 corners of the camera frustrum as a bounding box for the geometry, but I have no idea how. The goal is like in the image below (from another source):

The purple lines represent the final bounding box I am trying to achieve.

From what I know, I am supposed to do use the inverse of the cameras view-projection matrix, like this I believe:

    Vec4 corners[8] = { Vec4(-1.0f, -1.0f, 1.0f, 1.0f), Vec4(-1.0f, -1.0f, -1.0f, 1.0f), Vec4(-1.0f, 1.0f, 1.0f, 1.0f), Vec4(-1.0f, 1.0f, -1.0f, 1.0f),
                        Vec4(1.0f, -1.0f, 1.0f, 1.0f), Vec4(1.0f, -1.0f, -1.0f, 1.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f), Vec4(1.0f, 1.0f, -1.0f, 1.0f) };
    const Mat4 inverseVPMatrix = glm::inverse(viewProjectionMatrix);
    for (uint32_t i = 0; i < 8; i++)
    {
        corners[i] = corners[i] * inverseVPMatrix;
        corners[i] /= corners[i].w;
    }
    float minX = corners[0].x, minY = corners[0].y, minZ = corners[0].z, maxX = corners[0].x, maxY = corners[0].y, maxZ = corners[0].z;
    for (uint32_t i = 0; i < 8; i++)
    {
        if (corners[i].x < minX)
            minX = corners[i].x;
        if (corners[i].x > maxX)
            maxX = corners[i].x;
        if (corners[i].y < minY)
            minY = corners[i].y;
        if (corners[i].y > maxY)
            maxY = corners[i].y;
        if (corners[i].z < minZ)
            minZ = corners[i].z;
        if (corners[i].z > maxZ)
            maxZ = corners[i].z;
    }

And the result would be the bounding box?
But the resulting corners are all maybe at most [-3.0, 3.0], waaay too small.

The view/projection are calculated like this. The view/projection matrices have been working fine so far, so I do not believe the problem lies there, but still.

const Mat4 viewMatrix = camera.GetCameraTransform();
const Mat4 perspectiveMatrix = glm::perspective(mWindow.GetFOV(), mWindow.GetScreenWidth() / (float)mWindow.GetScreenHeight(), mRenderer->GetZNear(), mRenderer->GetZFar());

Mat4 Camera::Orientation() const
{
    Quaternion rotation;
    rotation = glm::angleAxis(mVerticalAngle, Vec3(1.0f, 0.0f, 0.0f));
    rotation = rotation * glm::angleAxis(mHorizontalAngle, Vec3(0.0f, 1.0f, 0.0f));

    return glm::toMat4(rotation);
}

Mat4 Camera::GetCameraTransform() const
{
    return Orientation() * glm::translate(Mat4(1.0f), -mTranslation);
}

Any pointers on what is wrong?

EDIT1: Camera standing at Vec3(0.0f, 3.0f, 0.0f), looking down -Z axis generates the following inverted viewPerspective matrix:

Mat4(-1.24f, 0.0f,   0.0f,   0.0f,
     0.0f,   0.7f,   0.0f    0.0f,
     0.0f,  -15.0f,  0.0f   -5.0f,
     0.0f,   15.0f,  -1,0f   5.0f)

I dont know if that helps?


texts: Detect when a bullet rigidbody is on ground

texts:
I have a rigidbody that is on top of a plane or another rigidbody. How do I check if said rigidbody is on top of it?

I tried to check the Y-part of the velocity but it is never 0, it is always a small value.

What would be the best way to detect this?


texts: Unity WebGL audio not looping when started with playdelayed()

texts:
I have an audioSource in which loop is set to true.
I am starting it playing by calling playdelayed()

In the editor its plays fine. In a webgl build it does not loop. It just plays once.

Also in firefox it does not start playing at the correct time, it is a  good fraction of a second off.

public override void MatchStarted()
{
    Intro.Play();
    Loop.PlayDelayed(Intro.clip.length);
}

PlayScheduled has exactly the same effect.

public override void MatchStarted()
{
    Intro.Play();
    Loop.PlayScheduled(AudioSettings.dspTime + Intro.clip.length);
}

Play(ulong) has the same effect

public override void MatchStarted()
{
    Intro.Play();
    Loop.Play((ulong)(44100 * Intro.clip.length));
}

I'm posting this here seeking workarounds. Any suggestions?
As you can see from my code, my use case is a piece of music with an intro and a loop.

...

ps.
I have seen some posts saying that if the bitrate is not 44.1 KHz this can cause looping issues on WebGl. The audio file in question is set to override the bitrate to 44.1 in its import settings.


texts: Which free HTML5-based game engine meets these requirements?

texts:
I am experienced with traditional JS and HTML but new to HTML5. I want to develop games in HTML5 so that it can work on all devices and browsers, including IE. Additionally, I require the following features:

Physics Engine
Animation
Some AI
Vector drawing and manipulation
Better user/player controls, et cetera

I know there are many options, but just want some one that can give most flexibility... so I want some thing that can also be compiled to achieve maximum functionality.

One that is in my mind is GameKit; but please tell what you guys would suggest that meets my requirements.


texts:
I'm adding to the player's score, and I'm using a per-frame formula like:

int score, displayedScore ;// score is ACTUAL score player has,
// displayedScore is what is shown this frame to the player
// (the creeping/"rolling" number)

float disparity = score - displayedScore ;
int d = disparity * .1f ; // add 1/10 of the difference,
if( !d )  d = signum( disparity ) ; // last 10 go by 1's
score += d ;

Where

inline int signum( float val ){
  if( val > 0 )  return 1 ;
  else if( val < 0 )  return -1 ;
  else return 0 ;
}

So, it kind of works where it makes big changes rapidly, then it creeps in the last few one at a time.

But I'm looking for better (or possibly well known?) score-creeping functions.  Any one?


texts: Display Rich Text in a TextMeshProUGUI component

texts:
I am rading a text to be displayed in a Text UI from an asset using the standard commands

Resources.Load<TextAsset>("nameOfMyTextAsset");

The text is a .txt.

The text contains richtext tags to format the text in bold or italics.
The richtext tags are displayed as such.

I am using TextMesh Pro and insert the text via the following cmd

public TextAsset MainText;
MainText = Resources.Load<TextAsset>("nameOfMyTextAsset");
this.GetComponentInChildren<TextMeshProUGUI>().text = MainText.text;

The text is displayed like this

How can I read text with richtext tags from a text asset?


texts: When ever I have more than 4 point lights in my scene, only 4 show up. Why does it do that? Is there anything I can do to show more than 4 at a time?


texts: How do I make a sprite move to another position using vectors

texts:
Ok, so far I have made the sprite move to a mouse position. But I got a question, does anyone know how to make a sprite move by itself without the use of a mouseclick from Point a to point b using vectors? In which then the sprite stops after reaching point B.

def calcMoveVector(self):
    movetopos = self.posto
    currentpos = self.rect.center
    directtoX = movetopos[0]-currentpos[0]
    directtoY = movetopos[1]-currentpos[1]

    vect = pygame.math.Vector2(10, 10)
    if vect.length() > 0: self.vector = vect.normalize()
    return vect

    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            sys.exit()

        if event.type==pygame.MOUSEBUTTONDOWN:
            mpos = pygame.mouse.get_pos()
            r = pygame.rect.Rect(mpos[0],mpos[1],10,10)
            buttons=pygame.mouse.get_pressed()

            if buttons[0]==True:
                c = pygame.color.THECOLORS["green2"]
                pygame.draw.rect(screen,c,r)
                monster.posto = mpos
                monster.state = Monster.MOVETO
                monster.speed=3


texts:
The questions I've seen are outdated, explained, not to my liking, or just don't work.

Problem: I want to be able to create a game that can scale on all mobile devices with ease and with no pixelation.

Extra Info:

I'm very new to unity and tackling the the software with all my might I'm sorry for being a noob.
I already paired unity with my phone and set the build to android (Nexus 5).
Aspect ratio is 10:16, The game is going to be portrait.
I have no scripts or anything, Its legit a blank game with a camera that has a blue background.

I have some pictures, if you need anything else for my assistance don't hesitate I'm here to learn and take, GULP, Constructive Criticism.

PC

Android


texts: Can unity playerprefs fail to save, and if they do how can I check?

texts:
As the title says I would like to know if playerprefs can fail to save.

If they can, is there some way to check if it save properly / if it failed?

Example :

if (playerprefsFailed)
{
    Debug.Log("Failed to save playerprefs...");
}

I found PlayerprefsException in the Unity API, however I'm confused on how to use it.

I have also googled if they can fail, but couldn't find any results, however considering there is a exception for it, it can probably fail.

The PlayerprefsExceptionis also only thrown on the web player however I would like to know if it can fail, and when, and also how to stop it on a normal pc build.


texts: How can I prevent a component from handling collision events?

texts:
In Unity, I can set the enabled flag of a component to false, and this prevents Unity from running the Update method of the component.
However, Unity still runs other methods of the component, such as OnTriggerEnter2D.
Is there a way to completely disable a component (without removing it), such that it does not get any events at all?

Of course I can manually add a flag to my component, and check this flag from within the event handlers, but I would like to know if there is a built-in solution.


texts: Implementing a Deferred Renderer (Basic Understanding)

texts:
I am trying to implement a Deferred Renderer in Direct3D11. I am fairly new to this.
I already bought a book: Practical Rendering & Computation with Direct3D 11.
However, this book doesnt answer many of my questions.

The Book just says "Call one of the Draw Commands to execute the Pipeline"

In the context of a deferred Renderer I would like to know How I can actually render the different GBuffers, merge them and put actual Lighting to my scene.
Let's say my GBuffers should represent Diffuse, Specular and Normals.
I understand that Vertex Shaders have Constant Buffers that represent my Camera through Matrices. Vertices get Transformed in shaders into ViewSpace.
How Do I get my Diffuse/Specular/Normal information out of that?

Do I have to execute the Rendering Pipeline for every GBuffer?
Technically do I just need to transform my vertices once in a VS and just execute my different GBuffer PS?
The Context Object offers functions like "OMSetRenderTarget". The OutputMerger however is the last stage of the Pipeline, not the first...

The Book itself just calls "Present(0,0)" exactly once and doesnt explain how you actually put things together.

Sorry, quite a lot of different questions :(


texts:
I'm creating a game that has multiple levels. The first three levels are free but the others can be unlocked either using coins (collected during the game) or through IAP. For the coins, I'm using a binary formatter to store the number of coins. The reason I'm using BF is because it persits through all levels(so far this seems to work as the coin score is carried through to other levels). Here is code I have so far in the coinSystem:
public class CoinSystem : MonoBehaviour
{
  public TextMeshProUGUI coinScoreText;
  public int coinScore;

  void Start()
  {
    LoadScore();
  }

  public void Save()
  {
    coinScore++;
    coinScoreText.text = coinScore.ToString();

    BinaryFormatter bf = new BinaryFormatter();
    FileStream file = File.Open(Application.persistentDataPath + "/TotalCoinScore.dat", FileMode.Create);

    CoinContainer coinContainer = new CoinContainer();
    coinContainer.coinScore = coinScore;

    bf.Serialize(file, coinContainer);
    file.Close();
   }

  public void LoadScore()
  {
    if (File.Exists(Application.persistentDataPath + "/TotalCoinScore.dat"))
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/TotalCoinScore.dat", FileMode.Open);
        CoinContainer coinContainer = (CoinContainer)bf.Deserialize(file);
        file.Close();
        coinScore = coinContainer.coinScore;
        coinScoreText.text = coinScore.ToString();

     }
   }
 }

  [Serializable]
  public class CoinContainer
  {
     public int coinScore;
  }

This is code that I use to add to the coinScore.
public class Player : MonoBehaviour
{
  Rigidbody rb;
  public CoinSystem cs;
  public bool dead = true;

  void Start()
  {
    rb = GetComponent<Rigidbody>();
  }

  .
  .
  .
  .

  void OnTriggerEnter(Collider col)
  {
    if (!dead && col.gameObject.tag == "Enemy")
    {
        die();
    }
    if (!dead && col.gameObject.tag == "Coin")
    {
        cs.Save();
    }
  }

So now in the level select menu, I want to add a button that once clicked should enable the user to unlock a particluar level if he has enough coins. For example, if a level requires 500 coins and the user has 600, then on clicking this button the level is unlocked and the total coins now available are 100. And if the number of coins are less than what is required to unlock a level then the user should not be able to unlock that level. I'm not sure how to implement this.


texts:
I'm looking to create some procedural low poly rocks and boulders for a game.

I haven't found much interesting information on the internet other than 3D software articles. Not sure what way to go.


texts:
It seems they completely ruined .fx file loading / parsing in D3D11.

In D3D9, loading an entire effect file was D3DXCreateEffectFromFile( .. ), and you got a ID3DXEffect9, which had great methods like SetTechnique and BeginPass, making it easy to load and execute a shader with multiple techniques.

Is this completely manual now in D3D11?  The highest level functionality I can find is loading a SINGLE shader from an FX file using D3DX11CompileFromFile.

Does anyone know if there's an easier way to load FX files and choose a technique?  With the level of functionality provided in D3D11 now, it seems like you're better off just writing .hlsl files and forgetting about the whole idea of Techniques.


texts: Is using Spherical Harmonics still viable as a technique nowadays?

texts:
I've been implementing spherical harmonics in my Engine for learning purpose.

I was wondering if Spherical Harmonics are still used in modern engine or if they moved on to the more simple cubemaps or pre-convolved environment map with PBR and IBL (e.g in UE4) or any other technique for performance and good visual purpose ? What is the technique with the best performance/good visual ratio compared to SH ?


texts:
I'm trying to follow a youtube tutorial for my new game(images puzzle) and by using it's implementation on github to upload it later on facebook.

When I run the game inside unity editor its work without any problem, but when I export the game to exe or WebGL I get pink images background instead of the image am using.

Youtube tutorial link here.
GitHub repository link here.

The game works Fine inside unity

But shows pink images on web browsers and exe games

Why the images are showing pink background?


texts: Implementing an AI controller for Pacman

texts:
I'm currently implementing an AI controller class that is being used to determine the moves that ms.pacman should make to collect pills and avoid ghosts. In order to determine which is the best move to make in each state (configuration) of the game, I'm using Breadth-First Search to search the decision tree at each state. I've gotten the controller to work (at least somewhat) for Depth-First Search so I was trying to apply the same logic here.

The idea for DFS was to start with a "root" or driver function which would iterate through the possible moves ms. pacman could make at each state in the decision tree and then make a call to a recursive function that searches the tree to find the terminal state (point at which all pills have been eaten) with the highest value (e.g. highest score). This value is returned from the recursive function and stored in a variable in the root function. The root function the returns the move (out of possible moves) that had the highest value in the tree.

Since BFS is not recursive, I was thinking that it wouldn't be necessary to have a driver function like this, so I decided to put it all in one function. Based on DFS, I'm implementing BFS using a queue which stores all of the neighboring states of the current state and visits each state in FIFO order. Once a state is reached in which all pills have been eaten, the current Move should be returned. I'm not sure if this is the best approach, but its what I could come up with. The problem is that the code for the function takes too long to run and ms.Pacman immediately just goes left and runs into a wall. I'm assuming this is because the terminal state is never being found. Here is the function (in Java):

  public MOVE bfs(Game state){
        EnumMap<GHOST,MOVE> ghostMove = new EnumMap<>(GHOST.class);
        MOVE bestMove = MOVE.NEUTRAL;
        Queue<Game> q = new LinkedList<>();
        q.add(state.copy());
        while(!q.isEmpty()){
            Game current = q.peek();
            q.remove();
            for (MOVE move : current.getPossibleMoves (current.getPacmanCurrentNodeIndex())) {
                Game neighbor = state.copy();
                neighbor.advanceGame(move, ghostMove);
                q.add(neighbor);
                if ((current.getNumberOfActivePills() == 0) && (current.getNumberOfActivePowerPills() == 0)) {
                    return move;
                }

            }
        }
        return bestMove;
    }

Is there anything wrong with the design of the algorithm that could be causing this problem?


texts: What would be the optimal order to render something with OpenGL

texts:
That question mind sound dumb, but let me explain:
I'm writing a 3D rendering engine in C++, and my way of getting something to the screen seems rather unintuitive:

I really hope that my artwork is understandable. To be sure, I'll just explain it again with words.

[class Mesh] Load a raw mesh with vertices, uv coordinates, normals,
etc
[class Model] Creates VBO's off the data from the Mesh
[class Shader] Reads and compiles shader
[class RenderObject] Binds Shader
[class RenderObject] Sets uniforms
[class RenderObject] Binds Model VBO
[class RenderObject] draw call

That would be how I get something drawn on the screen. Is that the proper way of doing so? Is there a more or less standard way of doing this?


texts: how can I access to new function via getcomponent?

texts:
using UnityEngine;
    using System.Collections;
    using AssemblyCSharp.portal.www.com;

    public class Game5_Player: MonoBehaviour
    {
//string Logo;
        void Start ()
        {
            func webservice = new func ();//I should use new func(); so how should I use public func?
            //Logo= webservice.getCompanyLogo ();//this work correctly.I can get component Logo In another script but I want know how can I getcomponent my function.
        }
    }

why have I error when use Getcomponent In below?
other script:

using UnityEngine;
using System.Collections;
using AssemblyCSharp.portal.www.com;

public class MasterRange : MonoBehaviour {
        string Logo;
        void Start () {
        Game5_Player game5_Player = GameObject.FindGameObjectWithTag("Player").GetComponent<Game5_Player> ();
            Logo = game5_Player.webservice.getCompanyLogo;
        }
    }

error:

 Assets/MasterRange.cs(21,34): error CS0103: The name `webservice' does not exist in the current context

Is there any way to have a public new function?

using UnityEngine;
using System.Collections;
using AssemblyCSharp.portal.www.com;

public class ScriptA : MonoBehaviour {
string Logo;

public func webservice = new func();

void Start ()
{
    webservice();
    Logo = webservice.getCompanyLogo();
    }
}


texts: Minecraft modding - Dealing extra damage from a sword

texts:
I am making a Minecraft mod, and in my tin sword, when it deals damage to an entity, it randomly deals more damage.

public class ItemTinSword extends ItemSword {

    public ItemTinSword() {
        super(MPPTools.tin);
        this.setUnlocalizedName(MPPToolNames.TIN_SWORD.getUnlocalizedName());
        this.setRegistryName(MPPToolNames.TIN_SWORD.getRegistryName());
    }

    @Override
    public boolean hitEntity(ItemStack stack, EntityLivingBase target, EntityLivingBase attacker) {

        Random r = new Random();

        target.attackEntityFrom(DamageSource.GENERIC, r.nextInt(4));

        return true;
    }
}

But it does not work, and it always only deals normal 5 damage. (Courtesy: Damage Indicators Mod)

So how should I randomly deal more damage? (I'm using forge, btw)


texts: Maximum number of controllers Unity3D can handle

texts:
I've been trying to find out the maximum amount of xbox controller Unity3D can handle on one editor. I know through networking, Unity is capable of having as many people as your hardware can handle. But I want to avoid networking as much as possible.

Thus, on a single computer, and in a single screen (think Bomberman and Super Smash Brothers) how many xbox controllers can Unity3D support?

I have done work in XNA and remember that only being capable of support 4, but for the life of me, I can't find any information that tells me how many Unity can support.


texts: How to make one box Collider 2D go through another in Unity?

texts: How can I make one Box Collider 2D go through another one in Unity? I tried this, but it seems to work only for ordinary Box Collider, but not for Box Collider 2D.


texts: Turn based card game multiplayer: http polling or TCP

texts:
I am working on card games for mobile devices. For multiplayer I will be communicating through a central server. For the purpose I sorted out three options:

HTTP polling
TCP
Websocket (client libraries are not good, so will not use it)

HTTP polling is simple, but I fear it will introduce much more delay and too many HTTP calls. TCP introduces other complications.

So my question is: Is HTTP polling appropriate for a card game? Will the HTTP overhead be too much? How much interval should I keep for polling?

Can you give a sample game based on HTTP polling?


texts: GLSL - rewriting (geometry) shader from #330 to #130 version

texts:
I'm having trouble running example from:
https://raw.github.com/progschj/OpenGL-Examples/master/07geometry_shader_blending.cpp
My graphics card supports only #130 shaders version so I have to rewrite shaders.

I figured out how to fix vertex and fragment shaders. I removed:

layout(location = 0)

from

layout(location = 0) in vec4 vposition;

and added this into my source code:

glBindAttribLocation(shader_program, 0, "vposition");

However I have no idea how to rewrite geometry shader...

#version 130
uniform mat4 View;
uniform mat4 Projection;
layout (points) in;
layout (triangle_strip, max_vertices = 4) out;
out vec2 txcoord;
void main() {
   vec4 pos = View*gl_PositionIn[0].gl_Position;
   txcoord = vec2(-1,-1);
   gl_Position = Projection*(pos+vec4(txcoord,0,0));
   EmitVertex();
   txcoord = vec2( 1,-1);
   gl_Position = Projection*(pos+vec4(txcoord,0,0));
   EmitVertex();
   txcoord = vec2(-1, 1);
   gl_Position = Projection*(pos+vec4(txcoord,0,0));
   EmitVertex();
   txcoord = vec2( 1, 1);
   gl_Position = Projection*(pos+vec4(txcoord,0,0));
   EmitVertex();
}

The main problem is how to get rid of location here:

layout (points) in;
layout (triangle_strip, max_vertices = 4) out;

Can someone help me?

EDIT:
@melak47 - I edited shader, now I'm not getting any error, but window is black.

#version 130
#extension GL_EXT_geometry_shader4 : enable
precision mediump float;
uniform mat4 View;
uniform mat4 Projection;
out vec2 txcoord;
void main() {
    vec4 pos = View*gl_PositionIn[0];
    txcoord = vec2(-1,-1);
    gl_Position = Projection*(pos+vec4(txcoord,0,0));
    EmitVertex();
    txcoord = vec2( 1,-1);
    gl_Position = Projection*(pos+vec4(txcoord,0,0));
    EmitVertex();
    txcoord = vec2(-1, 1);
    gl_Position = Projection*(pos+vec4(txcoord,0,0));
    EmitVertex();
    txcoord = vec2( 1, 1);
    gl_Position = Projection*(pos+vec4(txcoord,0,0));
    EmitVertex();
};


texts: Publishing a game on Steam. Who's name to put in dev info, do I need a company?

texts:
I'm currently paying a game dev to create me a game that I can publish on Steam.

Should I put the devs name or mine for the dev info on Steam?

Do I need a legitimate company in the UK to sell a game on Steam?


texts: How to execute AI in Cocos2d (replacing the Update method)

texts:
What is the best way to run AI in Cocos2d?

I already have my AI implementations. Normally I would execute AI in my game loop by checking how much time has elapsed since last AI execution and whether I can execute it in the current situation, then finally execute it.

From my understanding, Cocos2d removes the concept of the GameLoop and replaces it with Actions, which is great, but I'm not sure how best to employ them to take over in this AI execution. My current workaround is to create a ccSequence that 1) Executes AI, 2) Executes another ccSequence that does the same thing (essentially make an Action loop). What I don't like about this is that Actions all have to be timing needs to be precise in Actions... but I can work with that.

Another thing I don't like is that while this is good for AI... what about rendering actions. I can easily render the result of my Action for me, but what about the result of another AI's action? Such as another AI killed me. I have to wait for my Action Sequence to execute before I can check if anything happened to me, but what if my action was 10 seconds long... do I stand there before I realise I should be dead?

I'm thinking now that I could have multiple Action sequences set up. One for my AI. One for general updates to me. But before I go too far down this path, are Action Sequences really a good replacement for ye olde Update methods?


texts:
I'm still experimenting with some OpenGL in LWJGL, and as I get to know more and more about OpenGL, I start to do more complicated things like multi texturing, shadowmapping and more. Now, right now I'm using the src folder (src/res) for my resources, and use src/resourcename in my code. When I export it, this won't work on another location as the relative path is ofcourse incorrect. What would be the best way of deploying your game with all the resources in one file? Maybe put the files in the jar?

I would like to hear from a few people how they store and deploy their project with resources, thanks!


texts: Unity animations - Is the animation component really deprecated?

texts:
I was looking for a way to create simple transform animations for 2d objects. As example, I wanted to animate all the objects of the scene when the game is paused (i.e. I just want to move the objects outside the screen boundaries with a nice animation). I think that creating an Animator Controller for something like this is not really useful for two reasons:

I don't know where the objects are at runtime. Please correct me if I'm wrong,
I think I cannot dynamically change the value of a keyframe attached to an animation controller, so if I just start a transform animation the sprite will jump at the first keyframe value and then performs the animation. Terrible result.
If I have 200 objects I should create 200 animation controllers with 200 animations.

Creating animation programmatically would be great, but I read on forums and here on stackexchange that you cannot dynamically handle keyframes... and that I HAVE to use the Animation Controller, otherwise I can use the Legacy animation system (that to me sounds so... deprecated :P)

Then I checked this page of the documentation: http://docs.unity3d.com/ScriptReference/Animation.html

They talk about the "Animation" component... and they don't say this element is Legacy/Deprecated. Looking at this page it seems that I have a lot of control over Animation actually... but know I'm completely confused! Is this component deprecated or not? Should I always use the Animation Controller instead?


texts: Learning OpenGL: Red and Blue book still relevant?

texts:
I've recently purchased the Orange book( GLSL ) and am wondering if it is important at all to read through the red and blue books as well?

Any thoughts?


texts: How to calculate collision normal between two AxisAlignedBox's?

texts:
I'm writing a physics simulation in Ogre3D and I'm trying to figure out how to calculate the collision normal between two Ogre::AxisAlignedBox's.

I am checking for collisions using the "intersects" function then calculating the collision normals as below, but I am almost certain that this is where I am going wrong as my collisions are very unpredictable:

Ogre::AxisAlignedBox intersection = boxA.intersection(boxB);
Vector firstCollisionNorm = boxA.getCenter() - intersection.getCenter();
Vector secondCollisionNorm = boxB.getCenter() - intersection.getCenter();

After this, I am normalizing the collision normals, calculating the impulse magnitude using dot product, mass and relative velocity, then I multiply the collision normals by the magnitude to get the final impulse force vector, which is added to my current force vector as "impulseForce / deltaTime" for the next step of euler intergration.

If anyone could help me out I would greatly appreciate it!

Thanks