texts: Why do I seem to lose control of my computer when full screen Unity game loses focus?

texts:
When I press Ctrl+Alt+Esc or Ctrl+Shift+Esc the game loses focus, but then the whole PC is unusable  and I need to restart the PC to regain control

How do I prevent the computer from locking up (let the player control their PC) when a full screen Unity game loses focus?


texts: Vector movement in space type game (Mouse rotation)

texts:
I'm having an issue with my movement in my 'game' prototype. It's basically not working and admittedly my knowledge with vectors is lacking.

The issue I'm running into is that the ship won't move in the direction of my mouse. (I'm using my mouse as rotation)

Mouse look example video I took yesterday

I would love it if someone could look at my code/Vector math and tell me if they can notice anything I'm doing terribly wrong, I would greatly appreciate it.

private Vector2f acceleration;
private Vector2f force;
private Vector2f velocity;
private Vector2f position;
private Image image = null;
private float mass;
private float angle;

//Constructors
public Ship(float xin, float yin) {
    this.mass = 5000; // temp value of mass
    this.angle = 0;

    // Image of the ship
    try {
        this.image = new Image("res/ship.png");
    } catch (SlickException e) {
        e.printStackTrace();
    }

    // Vectors
    position = new Vector2f(xin, yin);
    velocity = new Vector2f(0, 0);
    acceleration = new Vector2f(0, 0);
    force = new Vector2f(0, 0);
}

public void update(Input input, float delta) {
    float mouseX = input.getMouseX();
    float mouseY = input.getMouseY();

    float xDistance = mouseX - (position.x + image.getWidth()/2);
    float yDistance = mouseY - (position.y + image.getHeight()/2);

    angle = (float) (Math.toDegrees(Math.atan2(yDistance, xDistance)) + 90);
    image.setRotation((float)angle);

    if (input.isKeyDown(Input.KEY_W)) {
        this.move(delta);
    } else if (input.isKeyDown(Input.KEY_S)) {
        //this.move(delta);
    } else {
        acceleration = new Vector2f(0, 0);
    }
}

public void move(float delta) {
    /*
     * Acceleration = Force / Mass
     * Velocity += Acceleration * ElapsedTime (delta)
     * Position += Velocity * ElapsedTime (delta)
     */
    System.out.println(delta); //debugging
    //delta = delta/10; //debugging
    //System.out.println(delta); //debugging
    force = angleToVector(angle); // Direction
    force = force.normalise();
    force = force.scale(2);
    acceleration = force.scale(1/mass);

    velocity = velocity.add(acceleration.scale(delta));
    position = position.add(velocity.scale(delta));
}

public Vector2f angleToVector(float angle) {
    return new Vector2f((float)Math.cos(angle), (float)Math.sin(angle));
}

If you want to see the full .java for my ship class here's a link.


texts: Need physics algorithm for modeling ceiling collapse in voxel-based game

texts:
I'm looking for algorithms on how to model the physics of cave-ins/collapses for a game idea I am working on. The game allows the player to extensively mine 3D voxel-based asteroids, and I want areas that are insufficiently supported to collapse under their own weight. Making the problem even more challenging, gravity will be non-uniform (the direction it pulls will depend on where a given voxel is in relation to the asteroid's center of mass), and the number of voxels in the asteroid will be too large to model them all individually (I am using a sparse voxel octree to model the asteroid).

Hopefully, someone will be able to provide links to articles discussing suitable algorithms, or can provide ideas on how to solve the problem. If you need more details, please ask.

Edit 1: It does not need to be very accurate, I'm looking for something that would be a reasonable approximation for a Minecraft or Dwarf Fortress style game. I am mostly interested in how to determine where sections should break off when blocks are added or removed, moving the bodies after they break isn't part of this issue.

Edit 2: My initial idea was to calculate the force on each block then iteratively distribute the forces amongst neighbors. However, this would require an entry for each block, while only blocks on the surface have entries in the data structure. Modeling all blocks on the scale I want would likely be prohibitive - I would like to have bodies of at least 10,000,000 voxels, of which 200,000 will be on the surface and need to be stored.


texts: Why is ScreenToWorldPoint always giving same coordinates with mouse position?

texts:
Whenever I use ScreenToWorldPoint(Input.mousePosition) and display the output in console this always gives me the same coordinates.
MyCode:
Vector3 screenToWorld;

void Update()
{
    screenToWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Debug.Log(screenToWorld);
}


texts:
I'm working on a software and I'd to move the rendering API from SlimDX to SharpDX. I've done that but I noticed that the solid polygon are not drawn correctly i.e., even if the polygon is at the back side of another polygon, part of it is visible, also part of the polygon lie inside terrain that is also visible. Below are the images from SlimDX implementation and SharpDX implementation for reference:

I tried to set the Stencil & ZBuffer but there are not working as expected. I've already applied DepthBias to it which worked fine with SlimDX but not with SharpDX.
Please let me know if, I'm missing something or I'm doing something wrong.
Update 1 (Polygon rendering):
// set the render state to device
device.SetRenderState(RenderState.AlphaTestEnable,
                      true);
device.SetRenderState(RenderState.AlphaBlendEnable,
                      true);
device.SetRenderState(RenderState.SourceBlend,
                      Blend.SourceAlpha);
device.SetRenderState(RenderState.SeparateAlphaBlendEnable,
                      true);
device.SetRenderState(RenderState.DestinationBlendAlpha,
                      Blend.One);
device.SetRenderState(RenderState.SourceBlendAlpha,
                      Blend.InverseDestinationAlpha);

// set the render state to the device
device.SetRenderState(RenderState.DepthBias,
                      -1E-06f);

this.effectVectoring.Begin(FX.None);

// binds the vertex buffer to device data stream
device.SetStreamSource(0,
                       this.vertexBuffer,
                       dataGeometry.FillVertexOffset,
                       stride);
// pass 1 to shader as a pass if it is 3D mode else 0
this.effectVectoring.BeginPass(is3D ? 1 : 0);
// renders the non-index geometric primitives using the data from current input stream
device.DrawPrimitives(SharpDX.Direct3D9.PrimitiveType.TriangleList,
                      0,
                      primitiveCount);
// end the pass
this.effectVectoring.EndPass();

this.effectVectoring.End();
device.SetRenderState(RenderState.AlphaBlendEnable,
                    false);
device.SetRenderState(RenderState.AlphaTestEnable,
                    false);
device.SetRenderState(RenderState.DepthBias,
                    0);
device.SetRenderState(RenderState.FillMode,
                    FillMode.Solid);
device.SetRenderState(RenderState.SeparateAlphaBlendEnable,
                    false);

Update 2 (Terrain rendering):
device.SetRenderState(RenderState.AlphaBlendEnable,
                      false);
device.SetRenderState(RenderState.AlphaTestEnable,
                      false);
device.SetRenderState(RenderState.CullMode,
                      Cull.Counterclockwise);

device.Indices = this.terrainIB;
device.SetStreamSource(0,
                       this.terrainVB,
                       0,
                       12);
device.VertexFormat = VertexFormat.Position;

// Set texture in effect...

effect.Begin(FX.None);

effect.BeginPass(pass);
device.DrawIndexedPrimitive(PrimitiveType.TriangleStrip,
                            baseVertexIndex,
                            0,
                            vertexCount,
                            startIndex,
                            primitiveCount);
effect.EndPass();

effect.End();
device.SetRenderState(RenderState.FillMode,
                      FillMode.Solid);
device.SetRenderState(RenderState.CullMode,
                      Cull.None);


texts: What is the best approach to informing individual GUI objects about the screen size?

texts:
I have a problem with designing classes for my game which I create.

In my app, there is:

the class CGame, which contains all the information about game, itself.
For example, screen width, screen height, etc. In the main() function, I
create a pointer to the CGame instance.
the class CGUIObject, which includes fields specifying its position and
draw() method, which should be able to draw an object according to the
screen size.
the class CGUIManager, which is a singleton, and includes a list of
CGUIObjects. For each object, in a list, it calls the draw()
method.

Now the problem is, each CGUIObject needs to know the screen size, which is held by CGame. However, I find it inefficient to include pointer to CGame instance in every object.

For clarity's sake, I'll provide some simple code:

class CGame
{
   int screenWidth;
   int screenHeight;
};

class CGUIObject
{
   CPoint position;
   void draw();     // this one needs to know what is a screen's width and height
};

class CGUIManager   // it's a singleton
{
   vector<CGUIObject*> guiObjects;
   void drawObjects();
};

And the main.cpp:

CGame* g;

int main()
{
   g = new CGame();

   while(1)
   {
      CGUIManager::Instance().drawObjects();
   }

   return 0;
}

What would be the best approach to provide the screen size to each CGUIObject?


texts:
I was watching a tutorial on using a BufferStrategy in Java and I wanted to test a very simple example. The issue is that it flickers intensely and it seems as if a piece of the starting oval stays on the screen. I know that the loop is a very bad practice but I just wanted to very simply test the BufferStrategy.

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferStrategy;

public class Game extends JFrame {
    private Canvas canvas = new Canvas();

    public Game() {
        setBounds(0, 0, 1280, 720);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        add(canvas);

        setVisible(true);

        canvas.createBufferStrategy(3);
        BufferStrategy bufferStrategy = canvas.getBufferStrategy();

        int x = 0;
        int i = 0;

        while(true) {
            i++;

            if(i == 10) {
                i = 0;
                x++;
            }

            bufferStrategy = canvas.getBufferStrategy();
            Graphics g = bufferStrategy.getDrawGraphics();
            super.paint(g);
            g.setColor(Color.RED);
            g.fillOval(x, 200, 50, 100);
            g.dispose();
            bufferStrategy.show();
        }
    }

    public static void main(String[] args) {
        new Game();
    }

}


texts:
When designing a behaviour tree that controls an agent, is it possible to construct the tree so that the agent first attempts task A, then depending on whether task A succeeds it attempts either task B or task C? That is, if A succeeds, the agent attempts task B, otherwise it attempts task C? Kind of like the ternary conditional operator?

The following may at first glance seem to work:

* Selector
|
+---* Sequence
|   |
|   +---* A
|   |
|   +---* B
|
+---* C

or equivalently, Selector(Sequence(A, B), C). However, if A succeeds and B fails, the sequence will still fail and C will be attempted (which it shouldn't since A succeeded).

This tree does run B if A succeeds and C if A fails and never runs both B and C:

* Selector
|
+---* Sequence
|   |
|   +---* A
|   |
|   +---* B
|
+---* Sequence
    |
    +---* Inverter
    |   |
    |   +---* A
    |
    +---* C

or equivalently, Selector(Sequence(A, B), Sequence(Inverter(A), C)). This is assuming that A yields the same result both times (oterwise either none of B and C will be attempted, or both will be attempted). However, this has the issue that will be attempted A twice if either either A or B fails.

What I want to achieve could be pseudo-coded like A ? B : C or like B if A else C. Can this be achieved with a behaviour tree?


texts:
I have a simple question that I can't find a answer to:

With the .NET Framework what is the difference in saying "folder1/folder2/file" and "folder1\\folder2\\file" in a file directory? Is there even a difference?

Also what does the "@" character do? I'm not sure if this is XNA specific or .NET specific but here is an example: ContentManager.Load<Texture2D>(@"SpriteSheets/Tile");

Thanks.


texts:
I'm working on a 2d game, where the player can take damage and die. And upon death, player object gets destroyed.

However, some attributes of player shouldn't be affected by his death, such as lives, ammo, current weapon and so on. I'm wondering where to store these values.

I'm using c++.


texts: Automatically setting tile variations in a 2D map editor

texts:
I'm looking to make a map editor for a 2D strategy tile-based game (I am using OpenGL with SDL and writing the game in C). My game levels are made up of a set amount of different tiles, like a river tile, a mountain tile, a sea tile, etc.

A level is a struct holding the tiles like this:

struct Level {
    Tile[LEVEL_ROWS_AMOUNT][LEVEL_COLUMNS_AMOUNT];
    ....

I initialize the level by filling it with a plain default tile. Then I just iterate every tile and render them one by one.

Every one of these tiles always has the same properties no matter what, BUT should look different depending on the tiles surrounding them. For example, if a river tile has a river tile to its left and to its bottom, it should take a top-right corner "L" shape appearance, while the river tile to the left should be horizontal and the one to the bottom should be vertical.

Here's an illustration of what I mean:

All of my tiles' visuals are loaded into a single sprite sheet image, and I have a JSON file pointing to the coordinates of every tile inside the image, where every entry looks like this:

{
"variations": {
    "horizontal": [
        {
            "x": 32,
            "y": 0
        }
    ],
    "top_right": [
        {
            "x": 320,
            "y": 96
        }
    ],
    ...
},

So every tile I place down in my game has multiple possible visual variations, and I'm able to manually set which one a given tile should have. But like stated above, I would like to make this process automatic upon placement of the tile.

What would be a good way to implement this? I have a good amount of unique tiles (around 20 or so) and most of them would require unique logic. I'll also probably be adding more tiles in the future, so I'm hoping I can find a way that doesn't involve long hard-coded if statements.


texts: what exactly is the logic behind 6502 and precise clock cycle emulation?

texts:
Key questions to consider based on page 10 of this document:

http://archive.6502.org/datasheets/rockwell_r650x_r651x.pdf

What does page 10 imply by "Add 1 to N if page boundary is crossed"?
What does page 10 imply "Add 1 to N if branch occurs on the same page?"
What does it mean by add 2 to N if branch occurs to different page?
Does read and write to other devices ie.RAM cause any irregularities in clock cycles?
Are there any other factors that could affect clock cycles on the 6502 (more specifically the NES) ?


texts:
How do I calculate the time between frames on Android? I'm using this for the thread:

public class GameThread extends Thread
{
  private int FPS = 30;
  private double averageFPS;
  private SurfaceHolder surfaceHolder;
  private Game gamePanel;
  public boolean running;
  public static Canvas canvas;
  public static double deltaTime;

  public GameThread(SurfaceHolder surfaceHolder, Game gamePanel) {
    super();
    this.surfaceHolder = surfaceHolder;
    this.gamePanel = gamePanel;
  }

  @Override
  public void run() {
    long startTime;
    long timeMillis;
    long waitTime;
    long totalTime = 0;
    int frameCount =0;
    long targetTime = 1000/FPS;

    while(running) {
      startTime = System.nanoTime();
      canvas = null;

      //try locking the canvas for pixel editing
      try {
        canvas = this.surfaceHolder.lockCanvas();
        synchronized (surfaceHolder) {
          this.gamePanel.tick();
          this.gamePanel.render(canvas);
        }
      } catch (Exception e) {
      } finally {
        if(canvas!=null)
        {
          try {
            surfaceHolder.unlockCanvasAndPost(canvas);
          } catch(Exception e){
            e.printStackTrace();
          }
        }
      }

      timeMillis = (System.nanoTime() - startTime) / 1000000;
      waitTime = targetTime-timeMillis;

      try{
        sleep(waitTime);
      } catch (Exception e) {
      }

      deltaTime = waitTime;
      totalTime += System.nanoTime() - startTime;
      frameCount++;
      if(frameCount == FPS)
      {
        averageFPS = 1000/((totalTime/frameCount)/1000000);
        frameCount =0;
        totalTime = 0;
        System.out.println(averageFPS);
      }
    }
  }

  public void setRunning(boolean b)
  {
    running=b;
  }
}

I tried doing it like in normal Java, but it didn't work (it only lead to a crash).


texts: Custom inventory items based on inheritance

texts:
So, here's the scenario:
I'm building an RPG. Like most of the other RPGs on the market, my game will feature an inventory and of course, inventory items. So far I've worked well with using a single class for all items, because I did not need anything else than character stat alteration on item usage (consumption). However, I'd like some items to have a more exotic effect. Think of something like when the user consumes a transformation potion, he automatically turns into a beast.

In order to achieve this I've thought about declaring a new class that inherits from BaseItem for each item. Each descendant would override some methods (like void OnConsume()), to change the base behavior.

This works fine, but when it comes to inventory management, I have some issues. The actual inventory will have to work with BaseItem components only (for obvious reasons, as it's an enumerable collection of objects of the same type); casting any descendant to the base class is possible, so no problems in adding items to the inventory. But how can I keep track of the descendant's type (class) for each item in the inventory? And how to perform the descendant's OnConsume from withint he inventory, for each item?

Let me know if you can think of a better solution than mine, or if you can think of a solution to my problem only.

Development is done in C#, inside Unity 3.5.

Thanks!


texts: Drawing large 2D sidescroller level terrain

texts:
I'm a relatively good programmer but now that it comes to add some basic levels to my 2D game I'm kinda stuck.

What I want to do: An acceptable, large (8000 * 1000 pixels) "green hills" test level for my game.

What is the best way for me to do this?

It doesn't have to look great, it just shouldn't look like it was made in MS paint with the line and paint bucket tool.

Basically it should just mud with grass on top of it, shaped in some form of hills.

But how should I draw it, I can't just take out the pencil tool and start drawing it pixel per pixel, can I?


texts: libgdx glClearColor not setting right color?

texts:
i just new to libgdx and trying to understand the example code, the following code sets the bg color

        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        Gdx.gl.glClearColor(60,181,00,0f);

my expected color is green,  R:60 Green:181 B:0, but the about code show me yellow color in my android app, anything  i'm doing wrong?

http://rapid-tools.net/online-color-picker/


texts:
I'm working on a compute shader for a 3d texture where I want to evaluate pixels in a specific order, is there any way to do this?
let's say that I have made a texture using the following code;

tex = new RenderTexture(64, 64, 0);
tex.volumeDepth = 6;
tex.isVolume = true;
tex.enableRandomWrite = true;
tex.Create();

Now let's say that for example I want to make the following computation on the gpu rather then cpu:

tex[0]=basetex //all values where z =0 are some basic 2d texture
for(int z=1;z<6;z++){ //loop over every z level
 for(int x=1;x<64;x++){ //loop over every x level
        for(int y=1;y<64;y++){ //loop over every y value
         tex[x][y][z-1]=tex[x-1][y][z-1]+tex[x-1][y][z-1]+tex[x][y-1][z-1]+tex[x][y+1][z-1] //add all values next to this pixel on the z value bellow
      }
  }
}


texts: Are all games made by drawing each frame?

texts:
I am a beginner learning about computer animation(for games). So far, the only method that I have come across is drawing each frame, every frame update. So at the start of every frame, the entire frame is erased, and then the things for that are needed that frame are redrawn.

My question is whether or not this method is the only one that is used for making animations and games. It seems like it is a bit inefficient. I also don't quite understand how this method would work for 3d games. Could someone please explain this in more detail?


texts: Optimising out tiles outside of viewport

texts:
I am playing around with the HTML5 canvas and have begun implementing a tile engine.

However, it's currently very inefficient: I have a 100x100 2D array and my code loops through the whole thing every frame. (Very bad, I know.) I'd like to optimise the rendering loop by using a viewport or camera to determine which parts of the area are view.

Here is an example. I haven’t added the camera offset yet because I’m not sure how:

for (var y = 0; y < state.map_data.length; y++) {
    col = state.map_data[y];
    for (var x = 0; x < col.length; x++) {
        color = (state.map_data[y][x]==1)?'#fff':'#000';
        self._draw({
            type:'rec',
            x: x * state.tile_width,
            y: y * state.tile_height,
            width: state.tile_width,
            height: state.tile_height,
            fill: color,
            visible: true
        },self.ctx);
    };
};

Here is a link to the game as it is.

How can I make this more efficient?


texts: Can I transfer C# coding I do in Unity for practice to another 3d engine?

texts: If I use a C# coding in Unity 4, can I transfer that coding into another non-Unity engine as long as it accepts C# too? I hope this question makes sense. Thank you in advance.


texts: Add tiles to both sides of TileMap List in MonoGame

texts:
This is what my tile map looks like (red highlighting added for clarity):

My code:
private List<List<int>> _layoutLayer = new List<List<int>>(50); // Layout Layer
private List<List<int>> _trLayer = new List<List<int>>(50); // Transitional Layer
private List<List<int>> _entityLayer = new List<List<int>>(50); // Object Layer
private List<List<int>> _logicLayer = new List<List<int>>(50); // Logic Layer

// To add a tile
if (inputManager.IsMouseHeld(true))
{
    try
    {
        switch (_currentLayer)
        {
            case LayerRepresentation.LayoutLayer:
                _layoutLayer[_gridMouseY][_gridMouseX] = _currentTile;
                break;
            case LayerRepresentation.TransitionalLayer:
                _trLayer[_gridMouseY][_gridMouseX] = _currentTile;
                break;
            case LayerRepresentation.EntityLayer:
                _entityLayer[_gridMouseY][_gridMouseX] = _currentTile;
                break;
            case LayerRepresentation.LogicLayer:
                _logicLayer[_gridMouseY][_gridMouseX] = _currentTile;
                break;
        }
    }
    catch
    {
         // Player clicked outside of map bounds, add specified amount of tiles to map
    }
}

What I need:
When the player clicks outside of map bounds for example on the point A, add the amount of tiles between point A and the map to the map's height. Do the same with point B, but add to the map width instead.
What I've tried:
    // Inside the above catch block
    if (_mapHeight - _gridMouseY == 0 && _gridMouseX < _mapWidth && _gridMouseX > -1)
    {
        List<int> tempDefaultLayout = new List<int>();
        List<int> tempDefaultOther = new List<int>();

        for (int i = 0; i < _layoutLayer[0].Count; i++)
        {
            tempDefaultLayout.Add(0);
            tempDefaultOther.Add(-1);
        }
        _layoutLayer.Insert(_gridMouseY, tempDefaultLayout);
        _trLayer.Insert(_gridMouseY, tempDefaultOther);
        _entityLayer.Insert(_gridMouseY, tempDefaultOther);
        _logicLayer.Insert(_gridMouseY, tempDefaultOther);
        _mapHeight++;
    }
    else if (_mapWidth - _gridMouseX == 0 && _gridMouseY < _mapHeight && _gridMouseY > -1)
    {
        for (int y = 0; y < _layoutLayer.Count; y++)
        {
            for (int x = 0; x < _layoutLayer[y].Count; x++)
            {
                if (_layoutLayer[y].Count <= _mapWidth)
                {
                    _layoutLayer[y].Add(0);
                    _trLayer[y].Add(-1);
                    _entityLayer[y].Add(-1);
                    _logicLayer[y].Add(-1);
                }
            }
        }
        _mapWidth++;
    }
    return;

The problems:

The first part is about adding tiles to the height (only one row at a time) Adding the temp Lists to the layer Lists with List.Add() doesn't work, I don't know why. I used List.Insert instead.
The second part is used to add a single column to the map one at a time.

Any help would be appreciated.


texts:
I have the following setup:
MainCamera render everything except ImageTurret layer.
TurretCamera render only ImageTurret layer on a RawImage

My problem is:
MainCamera render everything and TurretCamera render nothing
TurretCamera render only if set to default layer.


texts: Is It Better To Generate A Pre-Generated Map or A Randomly Generated Map When Using Tile Properties?

texts:
So I am contemplating whether or not to add a Pre-Generated Map or a randomly generated map into my game. But I also need to add Tile properties into the map (i.e. so that water tiles aren't being walked on by the player, etc.). Which way is better, to add tile properties to an existing image file or to add tile properties to a randomly generated map?

I want to make it so that I can add Tile properties to a pre-generated map as I already have one ready to go, but is it even possible to add tile properties to a pre-generated map?

I am using Java and the Slick2D gaming engine.


texts: Accessing a char array from another class

texts:
I'm working on a crossword puzzle game. In order to set the letters in my tiles, I have a script attached to text components that accessing a char array that stores my letters. It looks like this:

First class:

  public class GenerateBoard : MonoBehaviour
  {
    public static char[,]gameBoard = new char[15,15];
    void Start()
    {
        gameBoard[0, 0] = 'W';
    }

Second class:

public class SetLetter : MonoBehaviour
{
    Text letter;
    public int x;
    public int y;
    // Start is called before the first frame update
    void Start()
    {
        letter = GetComponent<Text>();
        letter.text = GenerateBoard.gameBoard[x,y] + "";
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log("glitch: " + GenerateBoard.gameBoard[0, 0]);
    }
}

I would expect Debug.Log to print 'W' but it appears to be empty. Why isn't it accessing the letter 'W' from the first class? When I use Debug.Log in my first class it properly prints 'W'.


texts: How can I apply a fullscreen shader on a specific layer?

texts:
How do I apply a full screen shader on one layer of objects using LWRP/URP and shader graph? I want to pixelate only my particlesystems, but nothing else. I want the effect of pixelcamera, but only on particlesystems.

Normaly I whould have a seperate camera rendering the particlesystem and then pixelate only that camera, but I can't have a transparent background (dont clear) for some reason while using LWRP. If I have 2 cameras, the background only turns black and only renders the particles :(


texts: How do I make Windows store recognize multiple resolutions?

texts:
I'm currently developing a XNA Game for Windows phone 8, it works with every emulator resolution (WXGA, WVGA, 720p). However, when I upload the XAP to the Windows phone store it tells me that only WVGA resolution was detected.

Do I have to add some code to make the app downloadable for WXGA phone owners ?


texts:
This is a screenshot from RE7.
I have once seen the same image effect in Unity, but I don't remember the name:

I'm not talking about AA or DOF here, I mean this grainy / greenish thing, I don't know how to describe it...
At first I thought the name was something like "Anisotrophic filtering", but that didn't bring up anything that looked like it.
Can anybody tell me the name of the effect that I see here?
Edit:
It can be seen in the start screen of this video, too:
https://www.youtube.com/embed/aaN3MNb9ij0?feature=oembed
Both screenshots look pretty similar to me, so I guess it's the same effect?
Edit 2:
The pixels seem to shift into red / blue the closer they get to the edge of the screens.
I have drawn red arrows to region where this effect is very visible to me.
These pixels appear as "shifted" to me.
I think this effect is more visible at the edge of the screen.

Thank you.


texts: What is the game design rationale behind forcing MMO players into gameplay styles they do not enjoy?

texts:
Most MMOs have a varied assortment of content. However, not everyone enjoys particular content styles. There are a lot of PvE players who don't like PvP, and vice versa. There are players who only want to do small group content or large group content, but not the other type. There is always an argument among the playerbase on whether it's a good idea to encourage players to participate in content styles they do not enjoy. The most common argument is that it makes the world feel more alive if there's more to do. However, I personally am of the opinion that forcing players to do content that they do not enjoy, for example through exclusive player power rewards or cosmetic rewards, will make them enjoy the rest of the game less and in turn stop playing sooner.

What is the potential game design rationale for an MMO to force PvE players into PvP and vice versa, or to force players who prefer to play in small groups to do large group content?


texts: Utilize remote PC to Boost UE4 Editor Performance

texts:
As the title suggests, I would like to know how I can take advantage of a desktop PC at my workplace to help boost the performance of the editor on my laptop at home.
General editor actions such as shader compilation, light building, and terrain generation require large amounts of CPU power and RAM, both of which are much better suited for a desktop PC. It would be great if there is a service that can allow me to offload the tasks from my laptop to the remote PC. Unfortunately, directly remoting into that PC does not work for my case.
I am aware of a system known as UnrealSwarm, but have had difficulty finding recent documentation and substantial resources showing it can effectively run jobs other than lightmass rendering.
Please let me know how I can solve my problem!
Thanks in advance!


texts:
I'm currently working on a 2D platforming game with an infinite map.

I did my research and I discovered that I can use chunks. Based on my understanding chunks is about spawning terrain at the right time and then removing them when not needed.

My idea was to pool a body then add it to an array list so that I can use a static body and remove it any time without any problems.

But then I realized that Pooling is not applicable to bodies.

How can I spawn chunks, without creating a new body every single time and then remove it when not needed?


texts: Do leaderboard sets (in Game Center) allow 500 unique leaderboards?

texts:
The Game Kit Programming Guide for iOS claims:

  The number of different leaderboards allowed increases to 500
  leaderboards per game when leaderboard sets have been
  enabled...Leaderboard sets offer developers the ability to combine
  several leaderboards into a single group.

But their example (see image below) implies that a single leaderboard is placed into multiple leaderboard sets. Is that the only way to be able to use the full 500 leaderboards? by combining the same leaderboard into multiple sets? I want to be able to have 500 unique leaderboards that are not duplicated between sets. Is this possible?


texts: How do you access Target in a Beam ParticleSystem in UDK?

texts:
I have a Beam ParticleSystem which looks like this:

I want to set the Target location when the effect plays, but I can't figure out how to do that from UnrealScript.

I've looked at the UDN page on it: link

But this doesn't seem to explain how to access the relevant info from script. I am currently able to get the effect to play, but I just can't set the endpoint.


texts: Why isn't OnCollisionEnter being called?

texts:
I have a hammer and an object to be hit in my scene. I put this line
Debug.Log("Collided with" + collision.gameObject.name);
to debug whether the function OnCollisionEnter(Collision collision), was being called. On my hammer, there is a box collider (not trigger), and on the object to collide, it has a rigidbody (non-kinematic), and a mesh collider (convex). I've tried with various objects but it won't call oncollisionenter. They're all the same tag and layer. I made the box collider way bigger and it pushes me back when I try running into an object so it is colliding, but not calling oncollisionenter.

I've heard that it won't work with dynamically instantiated objects, and my player is instantiated at runtime. Could that be it, and are there any fixes? EDIT: I tried disabling the script that instantiates the player (with the hammer on them), and then just having the player in the scene. and it still doesn't recognise any collision from oncollisionenter


texts: Creating outline from a collection of points following the concavity

texts:
I am trying to create an outline from a collection of points. I found this solution for Convex Hull. I specifically picked this implementation: https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain
Edit: I can't find an algorithm that will find the concavity of the region specified in green. The yellow line is the Hull from the algorithm amove

I have the point is defined as:
[Serializable]
public struct Point : IComparable<Point>, IEquatable<Point>
{
    public int X;
    public int Y;

    public static int Cross(Point o, Point a, Point b)
    {
         return (a.X - o.X) * (b.Y - o.Y) - (a.Y - o.Y) * (b.X - o.X);
    }
}

Here is the implementation of the algorithm:
        public static List<Point> ConvexHull(List<Point> points)
        {
            if (points == null || points.Count <= 3) {
                return points;
            }

            var size = points.Count;
            var k = 0;
            var hull = new Point[2 * size];

            points.Sort();

            //build lower hull
            for (int i = 0; i < size; ++i) {
                while (k >= 2 && Point.Cross(hull[k - 2], hull[k - 1], points[i]) <= 0) {
                    k--;
                }

                hull[k++] = points[i];
            }

            //build upper hull
            for (int i = size - 1, t = k + 1; i > 0; --i) {
                while (k >= t && Point.Cross(hull[k - 2], hull[k - 1], points[i - 1]) <= 0) {
                    k--;
                }

                hull[k++] = points[i - 1];
            }

            var result = new List<Point>(hull);

            if (k > 1) {
                result.Resize(k - 1);// remove non-hull vertices after k; remove k - 1 which is a duplicate
            }

            return result;
        }


texts:
My initial research showed the most people prefer to use UDP protocol and build a control code on top of it for multiplayer games. It seems like a good design at first, but I am wondering if it is really the best in the long run.

For example, what happens if your game goes from 64 players to 500, 1000, 20 000

Is the UDP port going to overflow and start dropping incoming packets?
Is the overhead that you wrote for UDP-reliability going to be less optimal when you start using more bandwith? (I.e. the server will spend significant cycles managing features that may already be present at the hardware and network level that are built into TCP)

I am considering re-writing a server that initially used UDP+reliablity protocol and splitting it into two cluster servers to handle different regions as well as introducing a load balancer in the middle. The UDP design is starting to look a little more complicated and having a large number of NPCs and state synchronization that may have to take place is making me reconsider UDP.


texts:
I am trying to implement a twin stick shooter game, sometimes referred to as dual stick shooter where the left stick controls movement, and the right stick aims a gun.

What I do now, is directly map the stick angle to the gun angle, if the deflection is large enough. In pseudo code:

// jx in [-1,1]
// jy in [-1,1]
if lenght (jx,jy) > 0.5 :
    gun_angle = toangle( jx, jy )

This gives a very unsmoothed, twitchy signal for the aim.

The gun can flicker in any direction in a single frame.

In theory, the most responsive scheme, but on-screen looks far too twitchy.

So I wonder: should I sacrifice some responsiveness for a smoother signal?

Should I make the gun swivel around as I reverse the direction of the joystick, or just set it hard, like I do now?

I've been considering using the stick signal as input to a PID controller that does the actual gun rotation, but would like to know whether that's an appropriate solution for this application.


texts: We are asked not to use "Set Native Size"

texts:
it's been around 2.5 weeks since we were tasked to build a 2d mobile game. The game heavely uses canvas and we have lots of images. Our designer uses Figma to design the game and I export images from it.
If you have ever used Figma or Sketch, you may know that their mobile phone frame width and height is quite different than the physical device. For example, iPhone Pro Max frame in Figma has 896x414 but the physical device 2688×1242. So all the screens and the images in design is scaled down to look good in Figma's 896x414 frame.
Another important thing I think worth to mention is that we set our Canvas Scaler's reference resolution to 1920x1080 as shown in the image below.

So the thing is, there is also a guy, who is much more experienced in Unity, told us that we should export images from Figma with 2x scale. He says that images will look blurry if we export them in 1x.
On top of that, he told us not to use Image component's Set Native Size property, because the image has twice the size shown in Figma. Instead we should scale down the images ourselves MANUALLY with eye decision (not sure if that phrase exists).
So I am confused and not sure if that method is correct. What is a common practice in such situations? Do people not use Set Native Size? What would be a correct way of exporting images from Figma to a 1920x1080 canvas?
P.S. As I am new to Unity, I may not be able to explain the situation correctly, if there is some extra information you need, feel free to ask in the comments.


texts: I have a question about loading 3ds using this tutorial. I want to use more than one texture on the model (because here all the models have more than one) but it seems that this library can't do that. Do you know any other alternatives or a way to edit this existing library to reach my aim?


texts: Should the lobby and game room be database tables or arrays?

texts:
I'm designing a lobby which holds all game rooms

If a room is empty, it gets deleted by the lobby
If a room is full, a new room is created
For now the lobby is an array of objects on a websockets server
which holds the room.
The rooms are are arrays of objects which hold the players.

The players data are stored on firebase, I don't care about the room data, they're just spawned and deleted, therefore they're not stored anywhere now. The problem I'm facing is the following:

If I leave it like that, I'm going to face problems when scaling on multiple servers, plus it I don't think I can get away with an array holding 50k arrays which holds players data.
I don't want to install redis, every time I have to use that I have stringify and serialize.
Using a database like MongoDb, means installing a database, doing read and write, perhaps managing clusters, all that for data I don't care about.
Using firebase, means doing too many unnecessary requests

My architecture is simple

The client is the mobile app
The game logic is done on the server using nodejs
Data storage and authentication is done on firebase, using nodejs, from the server side
The websockets server is uwebsockets.js

I have to solve the last part which is the rooms and lobby, If I manage to do it without installing a database it would be great, because as of now, I managed to do everything without needing a database on the server, which means easier to scale and all the server has to do is run some nodejs code.


texts: How can I add biomes to my generated world?

texts:
I need a way to generate a world realistically. I want to generate worlds similar to dwarf fortress.

My current code for world generation is this:

    worldTiles = ['^',',','.','.']
    def generateWorld(self, x=40, y=20):
        world = []

        for i in range(y):
            row = []
            for z in range(x):
                row.append(random.choice(self.worldTiles))

            world.append(row)
        return world

with the worlds it generates being this:

The world is ok, however what I want is biomes, not just completly random generation.

In case it helps, heres how the current generation works:

A variable called worldTiles has alls the tiles the world can have. This is used by the function. The function, creates an array, and appends a row to it. The row is then added to the world, as another array.

A example world might be:

  [
    ['^', ',', '^'],
    ['^', ',', '.'],
    ['^', ''., '.']
  ]


texts: Creating similar effects of Geometry Wars in 2D only

texts:
I want to create a game with similar effects to that of "Geometry Wars"... for those who have never played the game, basically, massive amounts of 'bending' and 'warping' effects are done on the background during explosions and pulses.

Here is a picture:

The grid is normally a bunch of squares (perfect squares) in a perfect grid.  When certain effects happen, the grid stretches and creates amazing effects.

Now, I'm trying to create a game using my own, from scratch, 2D engine.  Is it possible to fake 3D effects such as this to my sprites?  Is there some kind of effect I could do to do this?


texts:
I found some code I needed online, but I want to understand how it works.
Renderer c = (Renderer)b; What is this (Renderer)b action called so I can Google about it?
It looks like it's trying to get a Renderer instance from b, but isn't b a Component of type Renderer already? Or is this because Renderer is a subclass of Component?
void SetTargetInvisible(GameObject Target)
{
    Component[] a = Target.GetComponentsInChildren(typeof(Renderer));
    foreach (Component b in a)
    {
        Renderer c = (Renderer)b;
        c.enabled = false;
    }
}

Code is from
https://forum.unity.com/threads/how-to-make-all-children-invisible.27259/
Thanks for taking the time!


texts:
I'm implementing reflection/environment mapping using a cubemap. I have it working for the most part but when I move my camera around, I see the same area reflected on the object. I am calculating the eye vector and normal vector in view space similar to OpenGL Shading Language 3rd Edition example (p.311, Section 10.4).

Why does the reflection stay as if it is from the same view?

Which space should I be doing my calculations?

How render looks:

Snippets of HLSL code

Vertex shader:

normal = mul( (float3x3)mvMatrix, input.normal );
normal = normalize(normal);
viewPos = mul( mvMatrix, float4(input.pos, 1) );

Pixel shader:

viewPos.w = 0;
V = normalize(viewPos);
normal.w = 0;
normal = normalize(normal);

float4 reflectVec = normalize(reflect(V, normal));
float4 reflectColor = tex.Sample(samLinear, reflectVec.xyz );


texts: Does swf provide better compress rate than zlib for png image?

texts:
Somebody told me that when a png image is stored in swf, it's separated to several layer, hence the alpha channel can be compressed better. Is it true? Or, once png image is imported into a swf, it's format is changed, e.g converted into bitmap data, and than compressed by swf's compress algorithm. That's, it is not in png format anymore.
I don't know how swf packing its resource, please tell me if you know.


texts: Could I make my own pokemon game without running into a copyright issue?

texts: I've always wanted to make a video game that criticises pokemon. I want to know if I could use pokemon as the characters in the game without running into copy right laws. The game itself will have nothing to do with the normal purpose of pokemon but at one point also mimics pokemon mystery dungeon a little. that point in the game would be similar to the rescuing of other pokemon and will also have some of the same characters in pokemon mystery dungeon. so, could I possably make this game? or not. If I couldn't, what would it take to have permission. If your wondering how the game criticises pokemon, it does so cause it's supposed to be a gory hard core M game. What if I was to not include any of the titles from pokemon like pikachu for example and just simply give the characters real life names as well as give minor changes in designs and abilities? Could that help avoid copyright problems?


texts: MonoGame "couldn't find a default importer" for .txt file?

texts:
I'm trying a solution in MonoGame to create levels from a .txt file, but the pipeline tool fails when trying to build the Content.mgcb correctly:

❌ Skipping HighResolutionContent\Backgrounds\Layer1_0.png
C:/Users/foo/Documents/Visual Studio 2017/Projects/Platformer/Content/HighResolutionContent/Backgrounds/Layer1_0.png
Couldn't find a default importer for 'C:/Users/foo/Documents/Visual Studio 2017/Projects/Platformer/Content/HighResolutionContent/Levels/2.txt'!
Couldn't find a default importer for 'C:/Users/foo/Documents/Visual Studio 2017/Projects/Platformer/Content/HighResolutionContent/Levels/0.txt'!
Couldn't find a default importer for 'C:/Users/foo/Documents/Visual Studio 2017/Projects/Platformer/Content/HighResolutionContent/Levels/1.txt'!

Visual Studio shows me this:

❌ The command ""C:\Program Files (x86)\MSBuild\MonoGame\v3.0\Tools\MGCB.exe" /@:"C:\Users\foo\documents\visual studio 2017\Projects\Platformer\Platformer\Content\Content.mgcb" /platform:Windows /outputdir:"C:\Users\foo\documents\visual studio 2017\Projects\Platformer\Platformer\Content\bin\Windows" /intermediateDir:"C:\Users\foo\documents\visual studio 2017\Projects\Platformer\Platformer\Content\obj\Windows" /quiet" exited with code 3.
❌ Couldn't find a default importer for 'C:/Users/foo/Documents/Visual Studio 2017/Projects/Platformer/Content/HighResolutionContent/Levels/0.txt'!
❌ Couldn't find a default importer for 'C:/Users/foo/Documents/Visual Studio 2017/Projects/Platformer/Content/HighResolutionContent/Levels/1.txt'!
❌ Couldn't find a default importer for 'C:/Users/foo/Documents/Visual Studio 2017/Projects/Platformer/Content/HighResolutionContent/Levels/2.txt'!


texts: How do I transition a cocos2d scene to a UiViewController?

texts:
My project is a cocos2d game project, but I added a UIViewController for the initial log in. The first scene is the splash logo, followed by the menu screen, but I need to pass to my UIViewController instead of my menu screen. I've tried lots of methods, but it keeps crashing.

-(id) init
{

    if( (self=[super init] ))
    {
        CCSprite *sprBack = [CCSprite spriteWithFile:@"logo.png"];
        [sprBack setPosition:ccp(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)];
        [self addChild:sprBack];

        [self schedule:@selector(logoTimer:) interval:3];
    }

    return self;
}

-(void) logoTimer: (ccTime) dt
{

    [[CCDirector sharedDirector] replaceScene:
        [CCTransitionFade transitionWithDuration:0.5f scene:[TitleLayer node]]];
}

My UIViewController is called LoginViewController. I need to pass a scene like this:

[[CCDirector sharedDirector] replaceScene:
    [CCTransitionFade transitionWithDuration:0.5f scene:[loginviewcontroller node]]];

I tried a lot of methods, but unfortunately, nothing will gives me the correct solution.

Itvis worth mentioning that  LoginViewController is not a Node. I have tried that method, but it geta stuck at the logo scene, with no page transition taking place.

-(void) logoTimer: (ccTime) dt
{
    UIViewController *cocos = [[LogoViewController alloc] init];
    [cocos.navigationController dismissViewControllerAnimated:YES completion:nil];
    [cocos.navigationController popViewControllerAnimated:YES];
}

How do I solve my problem?


texts: 2D Polygon Collision push direction with large polygons

texts:
I have a collision detection/resolution implementation that uses the Separating Axis Theorem. Detection and such works perfectly fine, as well as resolution for most objects/shapes in my game.

However, when it comes to sloped surfaces, there is a problem.

As the picture below in this post demonstrates, whenever an AABB polygon (i.e. the player) is tested against a large slope, the direction the player is pushed in will end up being incorrect. I understand why this phenomenon happens; my displacement calculation (which is used to determine if the push vector needs to be flipped) is giving improper results because the player is below the 'center' of the sloped shape, and thus the displacement calculation is reporting that +y (downward) is the direction to push away from the slope's polygon. This causes the player to get pushed into the ground, or through the slope entirely if there is no ground polygon underneath.

My displacement code looks something like this:

        MTV mtv(perpendicular, 0.f);

        sf::Vector2f center1 = GetRectCenter(shape_1.getGlobalBounds());
        sf::Vector2f center2 = GetRectCenter(shape_2.getGlobalBounds());
        sf::Vector2f dir;
        dir.x = center2.x - center1.x;
        dir.y = center2.y - center1.y;
        dir = unitVector(dir);
        bool flipme = false;

        float disp = dotProduct(mtv.axis, dir);
        if(disp < 0)
            flipme = true;

So what I am wondering, is there another solution to finding out if a polygon's displacement vector will end up towards the polygon or away from it? This displacement calculation works for rectangular shapes and smaller-sized slopes, but is obviously incorrect when the slope is large enough for its center to be navigated around.

I have also tried averaging the points together to find the centroid of the slope, but that still yields similar results.


texts: How to get the correct Input direction based on the camera angle to use in a rootmotion based third person controller

texts:
I move my character based on the rootmotion of their animation using a blend tree that uses 2D Freeform Cartesian input (Vertical, Horizontal)
if Vertical = 1, the character moves forward based on the direction he is facing
if Horizontal = 1, the character turns right based on the direction he is facing
and the rest of the system follows, here is the current Blend Tree:

Currently, if i press forward, the character move forward no matter where the camera is facing:

But in this example, what i want is for the character to slightly make a turn left to face the camera direction and then start walking forward:

When working on a game that moves the character by code (without rootmotion), something like this would solve the issue:
_inputAxis = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);
_inputCam = Quaternion.Euler(0, _cam.transform.eulerAngles.y, 0) * _inputAxis;

And then use _inputCam to move the character, but for some reason this isn't working, and these two variables are always equal to each other, what am i doing wrong ? also if there is a "standard" solution for this problem (am sure it is) please link it (doesn't matter if its Unity or not as long as the code is readable)
Thanks!


texts: XNA frame rate spikes in full screen mode

texts:
I'm loading a simple texture and rotating it in XNA, and this works.

But when I run it in full screen 1920x1080 mode I see spikes while my texture is rotating.

If I run it windowed with 1920x1080 resolution, I don't get the spikes.

The size of the texture does not seem to matter, I tried 512 texture size and 2048 texture size, same thing happens. Spikes in full screen, no spikes in windowed, resolution does not seem to matter, Debug or Release does not seem to do anything either.

Anyone got ideas of what could be the problem?

Edit:

I think this problem has something to do with the vertical retrace.
Set this property:
 _graphicsDeviceManager.SynchronizeWithVerticalRetrace = false;

you'll lose vsync but it will not stutter.


texts: Changing gameobject initialization order

texts:
Edit: Here is some important update:

I have found out that the script's Start and Awake voids are called, but AFTER the script is used by some other script.
So the problem here is that the gameobject that hosts "OtherScript"  is initialized after the gameobject which has a "MainScript" attached and which holds a reference to "OtherScript".

I hope I could explain it well.

If just the one gameobject was initialized before the other, everything would be fine. I will investigate now if I can change the intialization order.

Original post:

I have a complex scenario which I have reduced to the following problem:

I have a Cube in my Unity scene. This cube has the following script on it:

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

public class MainScript : MonoBehaviour
{
    public OtherScript TheOtherScript;

    public void OnGUI()
    {
        if (GUI.Button(new Rect(0, 0, 50, 50), "Load something"))
        {
            this.TheOtherScript.LoadFile();
        }
    }
}

The script "OtherScript" looks like this:

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

public class OtherScript : MonoBehaviour
{
    private string _sPath;

    public bool HasBeenInitialized = false;

    public void Awake()
    {
        _sPath = Application.persistentDataPath + "/somefilename.dat";
        this.HasBeenInitialized = true;//indicator that Awake or Start have occured
    }
    public void Start()
    {
        _sPath = Application.persistentDataPath + "/somefilename.dat";
        this.HasBeenInitialized = true;//indicator that Awake or Start have occured
    }

    public void LoadFile()
    {
        if (_sPath == null)
        {
            Debug.Break();
        }
        //do something with _sPath
    }
}

I have created an empty GameObject to my scene, and I have added such a script to it:

I have then put a reference to empty GameObject to the Cube's "OtherScript" slot:

The problem that I'm experiencing is that "TheOtherScript"'s start / awake has not been called when this button is pressed:

    if (GUI.Button(new Rect(0, 0, 50, 50), "Load something"))
    {
        if (!this.TheOtherScript.HasBeenInitialized)
        {
            Debug.Break();//The script hasn't processed Start or Awake yet. Why???
        }

        this.TheOtherScript.LoadFile();
    }

Neither Awake nor Start is called on this script.

Which event could I react to in this case for initialization?


texts: Which network engine/library/system to use in a .NET turn-based game?

texts:
I'm developing an abstract strategy turn-based game in C#.

Being so, high network load is not expected. The players don't even have to be connected all the time. The host could wait for the current player to connect and make his move. I know I could make a web site to run that, but I want anyone to be able to host their own games.

I need something reliable and that enables me to have good productivity.

I'm already underway with WCF. Was that a good choice? Which other network framework should I consider?


texts:
I have tried to use up AppWarp's old SuperJumper as a sample to create an up to date project from it with Gradle. Maybe it is good for learning. So, I have downloaded project from GitHub(https://github.com/SauravGShephertz/libgdxMultiplayerSuperJumper) as zip and started to build a new Gradle based libGDX project from it.
Here you can see actual state: https://github.com/kovacsa91/superjumper

I have some errors with following lines.

com.shephertz.app42.gaming.multiplayer.client.command.*;

Maybe it cannot found needed JAR file(s)? How should be it placed? Can you please check it out? Code was separated between project folders inside the main libGDX project.


texts: Working with retina graphics on Unity 2D

texts:
I begun trying Unity for iOS 2D development.

I am curious about how to work with retina devices. The first thing I did was create a 1136x640 solid rectangle sprite and throw it into my scene, then run the game on my iPhone 5.

My expectation was that this image would perfectly fill the screen - that is, the retina would "kick in". Alas, this was not the case: my sprite was much smaller than the iPhone's screen.

Then I saw the main camera game object, and played around with the size property. By default is was like 5, but I determined that the number I needed for my sprite was somewhere around 3.2.

This works and looks fine in my phone. But I am unsure if this is how I am suppose to do things: what is the correct way of supporting retina images? I feel like guessing the size property of the main camera is a bit hackish. Actually, how do I know if Unity is indeed using retina?


texts: Prevent button layout changing after one is removed?

texts:
I have a layout with four buttons in it. I end up removing one of the buttons using:

View v = (View) findViewById(R.id.ViewId);
                    ((ViewManager) v.getParent()).removeView(v);

The problem is, whenever I remove one button (which works fine), the other three buttons move out of place.

For example, I have a top right button, a top left button, a bottom right button, and a bottom left button. I choose to remove the top right button using the code I gave earlier. This causes all the other three buttons to move out of place.

I think this may be because of the xml, where it states things like:

android:layout_toRightOf

And I think that when I move one button, that statement in the xml has nothing to be to the right of, and so it goes of to a random position. Is there a way I can remove these statements without having to change the position of my buttons?

Can I keep the buttons independent of each-other?


texts: I need to write a simple 3D billiard game using OpenGL. Which physics engine is simple and best to use in this case? Or it's better to write physics by myself?


texts: In Monogame, can/should SpriteBatch be instantiated in the Initialize method as opposed to the LoadContent method?

texts:
By default the SpriteBatch instance used is instantiated in the LoadContent method of Game1.

For example see here

However a SpriteBatch only requires a GraphicsDevice object to be instantiated. Said GraphicsDevice is actually already available when the Initialize method is created, so my question is why is the SpriteBatch created in LoadContent?

I think that both methods are run only once per game, so don't see why you can't/shouldn't instantiate the SpriteBatch object in the Initialize method?


texts:
I have 2 questions about how i should approach this.

I want to make a 2D game, with alot of different creatures.

Question one: If i have alot of monsters and i'm using ScriptableObjects, since they have very similar variables. How can i make one Enemy prefab which will load the right ScriptableObject information? For example i have an Enemy Prefab, then it will load random monster between: Dragon, Frog, Wolf. How can i achive this without creating 3 new Prefabs for each one and instead load just the right ScriptableObject.

Question two: Should i create new prefab for each monster? Or is approach 1 the right way to do it, if you plan to expand over 100+ creatures.

Thanks


texts:
I'm playing around and trying to build an orbit simulator. Unfortunately, it isn't working out to well. Instead of forming some sort of elliptical orbit, I get this:

Here is the code I'm using to generate the orbits:

public class OrbitBehaviour : MonoBehaviour {
    public Double Mass;
    private List<GameObject> _bodies = new List<GameObject>();
    private float _gravConstant = 6.673f * Mathf.Pow(10.0f, -11.0f); // Units: m3 kg-1 s-2
    private int delay = 0;
    private float _distanceConversion = 6.68458712f * Mathf.Pow(10.0f, -12.0f); // m -> AU (Astronomical Units)
    private float _massConversion = 1.67403241f * Mathf.Pow(10.0f, -25.0f); // kg -> E (Earth masses)
    private float _timeConversion = 1.1574074074074074074074074074074e-5f; // s -> D (Days)

    // Use this for initialization
    void Start() {
        _bodies = GameObject.FindGameObjectsWithTag("mass").ToList();
        _gravConstant *= Mathf.Pow(_distanceConversion, 3.0f);
        _gravConstant /= _massConversion;
        _gravConstant /= Mathf.Pow(_timeConversion, 2.0f);
        gameObject.GetComponent<Rigidbody>().AddForce(Vector3.left * 10f);
        Mass = Mass * _massConversion;
        Time.timeScale = 99.0f;
    }

    // Update is called once per frame
    void FixedUpdate() { StepSimulation(); }

    private void StepSimulation() {
        // Walk each body in the system
        foreach (GameObject body in _bodies) {
            if (gameObject == body) {
                continue; //skip self
            }
            Vector3 tSeparationVector = body.transform.position - gameObject.transform.position;
            tSeparationVector = tSeparationVector.normalized;
            OrbitBehaviour bodyBehaviour = body.GetComponent<OrbitBehaviour>();
            Double tForceValue = _gravConstant * (this.Mass * bodyBehaviour.Mass / tSeparationVector.sqrMagnitude);
            gameObject.GetComponent<Rigidbody>().AddForce(tSeparationVector.normalized * (float)tForceValue);
        }
    }
}

Does anyone know what I am doing wrong here?


texts: Is there a benefit to applying forces to my camera?

texts:
I have implemented a camera system and a rudimentary physics system. I now have a decision to make regarding steering the camera:

Option 1 - Update the camera movement directly.

eg. position (0, 0, 0) + Key 'W' => position (0, 0, 1)

Option 2 - Apply a force to the camera and let my physic's integration sort it out.

eg. position (0, 0, 0) + Key 'W' + force (0, 0, 0.2) => ...?

How should I implement camera movement?


texts: The .apk file for my built game is much larger than expected

texts: Assets of my game are 15 MB, Player Settings are default, but my .apk file is 45 MB. I tried to change Player Settings and convert PNG images to JPEG, but this didn't work.


texts:
So, I'm just starting out with LWJGL, and my current task is to render two colored cubes on the screen. I can render them, however, I'm looking for some advice on the most efficient way to specify the colors. Currently, I'm doing this:

// specify vertices and colors
vertexData.put(new float[] { -0.5f, -0.5f, 0, 0.5f, -0.5f, 0, -0.5f,  0.5f, 0, 0.5f,  0.5f,  0, // 1st cube vertices
                             -1.0f, -2.5f, 0,    0, -2.5f, 0, -1.0f, -1.5f, 0,    0, -1.5f,  0 }); // 2nd cube vertices
colorData.put(new float[] { 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, // colors for 1st cube
                            1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1 } ); // colors for 2nd

In the render loop:

glVertexPointer(vertexBufSize, GL_FLOAT, 0, 0L);
glColorPointer(colorBufSize, GL_FLOAT, 0, 0L);
...
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // 1st cube
glDrawArrays(GL_TRIANGLE_STRIP, 4, 4); // 2nd cube

This works, but I can't help but think that since I'm specifying the exact same color values for both cubes, I'm wasting memory. I was hoping to just have one set of vertex colors that could be applied to each cube that gets drawn. Can it be done? If so, what is the best way to do it?

Thanks


texts: Figuring out the exponent in a spotlight equation from the angle of a cone

texts:
I followed a tutorial on how to build a spotlight using DirectX. This tutorial uses a point light equation plus a line of code to limit the light to the shape of a cone. I have everything working, but the equation for constraining the light uses a constant exponent to control the broadness of the light, which is all well and good if I was just tweaking the value for looks alone, but I also want to know the precise size of the cone in order to do culling on the CPU side. Here's the equation:

float lightAmnt = dot(lightToSurfaceVector, inputNormal); // point light

lightAmnt /= attenuationA + attenuationB * distance + attenuationC * distanceSquared; // falloff

// exponentConstant to control broadness
lightAmnt *= pow(max(dot(-lightToSurfaceVector, lightDir), 0.0f), exponentConstant); // spotlight

what I'd like to do is create an angle theta for the cone on the CPU, and then create the exponentConstant based on that and the range aka cone height, but I don't know how that math would work. And I realize there are other spotlight equations, but I like this one because the attenuation works identically between point and spot lights. Can anybody lend a hand?

link to the tutorial: https://www.braynzarsoft.net/viewtutorial/q16390-21-spotlights


texts: Circle-Rectangle collision in a tile map game

texts:
I am making a 2D tile map based putt-putt game.

I have collision detection working between the ball and the walls of the map, although when the ball collides at the meeting point between 2 tiles I offset it by 0.5 so that it doesn't get stuck in the wall. This aint a huge issue though.

  if(y % 20 == 0) {
    y+=0.5;
  }

  if(x % 20 == 0) {
    x+=0.5;
  }

Collisions work as follows

Find the closest point between each tile and the center of the ball
If distance(ball_x, ball_y, close_x, close_y) <= ball_radius and the closest point belongs to a solid object, collision has occured
Invert X/Y speed according to side of object collided with

The next thing I tried to do was implement floating blocks in the middle of the map for the ball to bounce off of. When a ball collides with a corner of the block, it gets stuck in it. So I changed my determineRebound() function to treat corners as if they were circles. Here's that functon:

   `i and j are indexes of the solid object in the 2d map array. x & y are centre point of ball.`
   void determineRebound(int _i, int _j) {
     if(y > _i*tile_w && y < _i*tile_w + tile_w) {
        //Not a corner
        xs*=-1;
      } else if(x > _j*tile_w && x < _j*tile_w + tile_w) {
        //Not a corner
        ys*=-1;
      } else {
        //Corner
        float nx = x - close_x;
        float ny = y - close_y;
        float len = sqrt(nx * nx + ny * ny);
        nx /= len;
        ny /= len;

        float projection = xs * nx + ys * ny;
        xs -= 2 * projection * nx;
        ys -= 2 * projection * ny;
      }
    }

This is where things have gotten messy. Collisions with 'floating' corners work fine, but now when the ball collides near the meeting point of 2 tiles, it detects a corner collision and does not rebound as expected.

I'm a bit in over my head at this point. I guess I'm wondering if I'm going about making this sort of game in the right way. Is a 2d tile map the way to go? If so, is there a problem with my collision logic and where am I going wrong?

Any advice/feedback would be great.


texts: How to PRECISELY measure execution time of a code?

texts:
In order to compare algorithms speed, I measure execution time of a code part with a method similar to the one described in this question.

I am not operating on Windows, but on Linux, so I use gettimeofday function in order to measure time with microsecond precision.

My test program has a simple architecture:

int main()
{
    test_algorithm1(); // Measure execution time of algorithm1 and
    test_algorithm2(); // Measure execution time of algorithm1 and

    return 0;
}

My functions test_algorithm1 and test_algorithm2 have exactly the same structure:

void test_algorithmX()
{
    struct timeval before, after;
    time_t         elapsedUs;
    int            i;

    gettimeofday(&before, nullptr);
    for (i = 0; i < 1000000; i++) // Repeated 1 000 000 times for more precision.
    {
        // Code to measure here
    }
    gettimeofday(&after, nullptr);

    elapsedUs = after.tv_usec - before.tv_usec; // Elapsed microseconds
    elapsedUs += (after.tv_sec - before.tv_sec) * 1000000; // Elapsed seconds
    std::cout << "Elapsed time for algorithm X: " << elapsedUs << std::endl;
}

However, I face two problems:

Measured time seems very random, especially with short algorithms. If I run many times the program, I can obtain results between 25 000 and 35 000 us.
If I invert algorithms order in the main function (running test_algorithm2 before test_algorithm1), values change. It appears that the first one to be executed is slower. Values like 50 000/15 000 us may change to 40 000/20 000 if I invert them.

This is very problematic, because I sometimes measure algorithms of very close speed, and I cannot make a conclusion with this random.

Is there a better way to measure execution time? Or did I do something bad, like using the gettimeofday function?


texts: Unity, Player isnt following along the waypoints

texts:
I have a player with a Rigidbody, I want it to follow along the Waypoints, I have a script for it I tested it first on a Cube, everything worked fine, but on my character it just moves Towards the first waypoint then stays on the first waypoint instead of going ahead. Even if I comment out the LookAt Code section its not working. It could maybe cause the Y position of the waypoints that my player is stuttering, I changed it now. It is now moving along but stuttering much.

Here is a picture of the problem:

Here is my code:

public GameObject[] waypoints;

public float grindSpeed;
public float turnSpeed;

public int currentWaypoint;

private Animator anim;
private Rigidbody rb;

public bool isGrinding = false;

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

void Update()
{
    MoveAlongWaypoints();

    if(isGrinding)
        anim.SetBool ("isOnGrinding", true);
    else if(!isGrinding)
        anim.SetBool("isOnGrinding", false);
}

void MoveAlongWaypoints()
{
    if(isGrinding)
    {
        //TRANSLATE
        transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypoint].transform.position, grindSpeed * Time.deltaTime);
        //ROTATE
        var rotation = Quaternion.LookRotation(waypoints[currentWaypoint].transform.position - transform.position);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, turnSpeed * Time.deltaTime);

        if(transform.position == waypoints[currentWaypoint].transform.position)
        {
            currentWaypoint++;
        }
    }
}

void OnTriggerEnter(Collider other)
{
    if(other.gameObject.tag == "GrindWayPoint")
    {
        Debug.Log ("Waypoint!!");
        isGrinding = true;
    }
}


texts:
In my Java game, I've got a number of randomly-generated maps made of tiles.
I'm struggling with writing the code to handle the entering/exiting of the maps.

Originally, I only had Ascend and Descend. Easy. Enter exit, arrive at entrance. Basically, I used depth-- and depth++. Start at level 1, descend to level 2. Ascend to level 1 if desired.

Now I have maps that have North, East, South, and West entrances.
So when I exit North, I need to arrive at the South entrance. Similarly, when I enter East, I need to arrive at the West entrance.

I'm working on an elaboration of the Ascend/Descend --/++ system. This basically means I have to have code for:

eastEntrance sends player to westExit,

westEntrance sends player to eastExit,

northEntrance sends player to southExit,

southEntrance sends player to northExit.

westExit sends players to eastEntrance (etc for east, south, north).

This seems pretty cumbersome.
What is a good way to link my maps?

I'd really appreciate any input on this.


texts: Do I need to be careful about PPU and Camera size and Device Resolution even if I'm not creaing a pixel art 2d game?

texts:
I was reading this blog post
https://blogs.unity3d.com/2015/06/19/pixel-perfect-2d/
and was wondering if I need to be super careful about those numbers, although my game's art is not pixel art.


texts: lwjgl licence and requirements for commercial use

texts:
is it completely legal to use light weight java game library in a commercial 2 dimension game engine like drag and drop not straight code?if yes what are their  requirements?if not what are my options?
thanks in advance.


texts: Game running with fewer steps than desired (game created in GameMaker)

texts:
I tested my game on 4 different computers and got some results.

PC 1 => AMD A4-6300 APU with Radeon HD Graphics / 2,0 GB RAM / AMD Radeon HD 8370D

In this computer I tested a few stages and I noticed a loss of 1 second in 10, ie ... In the game 10 seconds passed while here in the real world 11 seconds passed.

I calculate the time in the game based on the step event.

I set the speed of the room by default as 30.

Time code:

Step Event: currentTime+=1;

Draw Event: draw_text(x,y,string(currentTime/30));

On my computer I never had problems. Hence the need to test the game on other computers.

PC 2 => Pentium Dual-core CPU E5700 @ 3.00GHz / 4,0GB RAM / Intel G41 Express Chipset

On this computer, I performed the same tests and I detected a slightly smaller loss. Less than 1 second every 10 seconds, ie ... In the game 10 seconds passed while here in the real world 10.7 / 10.8 seconds passed.

PC 3 => Intel core i3-3217U CPU @ 1.80GHz / 4GB RAM Intel HD Graphics 4000

Worked perfectly! It's a core i3 right? I did not detect any apparent losses.

PC 4 => Intel Core 2 Duo CPU e8200 @ 2,66GHz 2,66GHz / 4GB RAM

Worked perfectly! I did not detect any apparent losses.

Detail that in this computer the game lost enough in resolution (it seems that the monitor is too large for the components of the computer).

Post with the problem => Game was resized incorrectly for no apparent reason (GameMaker)

Important!

I put a function on the shift key to accelerate the game (it would be a function for the players who wanted to analyze all the course of the stage, just playing to understand) and I defined that when clicking on the shift key the speed of the room goes to 3000 steps. On my PC the game is super fast, but I doubt it reaches exactly 3000 steps. Even so, a few hours pass in a few minutes here at home.

On PC 1 I tested this same function and accelerated by approximately 20%. In the game it was 11 seconds while 10 seconds passed in the real world.

Solutions:

1=> Stop measuring time through the steps.

I imagine there is some way to do time measurement based on another type of argument, just like unity timeDeltaTime.

That way, I imagine that a player with a GTX 1080 the game works correctly and phase 1 finishes in exact 11.23 seconds (real time).

But a player with a humbler computer that same phase finishes with 13 or 14 seconds (real time). It turns out that the same phase that lasted 11.23 seconds on the computer with a GTX 1080, it would take longer to be finalized on that more humble computer. The time was going to be measured correctly (13/14 seconds in the game), but the game was going to be running in different ways (different speeds).

2 => Based on the boost (shift key) I tested on PC 1 (the humblest computer I tested) I see that it is possible to force the game to rotate in a number of steps even on that weaker computer.

I think that using solution 2, when I make the online mode available, I may have problems (just like Fallout 76), people with a good computer could change the steps of the game and make the game work in a much larger number of steps.

The ideal would be to join the two solutions, so that time is measured regardless of the number of steps, but that the operation of the game is the same on any computer.


texts: Assets Management, database or versioning system?

texts:
While developing the assets for the game, (meshes, textures, sounds, videos) ho do you manage them?

Keeping them together with the source code
inside the versioning system? (perforce, git, etc…)
Or having a central back-upped, database
dedicated to the assets and having
the editors always work liked to it?
(PostgreSQL, MySQL, etc…)
Other?

What are the pro and cons of each, and why one should choose it over the other/s?


texts: Blender: How to merge multiple meshes of same object?

texts:
I have run into a bit of a problem creating my 3D model. I started with a single mesh and added additional meshes (all in edit mode) to create my geometric shape. They are all part of the same object, but now I can't figure out how to "carve" my desired shape of this geometric mesh pattern because some of my faces are going to get deleted etc.

Here are pictures of what I have, and what I want to achieve.


texts:
Let's say I have some surface rasterized and stored to a texture. How do I calculate the actual surface area that is visible in one of the rasterized pixels, from some other location?

So far, I'm assuming it's

A_visible = A * cos(theta) / d^2

where d = distance from viewer, theta = angle between normal and viewer-surface direction, A = ... I'm not even sure how to express it. I guess you could call it the "world space area" of the pixel.

Is the above equation even correct? How do I determine "A? Notice that I'm not only looking for the area strictly as visible from the (e.g. perspective) camera. I'd also like to compute this area as visible from other surfaces, i.e. other surface areas that receive light from all around its hemisphere above the surface.


texts: Monogame - Not enough storage is available to complete this operation, on backgrounds

texts:
I am making a level selector, which works like a web slider. I am showing 12 levels per page, and I have a total number of 60, which means 5 pages of 12 levels.

Each level has his on background image, and I tried to load all the backgrounds into an Texture2D array. Since now I loaded only 12 backgrounds, because I had only them, everything worked perfectly. Now, I have more, about 40, and when I try to load them into the array I receive this error:

Additional information: HRESULT: [0x8007000E], Module: [General], ApiCode: [E_OUTOFMEMORY/Out of memory], Message: Not enough storage is available to complete this operation.

Code line:

for (int i = 1; i <= 36; i++)
                LevelBackgroundTextures[i] = Resource.ContentManager.Load<Texture2D>("Levels/Backgrounds/bg_" + i);

If I understood correctly I receive this error because I do not have enough space (RAM) to load all the content once and I need to use multiple content processors, and here is the problem.

I do not know how can I use them to be effective, when to load/unload the content, etc. Or is there another way that I can fix this error?

Thanks.


texts: Is there a way to export 3D objects with animation from Blender or any other app into OpenGL ES 1.1 code?

texts:
The problem is that all the examples I've found are obsolete or iOS/Android specific and not "pure" OpenGL ES 1.1.

If anyone can provide me with a good example/tutorial/book it would be very much appreciated!

Thank you!


texts: How can i use A star pathfinding algorithm

texts: How would i implement an A star algorithm for a game that i'm making on the android in java? i'm looking for a pre-made A star API in java with classes and methods to call. i don't want to have to code from scratch.


texts:
I'm trying to find a way of setting any kind of material class on any kind of primitive class (all the material classes have a base material class, same goes for the primitive classes).

What I mean by that, is, I'm looking for a way to do something like this:

Cube a = Cube( ColorMaterial( COLOR_RED ) );
Cube b = Cube( TexturedMaterial( ambienTex, diffuseTex, specularTex ) );

Ok, so that looks pretty easy, but I've got a few problems.
First of all, inside my Cube class I've got a function in which I build the cube's geometry, as such:

VertexPositionColor vertices[36] =  { VertexPositionColor( pos, color ), ... }

Because of this, I can't just pass any type of material to my primitive class, because that would mean that the function that builds the geometry would need to be able to change the type of vertex it uses.
I can't use templates either, because, even though it would solve the type issue, different vertex types are not constructed the same way.

So, is there any way of associating a material to a primitive?


texts: libGDX collision detection / bounding the object

texts:
I am trying to implement collision detection so I am drawing a red rectangle to see if it is working. When I put the code below into the update method to check if it is going to work the position is not in the right place. The red rectangle starts from the middle and not at the x and y point? So it draws it wrong.

I also have a getter method so nothing wrong there.

bullet.set(getX(), getY(), getOriginX(), getOriginY());

this is for the render

shapeRenderer.begin(ShapeType.Filled);
shapeRenderer.setColor(Color.RED);
shapeRenderer.rect(bullet.getX(), bullet.getY(), bullet.getOriginX(), bullet.getOriginY(), 15, 5, bullet.getRotation());
shapeRenderer.end();

I have tried to do it with a circle but the circle draws in the middle and I want it to be at the tip of the bullet. At the front of the bullet. x, y point.

boundingCircle.set(getX() + getOriginX(), getY() + getOriginY(), 4.0f);

shapeRenderer.begin(ShapeType.Filled);
shapeRenderer.setColor(Color.RED);
shapeRenderer.circle(bullet.getBoundingCircle().x, bullet.getBoundingCircle().y, bullet.getBoundingCircle().radius);
shapeRenderer.end();

I need it to be of the x and y as the bullet is in the middle of the sprite when drawn originally via paint.


texts: "Fading" effect between different screens?

texts:
I'm not sure what the correct word for it is, but I'm thinking like the fading effects when you move between different screens in Powerpoint or Keynote; that the screen fades black before the new screen is shown instead of instantly change.

The "screens" I'm talking about are actually two pictures, and since it's for an adventure type game I thought it'd be cool if it could be done.

Does anyone know a good way to implement this?


texts: Is Update(GameTime) called before it's finished?

texts:
Code at the beginning of Update(GameTime) is being called over and over again, and code at the end of Update(GameTime) is only being called after a delay. Is Update(GameTime) called again before it's finished?

Relevant code:

    public override void Update(GameTime gameTime)
    {
        Console.WriteLine($"Current Position (Outer): {Texture.Position.Y}");
        if (Keyboard.IsKeyDown(Keys.Space))
        {
            Jump(gameTime);
        }

        UpdateGravity(gameTime);

        if (Keyboard.IsKeyDown(Keys.A))
        {
            velocity.X = -HorizontalMoveSpeed*(float) gameTime.ElapsedGameTime.TotalMilliseconds;
        }
        else if (Keyboard.IsKeyDown(Keys.D))
        {
            velocity.X = HorizontalMoveSpeed*(float) gameTime.ElapsedGameTime.TotalMilliseconds;
        }
        else
        {
            velocity.X = 0f;
        }

        Texture.Position += velocity;

        CheckCollisions();

        base.Update(gameTime);
    }

    private void UpdateGravity(GameTime gameTime)
    {
        velocity.Y += Gravity * (float) gameTime.ElapsedGameTime.TotalMilliseconds;
    }

    private void Jump(GameTime gameTime)
    {
        if (jumping) return;
        jumping = true;
        velocity.Y -= JumpSpeed * (float) gameTime.ElapsedGameTime.TotalMilliseconds;
    }

    private void CheckCollisions()
    {
        foreach (var platform in CryoGame.Platforms.Where(CollidesWith))
        {
            Console.WriteLine($"Current Position (Inner): {Texture.Position.Y}");
            var collision = false;

            var topInsideOther = Texture.Top <= platform.Texture.Bottom;
            var bottomOutsideOther = Texture.Bottom >= platform.Texture.Bottom;
            if (topInsideOther && bottomOutsideOther)
            {
                Texture.Top = platform.Texture.Bottom;
                collision = true;
            }

            var topOutsideOther = Texture.Top <= platform.Texture.Top;
            var bottomInsideOther = Texture.Bottom >= platform.Texture.Top;
            if (topOutsideOther && bottomInsideOther)
            {
                Texture.Bottom = platform.Texture.Top;
                collision = true;
            }

            if (collision)
            {
                velocity.Y = 0f;
            }
        }
    }

Example output:

Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Outer): ...
Current Position (Inner): ...

```


texts: How should I organise classes for a space simulator?

texts:
I have pretty much taught myself everything I know about programming, so while I know how to teach myself (books, internet and reading API's), I'm finding that there hasn't been a whole lot in the way of good programming.

I am finishing up learning the basics of XNA and I want to create a space simulator to test my knowledge. This isn't a full scale simulator, but just something that covers everything I learned. It's also going to be modular so I can build on it, after I get the basics down. One of the early features I want to implement is AI. And I want to take this into account as I'm designing my classes so I can minimize rewriting code.

So my question:
How should I design ship classes so that both the player and AI can use them?

The only idea I have so far is:

Create a ship class that contains stats, models, textures, collision data etc. The player and AI would then have the data for position, rotation, health, etc and would base their status off of the ship stats.


texts: How to code a game that can interact with custom controllers?

texts:
I want to have my work featured in alt.ctrl.gdc someday.

The process of building a bizarre custom controller is a question for a different stackexchange site, but

Can you tell me a way how to take data from a custom controller with potentially a lot of different bizarre data pouring in and then have that data control a game?


texts:
I'm passionate person, who has been around AI from a long time [1] but never going in deep enough. Now it's time!

I've been really looking for some way to concentrate on AI coding but couldn't succeeded to find an AI environment I can focus on. I just want to use an AI sandbox environment which would let me have tools like:

visibility information
character controller
able to easily define a level, with obstacles of course
physics
collider management
triggers management
don't need to be a shiny, eye candy graphical render : this is about pathfinding, tactical reasoning, etc..

I have tried :

Unreal Dev Kit : while the new release announce is about C++ coding, this is about external tools and will be released in 2013
Cry Engine : really interesting as AI is presents here but coding with it appears to be an hell: did I got it wrong ?
Half Life source, C4, Torque, Dx Studio : either quite old, not very useful or costly these imply to dig in documentation (when provided) to code everything, graphics included.
Unity 3D : the most promising platform. While you also need to create your own environment, there are lot of examples. The disadvantage is, in addition to spend time to have this env. working, is the languages choice : C#, Javascript or Boo. C# is not that hard, but this implies you'll allways have to convert papers (I love those from Lars Linden) books codes, or anything you can have in Aigamedev are most often in C++. This is extra work. I've look at "Simple Path", the very good Arong Greenberg work but no source provided and AngryAnt work.
AI Sandbox : this seems to be exactly what as AI coder I want to use. I saw some preview but from 2009 we still don't know what it will be about precisely, will it be opensource or free (I strongly doubt), will I be able to buy it? will it really provide me tools I need to focus on AI ?

That being said, what is the best environment to be able to focus on AI coding only, is it even possible?


texts: Recommended polycount for a MMORPG character

texts:
"How much polygons is too many for a MMORPG character?"

I did some research and found a few discussions about the matter. But the answers I found was mostly "Polygons has nothing to do with networking" and they just start to argue and flame each other.

I think the question wasn't received well because it wasn't clear. So, I'll try to make it a bit clearer.

Consider the main character of an offline game, it has so much details, but it is the only character on the scene for most of the time.

Now, on a MMORPG everyone is a main character. Let us say 100 players are in sight of each other at a given time. If we had the same character from the offline game we'd have too many polygons and frame-rate/performance would suffer.

If I target a minimum system requirement of 4GB memory, Intel i3 (3rd gen) CPU, and at-least a laptop GPU (cheap nvidia mobile?).

How much polygon should my characters be limited to?
or, How much polygons should be on the scene/sight at a time? (including terrain, other objects...)
or, Is there a rule of thumb for polycount that applies to any genre of games?


texts: What is the correct way to implement hit detection with non-rectangular sprites?

texts:
What is the correct way to implement hit or touch detection for non-rectangular sprites in Cocos2d?

I am working on a jigsaw puzzle, so our sprites have some strange forms (jigsaw puzzle bricks). As of now, we have implemented the "detection" this way:

- (void)selectSpriteForTouch:(CGPoint)touchLocation {
    CCSprite * newSprite = nil;

    // Loop array of sprites
    for (CCSprite *sprite in movableSprites) {

        // Check if sprite is hit.
        // TODO: Swap if with something better.
        if (CGRectContainsPoint(sprite.boundingBox, touchLocation)) {
            newSprite = sprite;
            break;
        }
    }
    if (newSprite != selSprite) {
        // Move along, nothing to see here
        // Not the problem
    }
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
    [self selectSpriteForTouch:touchLocation];
    return TRUE;
}

I know that the problem is in the keyword "sprite.boundingBox". Is there a better way of implementing this, or is it a limitation when using sprites based on .png's? If so, how should I proceed?


texts: Java Libgdx: How do you add cells to a TiledMap?

texts: I'm trying to make a Side-Scrolling game that will allow you to place/remove tiles. I'm using the TileMap Editor to render the custom Tilemap but is there any way to add tiles? I have it where I can remove the tiles with .setTile(null) but is there anyway to get the properties from a tile in the TileMap Editor so that it can get the Texture/Tile to use so it can place the tile?!


texts: So let's say my sprite sheet has 3 sprites in one row. One sprite is 64 pixels wide and high. When that is combined my sheet would be 192 pixels wide and 64 high. So from that, how am I supposed to make it's dimensions POT without stretching sprites inside?


texts: Is there a way to run a tool script without attaching it to a node in the scene tree?

texts:
What I want to do is run a tool script on the editor.
The usual way would be to attach it to a scene tree node, but then I'd have to guard it with ifs all over to prevent editor code to be run at runtime and viceversa.
I could instantiate the script and run it directly without it being attached to a node, but the script that instantiates that script would have to be tool too, so not getting rid of the problem.
I guess I could create a node in the scene tree with a tool script attached, that removes itself from the scene tree once the game is running.
Is there a more elegant way of doing it?
Like some kind of project setting to run a tool script on project load?


texts:
I've got a shader that does the texturing, lighting, etc. for my game engine (written on top of MonoGame, in case that's relevant) for my block-terrain-based game (everything is rendered as triangles and each chunk has its own mesh made from logical block objects, recomputed when relevant). I have two versions of this shader, a SM2 one and an SM4 one (for different targets), both do the same thing and are almost identical but I primarily focus on the SM2 one since that is for the primary target.

Anyway, a week or so ago I implemented directional lighting, and it looks fine.. except it seems to fail to take the distance from the light source into account - i.e., every block looks like it's an equal distance from the light source.

I tried setting up some obvious solutions - I was already calculating the direction of the light using a parameter of the light position with the vertex position, so I took an intermediate (pre-normalization) value of this and used it as the distance to modulate the intensity of the light. Sounds good, yeah? Well, it somehow made no difference at all. I can't seem to find a piece of software to help me debug a vertex/pixel shader combo (only lone pixel shaders), so I'm basically stuck thinking through the logic and trying things. That's a familiar debug style for me, but I've been trying for a week or two and haven't come up with anything that has made a difference.

I've since stripped this out of the shader (since it didn't work, and I wanted to just work on other things for a while), but I was calculating the distance in the vertex shader (and passing it to the pixel shader) like this:

float3 final3DPos = mul(inPos, World);
float3 direction = -(final3DPos - LightPosition);
Output.LightDirection = direction;
Output.LightDistance = length(direction);

I also tried setting LightDistance to (abs(distance.x) + abs(distance.z)), with distance being what in the above is LightDistance - I ignored Y since it's constant and figured it would exaggerate the difference between positions.. same effect!

In the pixel shader, LightDirection is normalized before use.

I tried setting the end result as a color made from the distance, and everything ended up black. I tried dividing this by various values in case the numbers were too big and multiplying by 255, and no matter what i did everything was the same color.

I tried just using it in the calculations by dividing by it or deriving a multiplier to use from it, and again every block was lit the same.

I could pass the distance to the light in with the vertex information, but calculating that and sending it in for EVERY VERTEX seems really stupid and unnecessary.. :(


texts: The better performance in occlusion culling, plane or quad?

texts:
In the above picture, when the left camera shows two small parts of the quad, all of that is rendered (it can be a very large quad). But in the right one only two small parts of it is rendered.
Which of them has better performance?

On the other hand if camera rotates by 180 degrees then what? plane seems to have more vertices to be loaded than the quad.

What the overall decision should be? using quads or planes?


texts: Unity2D Register which player colliders have activated

texts:
I have a player character that has three separate coliders that form this shape (one for the top, one for the bottom, and one for both sides)

I'm trying to register floor collisions with the bottom collider so that I can reset jumping stuff (double jumps, etc), but since the corners are all touching the floor, I end up having the side colliders enter as well when I use OnCollisionEnter2D().

Is there a way to get which colliders are contacting, or is there a better way to register these collisions?


texts: Execute Timer Events of another Blueprint from the C++ UE4

texts:
I am having problem and it's about a week now that I still can't figure out how to get it right.

It seems that I can't run any functions from the blueprints that contain timers at all.

I have a Datatable full of details of each functions that will executed according to its key input and the owner of the functions.

The ordinary functions and custom events executed well but will stopped at a timer.

This is the code that I have made so far. I added the matching functions string into the delegate with its Owner which is the obj, and it will executed on key input.

p.s: Ignore the error, Intellisense was messing me up

I saw the error regarding the world not found here,

but I'm not sure if that is the case since other functions without any timer inside can execute well. Any ideas? Thanks.


texts:
I would like to write a "game", where you can place an obstacle (red), and then the black dot tries to avoid it, and get to the green target.
I'm using a very easy way to avoid it, if the black dot is close to the red, it changes its direction, and moves for a while, then it moves forward to the green point.

How could I create a "smooth" path for the computer controlled "player"?
Edit: Not the smoothness is the main point, but to avoid the red blocking "wall" and not to crash into it and then avoid it.

How could I implement some path finding algorithm if I just have basically 3 points?
(And what would it make the things much more complicated, if you could place multiple obstacles?)


texts: How to sample a texture with specified LOD in SM 2.0?

texts:
That is my question, in SM 3.0 there is the HLSL intrasic function tex2Dlod to pick a color on a texture2d at specified coords and specified level-of-detail.

But after long search on the web, I don't find equivalent in SM 2.0 (ps_4_0_level_9_3)...


texts: Rendering only a part of the screen in high detail

texts:
If graphics are rendered for a large viewing angle (e.g. a very large TV or a VR headset), the viewer can't actually focus on the entire image, just a part of it. (Actually, this is the case for regular sized screens as well.)

Combined with a way to track the viewer's eyes (which is mostly viable in VR I guess), you could theoretically exploit this and render the graphics away from the viewer's focus with progressively less details and resolution, gaining performance, without losing perceived quality.

Are there any techniques for this available or under development today?