texts: How can I find when moving the mouse pointer over raw image to what file it belong to?

texts:
I have on the hard disk some images and saved files. Each image have his saved file.
10 images and 10 saved files :

Then I'm loading the images to rawimages and when running the game it looks like that :

This script is loading the images to raw images :
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class SavedGamesSlots : MonoBehaviour
{
    public GameObject saveSlotPrefab;
    public float gap;

    private Transform slots;
    private string[] imagesToLoad;

    // Start is called before the first frame update
    void Start()
    {
        imagesToLoad = Directory.GetFiles(Application.dataPath + "/screenshots", "*.png");
        slots = GameObject.FindGameObjectWithTag("Slots Content").transform;

        for (int i = 0; i < imagesToLoad.Length; i++)
        {
            var go = Instantiate(saveSlotPrefab);
            go.transform.SetParent(slots);

            Texture2D thisTexture = new Texture2D(100, 100);
            string fileName = imagesToLoad[i];
            byte[] bytes = File.ReadAllBytes(fileName);
            thisTexture.LoadImage(bytes);
            thisTexture.name = fileName;
            go.GetComponent<RawImage>().texture = thisTexture;
        }
    }

    // Update is called once per frame
    void Update()
    {

    }
}

And the last script is for moving the mouse over the raw images and then it's making each image the mouse cursor is over to be brighter :
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class MouseHover : MonoBehaviour
{
    public SaveLoad saveLoad;
    public SceneFader sceneFader;
    public RawImagePixelsChange rawImagePixelsChange;

    private bool loadGame = false;

    public void OnHover()
    {
        Debug.Log("Enter");
        rawImagePixelsChange.modifyPixels(0.3f);
        PlaySoundEffect();
        loadGame = true;
    }
    public void OnHoverExit()
    {
        Debug.Log("Exit");
        rawImagePixelsChange.restorePixels();
        loadGame = false;
    }

    private void Update()
    {
        if(loadGame)
        {
            if (Input.GetMouseButtonDown(0))
            {
                StartCoroutine(sceneFader.FadeAndLoadScene(SceneFader.FadeDirection.In, "Game"));

                loadGame = false;
            }
        }
    }

    private void PlaySoundEffect()
    {
        transform.GetComponent<AudioSource>().Play();
    }
}

In this script the MouseHover I want to find and get the save file name the mouse cursor is over the image that belong to the saved file. Either inside the OnHover function or inside the GetMouseButtonDown.
Maybe it's be if I will save each image and it's saved file in another folder to identify easier what image belong to what saved file.
now the way the images and saved files are on the hard disk each image the saved file to his left are belong to each other they have saved the same time. So when I click the button mouse down in the MouseHover script it should load the specific saved file the mouse cursor is over the image.


texts:
Possible Duplicate:
  Would it be better to use XML/JSON/Text or a database to store game content?

I'm working on a 2D data-driven RPG. I intend for it to be modabble; my intention is to expose all the major game data (eg. monster stats, item stats, pet stats) through some interface to allow tweaking by end-users with a tool.

First, my basic assumption is that there will be a "lot" of data (perhaps on the order of magnitude of megabytes). I have a few requirements that I'm trying to figure out.

How to efficiently store and load the data. For example, a SQLite DB would be faster than reading text files on startup.
How to make it version-control friendly (text-files wins here).
How to maintain data integrity. If it's just a text-file, you can put invalid values in it.
If possible, I would like to allow users to make their own tools to crunch my data.

Since maintaining version-control friendly data is important, I think having one or more text files with data in it will win. I can probably try to get people to use my tools to edit the data, and put lots of integrity checks in the actual code (eg. if totalHealth < 0, throw).

Are there better approaches to achieve these four goals?

I would also like input on the file format (eg. YAML vs. XML vs. JSON vs. whatever)


texts:
What is the math theory when a child object moves with the parent transform?

I am doing an angle indicator which shows a field of view, which works fantastic when the angle is static. But I cannot get the
field of view indicators to play nice with the angle changing. Everytime I change the angle, the indicators are reset to
default positions and then the direction indicator and FoV indicators are out of sync.

There is of course a ghetto way of resetting the whole thing when changing the angle, but I'd prefer not to do it that way.

The red circles are the points which are used to draw the FoV lines and they are childed to the white sphere. If the angle is not modified after start they follow the white sphere nicely and show the FoV correctly.

Here is how it looks after trying the dynamic angle changing. The FoV lines should be pointing to the right and the white sphere should be in the middle.

Currently I am changing the red circles' position based on the angle given(transform is the green square in the middle.):

leftAngle.transform.position = transform.position + new Vector3(Mathf.Cos(firstLineRendererAngle * Mathf.Deg2Rad), 0, Mathf.Sin(firstLineRendererAngle * Mathf.Deg2Rad)) * 10;
rightAngle.transform.position = transform.position + new Vector3(Mathf.Cos(secondLineRendererAngle * Mathf.Deg2Rad), 0, Mathf.Sin(secondLineRendererAngle * Mathf.Deg2Rad)) * 10;

How do I add the position of the FoV direction sphere to emulate parent-child relationship with the objects?


texts: Code is skipped after await call and returns to the calling method

texts:
I'm developing a roguelike game in Unity using the RogueSharp library. Currently I'm stuck on realizing the turn-based combat aspect of the game (inspired by this tutorial), which is made up of a scheduling system that keeps track of the actors (i.e., the player and monsters) and handles the order of actions they can perform.
private async void ActivateMonsters()
{
    var scheduleable = SchedulingSystem.NextActor;
    UnityEngine.Debug.Log($"Turn of {scheduleable}!");

    if (scheduleable is Player)
    {
        IsPlayerTurn = true;
        SchedulingSystem.Add(Player);
    }
    else
    {
        if (IsPlayerDead)
        {
            return;
        }
        if (scheduleable is Monster monster)
        {
            UnityEngine.Debug.Log("Start monster turn!");

            if (await monster.PerformAction(InputCommand.None))
            {
                UnityEngine.Debug.Log("Monster action done!");

                SchedulingSystem.Add(monster);
            }
        }

        ActivateMonsters();
    }
}

At the bottom of the method, there is a recursive call to ActivateMonsters() for ensuring that all monsters perform their actions until the player has a turn again.
Since my roguelike game is graphical and not text-based, the monsters have animations for attacking, walking, etc., that should be displayed on every turn. Therefore, the game should wait for each monster to perform its attack including playing the corresponding animation, before moving on to the next monster's turn. To achieve that, I've made the ActivateMonsters() method async and wait for monster.PerformAction() to end (the InputCommand.None input enum can be ignored).
ActivateMonsters() is initially called in this event handler method invoked in Unity's Update() method:
private void UpdateGame(object sender, EventArgs e)
{
    if (IsPlayerTurn)
    {
        HandleKeyboardInput();
    }
    else
    {
        UnityEngine.Debug.Log("First ActivateMonsters() call!");
        ActivateMonsters();
        RenderRequired = true;
    }
}

monster.PerformAction() first calculates the next position of the monster via pathfinding in an async method, which then calls the following method:
public static async Task<bool> Move(Actor actor, Loc location)
{
    EnsurePropertiesAreSet();
    var previousActorPosition = actor.Loc;

    // Return true if moving the actor to the given location was successful.
    if (DungeonMap.SetActorPosition(actor, location))
    {
        if (actor is Monster monster)
        {
            var moveDirection = location - previousActorPosition;

            await Task.Delay(3000);

            // Move the monster on the map.
            Game.SetMonsterMoveDirection(monster, moveDirection);
        }

        return true;
    }

    return false;
}

For testing purposes, I put in the await Task.Delay(3000) before the monster moves to the next tile.
With this I get:
First ActivateMonsters() call!
Turn of BrainHero.RogueLike.Actors.Goblin!
Start monster turn!
First ActivateMonsters() call!
Turn of BrainHero.RogueLike.Actors.Player!
[3 second pause]
Monster action done!
Turn of BrainHero.RogueLike.Actors.Player!

However, what I want to get is:
First ActivateMonsters() call!
Turn of BrainHero.RogueLike.Actors.Goblin!
Start monster turn!
[3 second pause]
Monster action done!
Turn of BrainHero.RogueLike.Actors.Player!

The await Task.Delay(3000) part does work, but it seems like that the if (await monster.PerformAction(InputCommand.None)) is skipped and the code execution returns to UpdateGame() for some reason. How can I modify the code so that I can achieve the latter execution sequence?
Thanks in advance for any help in solving this issue!


texts:
I am trying to build a shader that change the output color according to something that happen in my c++ code

In my code I create a buffer with four element(each element containe four float - RGBA)

then I create four shader resource view associate with that buffer.
the first shader resource view contain the first element in the array the second shader resource view contain the second element in the array and so on.

in my code there is no exceptions and I can see in the diagnostic that my correct shader resource view with the correct resource associate to the pixel shader but in my pixel shader I get nothing.

Here is my pixel shader:

cbuffer cbChangesEveryFrame : register( b0 )
{
matrix worldMatrix;
};
cbuffer cbNeverChanges : register( b1 )
{
    matrix viewMatrix;
};
cbuffer cbChangeOnResize : register( b2 )
{
    matrix projMatrix;
};
float4 outPutColor : register(s0);
struct VS_Input
{
    float4 pos  : POSITION;
};
struct PS_Input
{
    float4 pos  : SV_POSITION;
};
PS_Input VS_Main( VS_Input vertex )
{
    PS_Input vsOut = ( PS_Input )0;
    vsOut.pos = mul( vertex.pos, worldMatrix );
    vsOut.pos = mul( vsOut.pos, viewMatrix );
    vsOut.pos = mul( vsOut.pos, projMatrix );

    return vsOut;
}
float4 PS_Main( PS_Input frag ) : SV_TARGET
{
    return outPutColor;
    //return float4(0,0,1,1);
}

The shader resource view should associate to outPutColor but when I debug the shader I get four float of zero.
Why I getting zero instead my buffer?


texts: Is there any heuristic to polygonize a closed 2D raster shape with n triangles?

texts:
Let's say we have a 2D image black on white that shows a closed geometric shape.

Is there any (not naive brute force) algorithm that approximates that shape as closely as possible with n triangles? If you want a formal definition:

  Approximate the shape with a polygon that when rendered into a new 2D
  image will match the largest number of pixels possible with the
  original image.


texts: Calculating the illumination level of an object

texts:
In my (UE4) scene I have an object and several (point) light sources. The object can move around, getting closer and away from all those light sources. Now I need to calculate for each light source how much it affects the object at its current position (i.e. distance from the light).

Every light source has three important values:

Intensity: How bright the light shines (integer vlaue 0..10000)
Attenuation: Radius around light, how far it visibly influences the scene
Falloff exponent: Radial falloff around light (inverse squared by default, or can be an integer between 2 and 8)

Now, depending on how far the object is from a light source, it is more or less affected by the light. If the object is outside the attenuation radius, it is not affected at all by the light. I am not so much interested in the light intensity, but more in the distance between the object and a light.

For each light I am interested in a value between 0 and 1. So the easy way would be to simply calc: 1 - distance / attenuation. But I would like to take the falloff exponent into account. Any ideas how to accomplish that?


texts:
Assume I have a behaviour tree like the following:

    [A]
   / | \
[B] [C] [D]

A = Selector (Priority node)
B = Perception task
C = Idle task
D = Walk to point task

The reason the tree looks like this is because B has priority over C and D since it should trigger alert procedures. In short, what I'm trying to model here is that the Agent sensors must have priority over behaviours.

Assume now the agent is in D and this node will continue returning running until the destination point is reached.

While D is running, something might happen (for instance, the NPC see or hear something) that should break the current operation as soon as possible but, D will go on regardless until it's done.

I know I could paste the sensors code on top of each tree leaf, like for example:

// kinda javaish pseudo code
void run() {
    // The node running method
    if (this.sensors.alert()) {
        return this.fail();
    }

    // Else, keep going.
    if (! this.reachedGoal()) {
        // do the walking
        return this.running();
    }

    return this.success();
}

But with that solution the "alert" behaviour is hard coded and out of the tree logic.

What solution do you suggest?


texts: Unity3D - Cancel a build process (Windows, Unity 5)

texts: I accidently pressed build for iOS and just realized that it might take a few hours to build the project. I tried to kill the unity process in the task manager, but on next start up unity instantly starts to build it again. Is there any option to cancel the build?


texts: How to draw grass sprites without using gameobjects?

texts:
I am making a rimworld-like procedurally generated 2D game using Unity's tilemap system.
Just like tiles, I also have to procedurally generate grass and trees. Each grass instance should have logic inside that keeps track of it's growth progress and update the grass size appropriately.
The downside is, I have to have maps as big as 400x400. That could be THOUSANDS of grass instances and each of them having their own GameObject seems ridiculous and like the game would lag.
How can instantiate those grass sprites without creating new gameobjects for each one while still being able to control the growth and similar things?
(Come to think of it, the DOTS / ECS system in Unity would be perfect for this, however it is nowhere near ready and many things I want to do are just not supported.)


texts: Given a constant rotation and target point, find position so that point will be in camera center

texts:
Given a fixed rotation and a target "center" point, how to I find the position the camera should be in so that that point is the center? LookAt changes the rotation keeping the position constant. Basically, I'm trying to do the reverse, but the math escapes me :-). Thanks!

Camera is currently psuedo-isometric (orthographic with rotation from Euler angles [X:35.264389683ish°, Y:45°, Z:0°]). Might want to change these a bit or allow rotation though, so ideally a solution would work for any rotation. Can easily get the projection matrix.

EDIT: thinking about it, there would be infinite such positions that satisfy this constraint. I would want to fix the Y component of the position (camera height) and find only an X/Z.

Thanks to Mokosha's answer below, here's the final code I'm using:

    private static Vector3 reverseLookAt(Quaternion cameraRotation, float cameraHeight, Vector3 targetPosition)
    {
        Vector3 d = cameraRotation * Vector3.forward;
        Plane plane = new Plane(Vector3.up, -cameraHeight);
        Ray ray = new Ray(targetPosition, d);
        Vector3 pos = UnityUtils.intersect(ray, plane);
        return pos;
    }


texts: How to render line renderer or trail renderer above UI canvas

texts:
I want to create a line renderer and also trail renderer that would follow touches but both must be rendered above my UI canvas — how can I do this?

I have tried this with the "screen space camera" mode and just came to know that it is not possible with screen space camera.

Is it possible by using line or trail with a "screen space overlay" canvas? If yes, then how could I make line/trail follow the touch position in such a setup?

I tried this before but i was not able to make it appear on screen rather it appeared on world as if it is ignoring the overlay canvas.Then I switched to screen space camera and this problem arose.


texts:
I want to export ingame items to seperate data files. Those files should also be "openable" to display information about the item. My idea is to create every item as an .exe that will open a small windowed unity app with and image and some texts/tabs.

How would I handle this "procedural building of .exes" from within another application? For exeample I have a game with an inventory. And when I press "export to file", the item is build to an "item data exe file", that is then portable and openable as a standalone "item previewer".

Thank you for help. For the start a general assessment of this idea could also be helpful.


texts:
I'm making a voxel engine, and I'm trying to figure out the right way to make efficient collisions with a slide response (making the player slide against the wall).

Currently my collisions are pretty simple : if, after update, the player bounding box collides with the voxel world, then we just cancel the collision.

I have seen this answer on SO, but I don't understand what the answerer means here. Since a voxel is a single unit, how can I compute its normal ? Should I map the 3x3x3 block surrounding the voxel to a precomputed normal ?

  Take the unit surface normal of the colliding voxel (pointing outward).


texts: Stuck in an infinite recursion in Minesweeper

texts:
I am trying to build a simple minesweeper game. The game gets stuck in an infinite recursion whenever a user clicks on a tile which is not a mine...

I have used the following function code for the click event..

When a user clicks on a tile which is not a mine, its adjacent tiles are to be checked for a mine and the process repeats.... I have used a recursive function which disables the tiles for which adjacent tile is not a mine...

  protected void set_text_of_button(Button btn)
  {
      //all these objects specify the location of adjacent tiles
      Block Top, Top_Left, Top_Right, Left, Right, Bottom, Bottom_Left, Bottom_Right;

      //code to specify the location of adjacent tiles...

      //if adjacent tile is a mine then display the total number of tiles....
      //recursive function should end in this if part..

      else
      {
      //recursive calls for all the adjacent tiles..

              if (Top != null && !Top.Mine)
                  set_text_of_button(Top.btn);         //recursive call
              if (Top_Left != null && !Top_Left.Mine)
                  set_text_of_button(Top_Left.btn);
              if (Top_Right != null && !Top_Right.Mine)
                  set_text_of_button(Top_Right.btn);
              if (Left != null && !Left.Mine)
                  set_text_of_button(Left.btn);
              if (Right != null && !Right.Mine)
                  set_text_of_button(Right.btn);
              if (Bottom.btn != null)
                  set_text_of_button(Bottom.btn);
              if (Bottom_Left.btn != null)
                  set_text_of_button(Bottom_Left.btn);
              if (Bottom_Right.btn != null)
                  set_text_of_button(Bottom_Right.btn);

      }
  }

can the following code be implemented or is there a better algorithm to perform the task...


texts:
What is a good source for sound effects for use in an indie game production (C#, XNA)?

The sounds do not need to be free.
They, however, should have a clear licence for commercial use.
The website should allow for searching, browsing and preview (or better: pre-listening).

I already had a look at http://www.1soundfx.com but their collection is not too large. I am specifically looking for sound effects. No music and no ways to make my own sounds.

All help is greatly appreciated!


texts: FileNotFoundException while using ShaderbyteCode.CompilefromFile method

texts:
I'm currently learning SlimDX, I want to load a Shader from tutorial which is named "triangle.fx" and it is in a folder called "FX",everything is in my solution.
When I'm typing this line of code:

 using (var bytecode = ShaderBytecode.CompileFromFile(@"FX/triangle.fx", "PShader", "ps_4_0", ShaderFlags.None, EffectFlags.None))

I'm getting FileNotFoundException, and I don't know why because everything exists in my solution.


texts: WriteObject in XNA with existing ContentWriters

texts:
I have quite a lot of custom content pipeline components, and I was just wondering if under the hood XNA knows about these things when doing its magic...

Here is my scenario.

I have animation objects which basically contain 2d animation frames and timings etc, which can be loaded as self contained objects or can be embedded within other object. Now I was expecting that my CustomObjectAWriter could contain an instance to AnimationObjectAWriter and internally just call through to that to write out each animation object, i.e:

<SomeCustomObjectA>
    <SomeCustomElementA>
        ...
    </SomeCustomElementA>
    <SomeCustomElementB>
        ...
        <AnimationObjectA>
            ...
        </AnimationObjectA>
    </SomeCustomElementB>
</SomeCustomObjectA>

However as AnimationObjectAWriter has its Write method protected I am unable to access it, however I was wondering if WriteObject will know of the AnimationObjectAWriter so if I did WriteObject<AnimationObjectA>(animationObjectAInstance) would this work?


texts: Ordered dithering between "discrete" colors?

texts:
I want to achieve color dithering between discrete colors like this:

As you can see, there is no gradient, or technically there is, but very discrete as it's only a 3 color image (right bar).

So I want the same results applying ordered dither (or at least try it and see if it works).

I have this test sample:

And this is teh function where i do the dithering:

// OrderedDither applies a Bayer matrix to dither.
func OrderedDither(img image.Image, palette []color.Color) image.Image {

rImage := image.NewRGBA(img.Bounds())

matrix := [][]float64{
    {0, 4, 1, 5},
    {8, 12, 9, 13},
    {2, 6, 3, 7},
    {10, 6, 11, 15}}

for j := 0; j < img.Bounds().Max.Y; j++ {
    for i := 0; i < img.Bounds().Max.X; i++ {
        m := matrix[i%4][j%4] / 16
        oldPixel, _ := colorful.MakeColor(img.At(i, j))
        oldPixel.R = oldPixel.R*m + oldPixel.R
        oldPixel.G = oldPixel.G*m + oldPixel.G
        oldPixel.B = oldPixel.B*m + oldPixel.B
        newPixel := GetClosestColor(palette, oldPixel)
        r, g, b, _ := newPixel.RGBA()

        rImage.Set(i, j, color.RGBA{R: uint8(r), G: uint8(g), B: uint8(b), A: 255})
    }
}
return rImage

}

I get this:

As you can see, there is not dithering in the borders and the dithering inside the boxes is awful.

Any recommendations?

Edit: I implemented the average distance in the 16 color palette:

r := AverageColorDistance(palette)

for j := 0; j < img.Bounds().Max.Y; j++ {
    for i := 0; i < img.Bounds().Max.X; i++ {
        m := matrix[i%4][j%4]/16 - 0.5
        oldPixel, _ := colorful.MakeColor(img.At(i, j))
        oldPixel.R = oldPixel.R + r*m
        oldPixel.G = oldPixel.G + r*m
        oldPixel.B = oldPixel.B + r*m
        newPixel := GetClosestColor(palette, oldPixel)
        r, g, b, _ := newPixel.RGBA()

        rImage.Set(i, j, color.RGBA{R: uint8(r), G: uint8(g), B: uint8(b), A: 255})
    }
}

And the result was not satisfactory neither:

The average color was 0.4792891. (got 256 values in a 16 color palette).

But in either case i still got no blur between the boxes. Should i stop trying to make Ordered work and go Floyd-Steinberg? I want to get some blur between the hard edges.


texts: How to reference a GameObject that shares position with gameObject in Unity C#

texts:
Well, thats a weird title. What i am trying to do is identify the object which position matches the gameObjects position that the script is attached to.
Hell, that didn't make it better.

Here's my script:

  public Vector2 tilePosition;
  public float tileYPiece;

  void Update()
      {
          tilePosition = transform.position;
          tileYPiece = tilePosition.y + 0.5f;

          pieceIdentifier();
      }

  void pieceIdentifier()
      {
          if ((tileYPiece) == GameObject.FindGameObjectWithTag("Piece").GetComponent<PieceScript>().piecePosition.y && tilePosition.x == GameObject.FindGameObjectWithTag("Piece").GetComponent<PieceScript>().piecePosition.x)
          {
              //the GameObject I need to reference does something

          }

      }

So the tile position is a Vector2(x, y), and the piece's position is a Vector2 (x, y) as well, and I need to reference the GameObject that shares position with the tile.

I'm confused as hell, if you hadn't noticed, and would reeally like some help

Thanks in advance


texts: Is there a way to check android version running the game using Unity3D?

texts: I want to separate code to run only on android 4.4 or higher. If it's lower, I do not want to run  this code. What should I do?


texts:
I'm creating a Tetris clone right now. I've got the tiles of tetromino stored as an std::array<tile, 4>. Each tile holds its (x,y) coordinates relative to the piece. For example, the t-block is:

(-1, 0)
( 0, 0)
( 1, 0)
( 0,-1)

I want to create a function: rotate(const bool clockwise) that applies a 2D rotation matrix to the tiles to rotate the block either 90 degrees clockwise, or 90 degrees counter-clockwise.

After doing some reading on rotation matrixes, I've found that a 2D rotation matrix looks like this:

 cos(angle), sin(angle)
-sin(angle), cos(angle)

Since I'm doing 90 degrees only, I figure it should look like this:

//clockwise
 0, 1
-1, 0

//counter-clockwise
 0,-1
 1, 0

After doing some more reading on how to multiply matrixes, multiplying the tile position by the matrix gives me this:

//(-1, 0) should end up as (0, 1) if rotated clockwise

-1                     0, 1                1,-1
 0  /*multiplied by*/ -1, 0  /*gives me*/  0, 0

My question is how do I get an (x,y) position out of that result? Am I missunderstanding how matrixes work? Is there a more trivial way to rotate coordinates around the axis by 90 degrees?


texts: How do I make the background color fade into a different color after hovering it?

texts:
I was trying to make the starter inputs for my text rpg change the background color in a fade effect with JQuery, but I cant figure out what i did wrong. Heres the part im focusing on:

  <script>
    $(document).ready(function() {
      $Intro_Inputs = $('#Header_Intro input');
      $Intro_Inputs.hover(function() {
        $(this).animate({'background-color':'#2E8AE5'}, 'slow');
      });
    });
  </script>

If anyone could help me out with the mistake i made i would greatly appreciate it!

(The problem was that it wouldnt fade the colors in)


texts: How to create adjustable formula for RPG level up requirements?

texts:
I'm trying to create a formula that can be modified simply by changing two values: number_of_levels, and last_level_experience. This is to enable people modding the game to change the levelling requirements.

I've got it so that I can specify the number of XP needed for the last level up, but I want to be able to control the XP needed for the first level up, which in this case can differ wildly. For example, if I have 40 levels, and 1,000,000 XP for the last level, the first level up requirement is then 625. But if I change the levels to 80, the first  level up becomes 156. In both cases, the last level needs 1,000,000.

There must be some way to get the computer to work out a suitable curve given just these two basic values.

#include <iostream>

int main()
{
    int levels = 40;
    if (levels < 2) levels = 2;

    int experience_for_last_level = 1e6;
    float fraction = 1.0 / levels;

    {
        int i = 0;
        float fraction_counter = fraction;
        int counter = levels;
        int total = 0;

        for (i = 1; i <= levels; ++i, fraction_counter += fraction, --counter)
        {
            int a = static_cast<int>(fraction_counter * experience_for_last_level / counter);

            std::cout <<"Level "<<i<<":  "<<a<<" ("<<counter<<")"<<"\n";

            total += a;
        }

        std::cout << "\nTotal Exp: " << total;
    }
}

Output:

Level 1:  625   (40)      Level 15: 14423  (26)      Level 29: 60416  (12)
Level 2:  1282  (39)      Level 16: 16000  (25)      Level 30: 68181  (11)
Level 3:  1973  (38)      Level 17: 17708  (24)      Level 31: 77499  (10)
Level 4:  2702  (37)      Level 18: 19565  (23)      Level 32: 88888  (9)
Level 5:  3472  (36)      Level 19: 21590  (22)      Level 33: 103124 (8)
Level 6:  4285  (35)      Level 20: 23809  (21)      Level 34: 121428 (7)
Level 7:  5147  (34)      Level 21: 26250  (20)      Level 35: 145833 (6)
Level 8:  6060  (33)      Level 22: 28947  (19)      Level 36: 179999 (5)
Level 9:  7031  (32)      Level 23: 31944  (18)      Level 37: 231249 (4)
Level 10: 8064  (31)      Level 24: 35294  (17)      Level 38: 316666 (3)
Level 11: 9166  (30)      Level 25: 39062  (16)      Level 39: 487499 (2)
Level 12: 10344 (29)      Level 26: 43333  (15)      Level 40: 999999 (1)
Level 13: 11607 (28)      Level 27: 48214  (14)
Level 14: 12962 (27)      Level 28: 53846  (13)


texts: Is there any way to embed browser component into game for facebook Authentication?

texts:
Say I have desktop game and I like to make it social, for that I need browser component
embedded into my game  ( c++ openGL) for the Authentication part. Is there any framework
for that?


texts: Resource Files creation and quick parsing

texts:
I'm having to come up with the format of my Resource File and I'd like to ask about the ways they're made, for example, if I'm using the code:

ifstream fileReader;
fileReader.open("Test.fbx");

if(fileReader.is_open())
{
    char buffer[256];
    while(fileReader.eof())
    {
        fileReader >> buffer;
        //Here
    }
}

When parsing .OBJ or .ASE files from 3DS Max, I could simply check for a...

if(strcmp("VERTEX:", buffer) == 0)
{
    //Whatever I want to do with vertexes
}

...because each vertex value was separated by an empty space, but when parsing a .FBX there's no spaces until the end of the line, and thus I had to:

int lineLength = strlen(buffer);
for(int i = 0; i < lineLength; i++)
{
    //buffer[i] has my current char
}

And get the values together by counting how many ',' I went through, etc.
I think the 2nd way is much worse due complexity, but I don't know how it affects performance-wise.

What are the best practices for the creation of asset files?
I plan on having all of them in a single file, but separated by something like "IMG:" (all image data defined by IDs) "OBJ:" (all model data) "WAV:" (all audio) etc.

Edit:
I'm asking if there's any "best practices" when developing your own resource file, and it'd be binary of course, and I didn't meant to use the original resource files at all.
Something like this:

Resource.dat (in ASCII)
IMG:
1 MyPicture.jpg [binary data composing only what I need from a .jpg file] ;
2 AnotherPicture.bmp [binary data composing only what I need from a .bmp file] ;
OBJ:
3 MyModel.fbx [fbx binary data] ;

etc
I won't save all the file headers for example, and I probably won't have more than one format for my resources, I'll be converting them all to just the data I need into my resource, such as the imageWidth, imageHeight, and 4 values per pixel for a image resource.
I have another code which parses these original files (.jpg, .fbx) and I'm going to save them into a new resource file (in a bloated .dat, organized by object index) to be used in the game engine, but I'd like to know any best practices while creating such a format so I don't code everything just to figure out after "Ops, I should've also saved [data] because I need it now"


texts: Is it a useful strategy for Mobile VR titles to render faster than their simulation loop?

texts:
For example - If a title had a very heavy simulation loop (say 20ms), is it desirable to render at a greater rate, say 90hz?
This would always a present head pose correct to the view, without being stalled on simulation.
Or does this result in discomfort for the player, and instead render and sim should stay in lockstep?


texts:
I'm working on a Fire Emblem style tactical engine, and looking into the AI.

I have it working so enemies will find the best target within their movement/attack range, but what about when no units are within range- for example at the start of the map when they're far away. Who do they decide to move towards?

Does it just pick out the weakest from the player units? Does it go for the nearest?


texts: Is my skill tree possible, balanced, or even a good idea?

texts:
Like most people, I have an idea for a game. I have a particular concept I want to create with a particular set of mechanics I want to implement.

What I need help with is the underlaying player statistics, how they effect what the player can do, and how I can enable a player endless expansion down a particular path that improves only a small sub-set of those statistics.

The entire game will be turn based. The concept is to explore and learn about the world you're in. Books, scripts, notes-on-napkins will lead you to secrets and dungeons. There are no quests to do this for you. You have to read, study and venture forth.

The base stats will decide how effective you are in combat as well as other areas of exploration and general existence in the world.

It could be important to mention that combat in my system isn't realtime or even in the control of the player. The player decides to enter a dangerous area of the map and the computer decides if they get into combat. The computer also rolls some dice and applies modifiers based stats, and finally decides who is the winner. You may die, you may be able to flee. I haven't decided yet.

At this moment in time, I'm considering the following (classic) player stats:

Strength
Stamina
Intelligence
Wisdom
Agility
Intuition

I'm considering the following three class types:

Combat
Magic
Stealth

Class types have two base statistics behind them:

Combat: Strength and Stamina
Magic: Intelligence and Wisdom
Stealth: Agility and Intuition

Somewhat obvious, I guess. Moving further into the mechanics, I had the following progression system in mind:

Levels 1-50 are about learning the game and its mechanics
Advancing to level 50 is fast and is also the cap
After level 50, you gain Guild Wars 2 style "Mastery" points which allow you to enhance specialisations
The end-game is about horizontal progression and mastering your class type, but more importantly, it's about lore and finding it

The idea behind Specialisations is you invest Mastery into them and they force your character down a particular path: combat, magic, or stealth. They also lock you out of the other paths, so you can't mix and match. You have to think about what it is you want to do and whether you can do it based on your understanding of the area you're going into.

The idea behind locking a player down a particular path (which can be unlocked and reassigned, but with research, effort and work) is I want to make it difficult for players to simply construct a "super character" that can take on everything and everyone. Think about how easy it is to become a super mage in Skyrim that can blow everything up... boring!

I want a world in which a very powerful mage is useless against certain monsters simply because of the magic resistance and shear strength that monster has: it forces the player to respec' and rethink before walking into any situation.

To summarise, my thoughts so far are:

Base stats effect everything the player does
Equipment can effect the base stats as well as potions and the other classic stuff
Specialisations effect only two stats and lock out other specialisations
Mastery points go on and on, but the "leveling" curve gets harder and harder quit quickly
Mastery and leveling up a particular specialisation enables the player enter new parts of the world (which is massive, by the way) and continue exploring, but not without first researching what's there (and respeccing as a result)

Am I looking at a dead end here, or is this possible? I'm brand new to game development and really enjoy the mechanics behind games. Am I describing a classic setup here, perhaps? Or something close to one?

I would welcome and greatly appreciate all feedback. I'd even welcome a preexisting system I can copy/paste into my world and just use ;-)

Thanks again.

EDIT: Thanks for the great replies and questions. I think I'm getting this a bit backwards and will, instead, focus on my location and movment, then overlay combat when the time comes :-)


texts: Good algorithm to generate pixels for thick line?

texts:
I am not really making some drawing as of picture manipulation but I use line function to calculate "claimed" pixels in my line race game (demo here):

The actual rendering is apart from the game algorithm which uses map of integers to remember which line "claimed" which pixel. I intentionally do the game logic based on pixels, not line intersections, because in future I want to add all kinds of shapes and analytic geometry would make that pain to implement. Instead, I'll use raster map and eventually make it look smooth on the rendering side.

The problem I have right now is that under special occasions, one line can cross another - and this is not an algorithm error but concept error. The problem happens because sometimes, the lines look like this:

As you see, there's no pixel collision - and this is not as unlikely as it seems. Making the line thicker would fix this and probably also make the game look better, but it has a flaw too - the line will now "claim" pixels it has already claimed last iteration. The current "thin" algorithm is  basically just copied from wikipedia:

/**
 * Returns array of points that form line between x1,y1 and x2,y2. The array looks like this:
 *  [x,y,x,y,x,y...]
**/
Line.straightPoints = function(x1,y1,x2,y2) {
  var result = [];
  // Define differences and error check
  var dx = Math.abs(x2 - x1);
  var dy = Math.abs(y2 - y1);
  var sx = (x1 < x2) ? 1 : -1;
  var sy = (y1 < y2) ? 1 : -1;
  var err = dx - dy;
  // First coordinates are not being added - it's assumed they were added in the last
  // iteration
  // Main loop
  while (!((x1 == x2) && (y1 == y2))) {
    var e2 = err << 1;
    if (e2 > -dy) {
      err -= dy;
      x1 += sx;
    }
    if (e2 < dx) {
      err += dx;
      y1 += sy;
    }
    result.push(x1);
    result.push(y1);
  }
  // Return the result
  return result;
}

But anyway, I need a trick to get this algorithm generate thicker line and I have no idea what to change. Should I generate circle of points for every point?


texts: How to use Steamworks API before our game is on Steam?

texts:
I'm part of a small team working on a game that we plan on distributing through Steam and integrating features which will utilize Steamworks API. We're not sure what the process is at the moment for how we can utilize Steamworks API without our game already being on Steam. Does anyone know where we need to start? I would imagine we will need an appid to be able to access Steamworks.

Is there a way that we can setup the game on Steam but not have it released until it's complete?


texts: Good data structure for storing graph-like map

texts:
I'm creating a strategy-based kingdom expansion game, where you start with one city and try to expand as far as possible from there. All the cities fit on a hexagon-grid and are connected by the edges of the hexagons.

Here's a diagram to illustrate what I'm trying to achieve:

Each city must be connected to another city by road, which means that all the cities are connected. At this point, I began to realize that this map is very similar to a graph, with the cities being nodes, and the roads being edges. I've already done some graph theory and implement multiple algorithms. However, when implementing it in a graph format (Map<Node, List<Edge>>), I ran into 2 problems:

There is no way to force that each node can only have 3 connections, with each being a multiple of 120º
If it was stored in this format, it would be very difficult to render just loop it through for updating.
I'm wondering if any of you have any better data structures that can be used for this. Any criticism, suggestions, or advice is welcome.

Thanks!

Ps. I've seen other questions that are somewhat related, however they either do not have an accepted answer or do not solve my problem.


texts:
I'm new in Unity and creating a game. So I have a class PicManager in which I have to load my images(sprites) from assets into a List and then use them in my game. What is the proper way to load multiple images from a folder in Assets?

I know, that I can use  Sprite[] sprites = Resources.LoadAll<Sprite>(texture.name);
But this article of Unity says not to use Resource folder.


texts: Could triangles be used for swept-AABB checks between positions?

texts:
I'm trying to understand swept-AABB collision detection. When checking for collisions between two positions of an object, I commonly see one of 3 strategies used:

Rays: trace rays from parts of the AABB at the previous postion to those on the final position, and check for intersection between them and other objects.
CCD: split the motion into multiple in-between positions, and check each one for collisions.
No sweep: just check that start and end positions are collision-free, and assume there was no collision in between.

A solution I've not seen discussed is just to use 2 triangles.

Here's how they compare:

The math wouldn't change even if you started using OBBs or convex shapes with more vertices: you still just need 2 triangles.

The above image illustrates the shortcomings of each approach. Only the Polygon conversion test is sure to catch all of the swept region.

From the tests I have done, simple triangle collision in not that costly, though slower than AABB–AABB and sphere–sphere. It seems to cost less than CCD also, but avoids misses (e.g. CCD might miss the red cube in the top left). Rays have a tendency to miss small objects if you imagine moving one of the red cubes up or down in the image.

Are there issues with this technique that would cause it to be used so little?


texts: Questions on the legal protection of games and their parts (assets, sounds, title)

texts:
we started new pirate game, and I just want to ask some questions about rights. So I am new in game dev, I guess there are a lot of answers, but I guess professionals can advise something for first steps.

So we started some things like:

concept arts
sounds
we are working on the name of the game (just use temp one for now)
we develop some models of ships and characters

I have question what's my step to protect everything I listed above. Do I need to protect everything separately? Do I need to register a game somewhere? Can I use my already made domain and subdomain for the game? Or do I need to register unique one domaine.


texts: Find centre of rotation from two locations

texts:
Ultimately I need to get c from the image and have a, b and that it takes 90 degrees to get a to d.

My solution to this was to rotate a around to get to d by the rotation. Then use the Y value from a and X from d to get c.

So far I an having trouble getting the rotation of a to d to work properly, what am I doing wrong in the rotation?

    Vector3 d = (Quaternion.Euler(0f, 0f, rotation) * (a - b)) + b;


texts: Typical Maximum steering angle of a real car

texts:
I'm building a car sim in Unity3D. I'm trying to set the properties of the car to be as realistic as possible. I can't seem to get a straight answer on Google so I thought of asking here.

What is the typical maximum steering angle of a normal passenger car ?


texts: Objects with custom shaders cast grayscale shadows when lightmapped

texts:
Unity 5 seems to be able to calculate colored shadows from objects mapped with standart shader and legacy shaders.

What should I do to make my custom shader to cast colored shadows as well?


texts: Programatically Build List of Custom Class Objects (prefabs)

texts:
This seems like it should be a simple thing, but I cannot seem to figure out a method.

Currently, I have a public List<MapGraphItem> roomList variable, and in the inspector, I add prefabs from Tiled2Unity for a given biome - currently a list of nine tiles for my test biome.  Map generation works great via this method. MapGraphItem is a custom class that is applied to these prefabs via script.

I'd like to programmatically build the list so that I can build it appropriately based on the biome that's being called (dungeon, forest, desert, et cetera).  I seem to be having trouble getting unity to put together a list of the items anyhow (they are in a specific assets folder and also have a specific prefix, in this case "dng_").

I tried this and some variations on it:

List<GameObject> _obj = GameObject.FindObjectsOfType(typeof(GameObject)).Select(g => g as GameObject).Where(g => g.name.StartsWith("dng_")).ToList();

But it seems the objects need to be loaded first (plus, I'd need to convert it to a List<MapGraphItem> before using it).

I could add another field to the MapGraphItem class for biome type and basically load ALL of the assets, but that's a huge waste of resources.  Manually adding these for each biome is really not ideal, and really not efficient.

Thanks!


texts: Simulation of a two-masses connected by a rod 2D system

texts:
I'm working on a multitouch-based interface and I want to add some physical behavior to gestures (pan, zoom and rotation). I thought model the system like that:

When a touch starts, a point mass is created.
As the finger moves, I calculate it's velocity vector.
When the touch ends, I suppose the mass is released and starts to move freely.

My problem comes when I have two masses (I don't need more than two masses to model this system):

The masses should act as if they were connected by a massless rod and, optional, they can slide along the rod with some coefficient of friction.

I attach a picture to explain the thing better.

I forgot almost all the physics I knew at college and now I'm a developer.

I know that at time t the masses have a position (x, y), a velocity and one or more forces or accelerations acting on it. And I want to know those values at time t+dt.

I would like to have some advice or approach to this problem. It's not about integrators or numerical analysis. My main doubt is about the rod constraint (keep the distance between masses) and the rotation movement.


texts:
I'm trying to edit large amounts of vertex attributes in my models for my game. The main attributes I really care about are strength (so wind can interact with them) and a couple of other things so the interaction with wind looks decent.

However, I'm not quite sure how do edit them easily. Of course I could manually write all of them, but that would be ridiculous. My first thought was to use a format in Blender that I could just export vertex colours and use the value as the attribute value.

Here's a picture for example (red = leaves, very windy, strength = 0.1; green = wood, strength = 0.7)

I don't really see any problems with this other than the fact I don't know of any formats, but I'm sure I can find some.

Is is there any way (or any program that can do this easier)? Or is the way of just colouring them the best way to go.


texts:
I've been stuck this evening on getting a Perlin Noise function to generate by itself. Every time I run the program without adding to different types of noise together it calls an ArgumentException error.

Here is my code I'm using.

        //perlin gen
        Random rand = new Random();
        double freq = 1 / 32.0;
        double lacu = 3.0;
        int octave = 5;
        double pers = 0.5;
        int seed = 1;

        Perlin perlin = new Perlin(freq, lacu, pers, octave, seed, QualityMode.High);

        //init the noise map
        noiseMap = new Noise2D(128, 128);
        noiseMap.GeneratePlanar(1, 2, 1, 2, true);

And the error that it calls is here.

public void GeneratePlanar(double left, double right, double top, double bottom, bool seamless)
    {
        if (right <= left || bottom <= top || this.m_generator == null)
        {
            throw new ArgumentException();
        }

I've checked and re-checked the code multiple times, so I'm not sure what is going on that is making the GeneratePlanar function call the ArgumentException error.


texts: LibGDX How to set spacing between list items in a Scene 2D Select Box Widget?

texts:
I have created a Select Box (Scene2D widget) which holds a list of items, to be selected. My code works fine, but I would like to make a little more spacing between each list item in the dropdown list in the select box. How can I achieve that??

My code for the list box is this.

List.ListStyle selectBoxListStyle = new List.ListStyle();
selectBoxListStyle.background = new NinePatchDrawable(new NinePatch(this.selectBoxListBackgroundTexture, 10, 10, 10, 10));
selectBoxListStyle.font = this.textFieldFont;
selectBoxListStyle.fontColorSelected = Color.WHITE;
selectBoxListStyle.fontColorUnselected = Color.BROWN;
selectBoxListStyle.selection = new TextureRegionDrawable(new TextureRegion(this.textFieldSelectionTexture));

SelectBox.SelectBoxStyle selectBoxStyle = new SelectBox.SelectBoxStyle();
selectBoxStyle.background = new TextureRegionDrawable(new TextureRegion(this.selectBoxMiddleBackgroundTexture));
selectBoxStyle.backgroundOpen = new TextureRegionDrawable(new TextureRegion(this.selectBoxMiddleActiveBackgroundTexture));
selectBoxStyle.font = this.textFieldFont;
selectBoxStyle.fontColor = Color.WHITE;
selectBoxStyle.listStyle = selectBoxListStyle;
selectBoxStyle.scrollStyle = new ScrollPane.ScrollPaneStyle();

SelectBox<String> selectBoxWidget = new SelectBox(selectBoxStyle);
selectBoxWidget.setItems("Test 1", "Test 2", "Test 3");


texts: Designing Collision Detection for 2D Rectangular Adventure/RPG

texts:
TLDR: I'm looking for an efficient way to detect collisions between irregular/small objects that are not a full tile size (like small cans) and a free-moving character in a 2D game.

I'm planning to design a 2D RPG-style game in XNA. It will be similar to the style of Chrono Trigger (pictured below) -- I will explain what that means. The main issue I have is how to properly design the collision detection.

First, a description of two of the main points of my game design:

Sprites are rectangular. So a character is two parts: lower-half (which collides with solid tiles) and upper half (which is "above" the lower half).
Free movement. Even though I use tiles, you don't move from tile to tile; you can move in any direction in a small increment (such as 8px).

Another important aspect of my design is that I don't (can't?) do any pre-processing on images to detect collision spaces. It must be either generic (eg. a 4px range outside of each tile), or cheaply calculatable. (This is to make it easier to develop by cutting down on the time needed to make sprites.)

My initial design for this (which I prototyped) was to use the (bottom half of the) character to collide with anything on the "ground" level. This works well with things that are full-tile covering (like walls), but not small objects (like cans). Pixel-level collision detection solved this, but can lead to irregularities, problems with granularity (eg. checking 4 pixels to either side), and of course, performance.

What I really want in this case is for the character to be able to move close to small or irregular objects. Is pixel-level collision detection the right answer? What about encapsulating it in a small polygon approximation (say a rectangle, even) and colliding with that area?  I'm concerned that, even with spatial partitioning, the performance will be poor and the user perception of collision will be poor-quality.

How do other 2D games deal with this?


texts: Line of Sight/Clear Path Check Theta* For Rectangle Character

texts: I am implementing Theta* pathfinding in a tile-based 2D game. A tile is either blocked or unblocked. The character has a rectangle collider with a width and height in tiles. Is there an algorithm for finding all the tiles the rectangle will overlap when moving in a straight line from A to B on the tile grid?


texts: I want to move one object (dot) in a circular path. How should I change the X and Y coordinates to accomplish this?


texts: As an example, the N64 has a notorious 4kb texture cache. Could someone sap another 4kb (or more) from the system's RAM or the Expansion Pak and use that as texture cache space? If so, would it be worth it to do it?


texts: Algorithm that cover one mesh by another mesh

texts:
Suppose I have two meshes (Let call me  first MeshShirt and second - MeshBody)
Meshes are aligned (if i render both MeshShirt "covers" MeshBody). But some parts of the body are not "under" the MeshShirt (because MeshShirt shape differs from MeshBody)

How can i "pull up" parts of MeshShirt which are under MeshBody and hold other parts in their places? Of course i want  save shape of MeshShirt if it possible

I think about following algorithm

mark all points of MeshShire which under MehsBody by tracing
intersection of its normals and MeshBody.

But if MeshShirt "hidden" parts have complex shape normal tracing will not work. So some way to detect bad points is needed
move every marked
point to the plane of its nearest triangle of MeshBody.

But i afraid
that these algoritm may produce significant  deformation of MeshShirt.
So some shape preserved deformation is needed too.

Sorry for my poor English and fuzzy problem definition


texts: Unity Player Movement Y Axis(Something like Swing Copters)

texts:
My Player moves on Y AXIS , but sometimes it doesnt go up but stucks in one place, Script is like in swing copters , when you touch it rotates to another side but its on X Axis , i took and made it on Y axis , but it doesnt work properly , player sometimes doesnt turn around and go up or back Please help out , sorry for bad english

void MovePlayerOnYAxis()
    {

        foreach (Touch touch in Input.touches)
        {

            moveL = !moveL;

            if (moveL)
            {

                transform.localScale = new Vector3(1, -1, 1);
            }
            else
            {
                transform.localScale = new Vector3(1, 1, 1);
            }

            huongbay = transform.localScale.x;
        }
        transform.root.Translate(Vector3.up * speed * huongbay * Time.deltaTime);
    }

Pre-Fix From @PompeyPaul
But Player still doesnt go Down , it now goes only up.

void MovePlayerOnYAxis()
    {

        foreach (Touch touch in Input.touches)
        {

            WasTouched = !WasTouched;

            if (WasTouched)
            {
                if (Input.touchCount == 0)
                {
                    WasTouched = false;

                    transform.localScale = new Vector3(1, 1, 1);
                }
            }
            else
            {
                if (Input.touchCount > 0)
                {
                    WasTouched = true;
                    transform.localScale = new Vector3(1,-1, 1);
                }

            }
            huongbay = transform.localScale.y;

        }
        transform.root.Translate(Vector3.up * speed * huongbay * Time.deltaTime);
    }


texts: Unity hangs when adding a GameObject to a List

texts:
Since 3 days ago Unity started freezing after adding a GameObject to a List. I haven't changed anything in that particular code, so I have no idea why this is happening:

 private IEnumerator HandleSelectedCubes() {
    if (InputManager.instance.selectedCube != null && !selectedCubes.Contains(InputManager.instance.selectedCube)) {
        if (oldSelectedCube == null) {
            selectedCubes.Add(InputManager.instance.selectedCube); // This is where it crashes
            oldSelectedCube = InputManager.instance.selectedCube;
        } else if (InputManager.instance.selectedCube.name != oldSelectedCube.name) {
            ClearSelectedCubes();
            selectedCubes.Add(InputManager.instance.selectedCube);
            oldSelectedCube = InputManager.instance.selectedCube;
            InputManager.instance.selectedCube = null;
        }

        AudioManager.instance.PlayCubeSelectSound();

        if (selectedCubes.Count == 4) {
            InputManager.instance.allowCubeSelection = false;
            moveDone = true;
            yield return new WaitForSeconds(0.07f);

            var destroySelectedCubes = true;

            foreach (var cube in selectedCubes.ToList()) {
                if (cube != null && cube.tag == "Lightning")
                    destroySelectedCubes = false;
            }

            foreach (var cube in selectedCubes.ToList()) {
                if (cube != null) {
                    cube.GetComponent<Cube>().hasGivenShard = true;
                    CubeAbilities.instance.TriggerSpecialCubeAbility(cube);

                    if (destroySelectedCubes) {
                        DestroyCube(cube);
                        ClearSelectedCubes();
                    }
                }
            }

            InputManager.instance.playerMovesCount++;
            AudioManager.instance.PlayCubeDisappearSound();
            ShardManager.instance.AddSessionShards(4);
        }
    }
}


texts: Detecting if a point is inside a rectangle

texts:
I have mouse coordinates in 2D game (x and y) and a rectangle (x, y, width, height).
How do I determine if the point is in the rectangle? I do not have any code to post here. I'm just searching for help.


texts:
I want to make an Repeating Task whisch isn't in the main Class. ("Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {},20,20);")

But it says that it can't resolve the method.


texts:
I don't really know how to describe my tilemap rendering problem with words, so I think the best way is to show the pictures.
This is how my map looks like when it rendered correctly:

but when I move the player little bit (the camera follows the player) I get this weird result:

Notice how the tiles which generating the floor got this strange shape, like they are not align correctly.
I do have a padding in my tileset, so I'm not sure this is the problem.
I also tried to round the camera position to integers, but it's result was always rendered like the second picture (the unwanted way), instead of sometimes correctly and sometimes not.

What else can be the issue?

EDIT: I noticed now that this problem happened only when the camera reach to the edges points of the tilemap, and also right at the beginning of the program running (when the player is at his first position, before any movement was made).


texts: Unity crashes if there are more than 4 terrains

texts: please can you help me with the issue that I face, that is, I decided to create open-world game by creating several terrains and connect them together in Unity and firstly respective size of the terrains was 500X500 then I decided to add more terrains to make game world bigger and once I added the 5th terrain in the scene, Unity simply crashed. Later, I thought what if I increase the sizes of terrains rather than create more new terrains then the sizes of originally created terrains were changed from 500X500 to 800X800 and again Unity crashed. Please guys help me out with that and how to overcome that and I am just trying to create game without using any ready plugins and, say, try to create the game on my own. Thank you for your attention))).


texts:
In the context of bilinear interpolation, if we look at the image below:

I'm confused about what P is exactly. I'm not sure if it's a point (as in (x, y)) or if it's a single value.


texts: How common is automated testing in game development?

texts:
Do gamers developers use to write unit and integration tests? How common is it among puzzle developers? And among developers of MMORPGs and FPSes?

(I have no background in game development neither am I cogitating about working with it - it is just a doubt that occurred to me. So, no need of trying to convince me to write them, even because I already like to write automated tests.)


texts: How to create a state based traffic signal?

texts:
I want to create a traffic light for a Unity3D game. I will model it in blender.

What is the best way to control this light in a unity scene?

One way I could think of is to change texture of say red light from dull red to bright red, when it is time for red signal. But I am not sure if this is possible or a good strategy.


texts: Make variables public, or make functions to get/set variables?

texts:
Dumb question but I want my game to be secure as possible. Right now I have classes interfacing with each other in order to save/load player information. Right now I have all the variables in my classes as public, and saving / loading the saved variables into them. But I don't think that's as secure.

Code:

public class PlayerRP : MonoBehaviour {

public string charName;
public string charRace;
public string charClass;
public string charClassSpec;
public string charBackground;
public string charGender;

}

public class CharacterManager : MonoBehaviour {
public void SaveCharacter() {
    BinaryFormatter bf = new BinaryFormatter();
    FileStream file = File.Create(Application.persistentDataPath + slotFile);

    CharacterSaveFile data = new CharacterSaveFile();

    // Character RP
    data.charName = playerRP.charName;
    data.charRace = playerRP.charRace;
    data.charClass = playerRP.charClass;
    data.charGender = playerRP.charGender;

    bf.Serialize(file, data);
    file.Close();

    LoadCharacter();
}
}

Would it be safer (or more efficient) to instead make methods in the playerRP class to get/set the variables separately, rather than have them as public?


texts: W want to use GL_CLAMP_TO_BORDER in my GL ES 3 app. Based on documentation (https://www.khronos.org/registry/OpenGL-Refpages/es3/html/glTexParameter.xhtml), it seems to be supported, however, on iOS this #define is not present. Is it named differently? Maybe some extension?


texts: Libgdx OrthogonalTiledMapRenderer not rendering map properly

texts:
I'm using a little hack to change the coordinate system to the one i'm accustomed to (left and up is negative and right and down is positive) but this causes the tiled map renderer to render the map incorrectly, as shown below

Whereas it looks like this in the Tiled map editor

This is the "hack" I'm using to change the coordinate system:

float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();

Camera = new OrthographicCamera(w, h);
Camera.setToOrtho(true, w, h);

My render code

renderer.setView(Camera);
renderer.render();

So is there a workaround to this? Or perhaps a better way to change the coordinate system that doesn't screw up everything?

Edit: The rendered tiles are correct now but the map and everything rendering is still flipped along the y-axis. If I was drawing sprite and stuff, I could always draw them flipped but I don't know how to do it with the tiled map renderer.


texts: Is there a way to layer 2D assets in Unity while maintaining correct player clipping?

texts:
I'm working on a 2D top-down game, currently building a scene where I want to place one asset on top of another (lamp on top of table).
Game objects are all on the same layer as the player so that the player clips accordingly when moving in front or behind an object, based on the pivot location on the y axis.
The easiest solution would be to adjust the 'Order in layer', setting the lamp asset to 1 instead of 0 so that it sits above the table. However, this interferes with player clipping in game, causing the lamp to always be in front of the player.
It's making it impossible to build custom scenes on the fly inside Unity as I am unable to arrange assets in the correct order using layers whilst maintaining player interactions such as clipping.
Does anyone know of a solution for this issue?


texts: How to edit and persist serializable Assets in the Editor Window?

texts:
I have an asset saved in my project which represents a serializable scriptable object.
Code of the object is very simple:

using UnityEngine;
using System.Collections;

public class TestScriptable : ScriptableObject {
    public float gravity = .3f;
    public float plinkingDelay = .1f;
    public float storedExecutionDelay = .3f;
}

There is no problem changing values for this object in the inspector, and the changes do persist and survive after exiting → entering Unity.

I am trying to mimic the inspector behavior in an Editor Window. But any changes I do in the Editor Window, though reflected in the Inspector, do not persist.
Here is my two scripts which lay inside the Editor folder:

the first one (auxiliary) - this script replaces inspector fields (see image above) with button, which calls my custom EditorWindow.

using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(TestScriptable))]
public class TestScriptableEditor : Editor {
  public override void OnInspectorGUI() {
    if (GUILayout.Button("Open TestScriptableEditor"))
      TestScriptableEditorWindow.Init();
  }
}

the second (with my problem) - script, where I'm trying to change my asset values:

using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class TestScriptableEditorWindow : EditorWindow {
    public static TestScriptableEditorWindow testScriptableEditorWindow;
    private TestScriptable testScriptable;

    [MenuItem("Window/TestTaskIceCat/TestScriptableEditor")]
    public static void Init() {
        // initialize window, show it, set the properties
        testScriptableEditorWindow = GetWindow<TestScriptableEditorWindow>(false, "TestScriptableEditorWindow", true);
        testScriptableEditorWindow.Show();
        testScriptableEditorWindow.Populate();
    }

    // initialization of my troubled asset
    void Populate() {
        Object[] selection = Selection.GetFiltered(typeof(TestScriptable), SelectionMode.Assets);
        if (selection.Length > 0) {
            if (selection[0] == null)
                return;

            testScriptable = (TestScriptable)selection[0];
        }
    }

    public void OnGUI() {
        if (testScriptable == null) {
            /* certain actions if my asset is null */
            return;
        }

        // Here is my tries to change values
        testScriptable.gravity = EditorGUILayout.FloatField("Gravity:", testScriptable.gravity);
        testScriptable.plinkingDelay = EditorGUILayout.FloatField("Plinking Delay:", testScriptable.plinkingDelay);
        testScriptable.storedExecutionDelay = EditorGUILayout.FloatField("Stored Execution Delay:", testScriptable.storedExecutionDelay);
        // End of the region of change values
    }

    void OnSelectionChange() { Populate(); Repaint(); }
    void OnEnable() { Populate(); }
    void OnFocus() { Populate(); }

}

My questions is: what am I doing wrong? What could be the problem? How to fix it?  Am I loading the asset wrongly in the Editor Window? Or what?
Any help/ideas would be appreciated.


texts: Multiple Render Targets, Multiple Fragment Shaders

texts:
I render a normal and a depth image of a scene. Then I want to reuse these two images to do further texture/image processing in a second fragment shader. I use a framebuffer with 3 textures attached to it. 2 for the normal and the depth textures and one is supposed to contain the final processed image. The problem is, that I can't get the first two images to the second fragment shader to use them as texture samplers.

Here is my code:
First I create a fbo and attach 3 textures to it.

    // create FBO
glGenFramebuffers(1, &Framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, Framebuffer);

glGenTextures(1, &renderedNormalTexture);
//glBindTexture, glTexImage2D, glTexParameteri ... left out for clarity
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderedNormalTexture, 0);

glGenTextures(1, &renderedDepthTexture);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, renderedDepthTexture, 0);

glGenTextures(1, &edgeTexture);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, edgeTexture, 0);

ndbuffers[0] = GL_COLOR_ATTACHMENT0;
ndbuffers[1] = GL_COLOR_ATTACHMENT1;
ndbuffers[2] = GL_COLOR_ATTACHMENT2;
glDrawBuffers(3, ndbuffers);

Fragment shader 1:
This is the first fragment shader which outputs 2 textures to position 0 and 1

in vec3 position_worldspace;
in vec3 normal_cameraspace;
in vec4 vpos_to_fragment;
uniform float zmin;
uniform float zmax;
layout(location = 0) out vec3 normalcolor;
layout(location = 1) out vec3 depthcolor;
void main() {
normalcolor = normalize( normal_cameraspace ) * 0.5 + 0.5;  // normal out
  vec4 v = vec4(vpos_to_fragment);
v /= v.w;
float gray = (-v.z - zmin) / (zmax - zmin);
depthcolor = vec3(gray);  // depth out
 }

fragment shader 2:
And the second fragment shader which is supposed to receive two texture samplers from position 0 and 1 and do sth. with them:

uniform sampler2D normalImage;
uniform sampler2D depthImage;
uniform float width;
uniform float height;
in vec2 UV;
layout(location = 2) out vec3 color;

void main() {
vec3 irgb = texture2D(normalImage, UV).rgb;
// do sth here...
color = irgb ;
}

And finally the rendering step:
Maybe I am mistaken here. I render the geometry/scene (once?!) and apply two fragment shaders.

glUseProgram(FragmentShader1);
SetMVPUniforms();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
RenderScene(); // render geometry

glUseProgram(FragmentShader2);

GLuint nID = glGetUniformLocation(FragmentShader2, "normalImage");
GLuint dID = glGetUniformLocation(FragmentShader2, "depthImage");

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, renderedNormalTexture);
glProgramUniform1i(FragmentShader2, nID, 0);

glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, renderedDepthTexture);
glProgramUniform1i(FragmentShader2, dID, 1);

Now what I get is either nothing or a wrong colored image.


texts:
I am approaching the point where I can release a playable beta of a very complex game I am making in Flash/AS3. It is fairly involved and the deepest game Ive made so far. I plan on hosting it on my personal site but I want to try and get good feedback on the game elements so far.

Is it worth it to expose this beta to as many places as possible before the release? What are good communities to do this?

Please note this will be freeware in its final release


texts: What is Purpose of pIntermediate in UpdateSubresources?

texts:
DX11 used ID3D11DeviceContext::UpdateSubresource but now DX12 seems to use a new method UpdateSubresources.  I think I can figure out most of the differences between these two functions but the pIntermediate parameter of the new function has me particularly confused.

Can someone help me understand what this new pIntermediate parameter is for?

I noticed the VS2015 Template I'm trying to work from sets up a local variable named vertexBufferUpload in a CreateDeviceDependentResources method which later uses it in an UpdateSubresources call; unfortunately, by the time I want to call the new UpdateSubresources method, the vertexBufferUpload variable is long out of scope.


texts: How to use SetBoneRotationByName() to rotate a single bone in a armature?

texts:
I am very excited to finally be learning Unreal engine development! But I have been working with Unreal editor for only the past couple of days but am having trouble understand how to rotate or translate bones in a SkeletalMesh that is part of a fbx model that I've imported to the project.
I don't wish to inconvenience anyone but I could really use some help to understand what I'm missing or why my armature's Chest bone is not rotating when the game is playing.
Here's a screenshot of my project that shows the 'Simple' armature in the scene that has a MyActor component attached to it. And under the "MyCategory" are two editor variables for assigning the skeletal mesh and the rotation vector to allow manually adjusting the rotation of the Chest bone:

This is the simple skeleton tree:

And here is my c++ code that basically tries to create a new FRotator for each Tick, then sets the value of the FRotator to the values of the user's myRotation values from the editor. And finally the FRotator is passed as the rotation parameter when calling SetBoneRotationByName.
But this line does not appear to update the armature and the Chest bone does not rotate even while the game is playing:
myMesh->SetBoneRotationByName(boneName, r, EBoneSpaces::WorldSpace);
MyActor.h
#pragma once

#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "Components/PoseableMeshComponent.h"

#include "MyActor.generated.h"

UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class FIRSTCPPGAMELESSON_API UMyActor : public UActorComponent
{
    GENERATED_BODY()

public:
    UMyActor();

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyCategory")
    FVector myRotation;

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyCategory")
    UPoseableMeshComponent* myMesh = nullptr;

protected:
    virtual void BeginPlay() override;

public:
    virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
};

MyActor.cpp
#include "MyActor.h"

UMyActor::UMyActor()
{
    PrimaryComponentTick.bCanEverTick = true;
}

void UMyActor::BeginPlay()
{
    Super::BeginPlay();
}

void UMyActor::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
    Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

    //int32 numBones = mesh2->GetNumBones();

    FRotator r;
    r.Roll = myRotation.X;
    r.Pitch = myRotation.Y;
    r.Yaw = myRotation.Z;
    UE_LOG(LogTemp, Log, TEXT("Yaw: %d"), r.Yaw );

    FName boneName("Chest");
    myMesh->SetBoneRotationByName(boneName, r, EBoneSpaces::ComponentSpace);
}

I have very little knowledge about developing in Unreal editor and was hoping someone could advise me how I could best control an armature using c++? After a couple of nights now of searching for any relevant examples I was not able to locate anything that leads a solution. I was wondering if in my approach am I trying to rotate the incorrect skeleton mesh object? Possibly something to do with .fbx import settings? I'd like to be able to achieve a way of adding armatures to my scene and rotating certain bones individually using c++. I was hoping someone here might be able to recommend a more proper solution so I could finally get my project going? Also are there any resources available pertinent to controlling SkeletalMesh in Unreal using c++? I cannot wait until I am a little more familiar with this engine! Greatly appreciate any advice! Thanks


texts: How to apply friction on the car so that car slow down

texts:
I am working on a driving game. I am able to move the car using arrow key.I am accelerating the car by applying a force in what ever direction that car is.But I need to apply friction to the car so that the car slow downs more quickly.How can I do it.Here is the code I am using for the movement

if(Input.GetKey(KeyCode.UpArrow) ) {
        rb.AddForce( transform.up * speedForce);
    }

after some search.I found that some used this line of code

rigidbody2D.drag=friction;

And I edited my script as below

if(Input.GetKey(KeyCode.UpArrow) ) {
        rb.AddForce( transform.up * speedForce);
        rb.drag=friction;
    }

Will this make any sense in applying friction.Can anybody please help me .


texts: Cannot connecting texture to heightmap using mapped uniform location

texts:
In my shader program, I have my attributes and uniforms added to a map for each. What I have displayed is a heightmap, but cant seem to connect the graphic texture to display.

mUniformList (std::string, GLuint) contains all the uniforms added from my shader (8 total). The problem is that retrieving and connecting the sampler2D named "groundTexture."

void Terrain::init()
{
    ....
    ....

    // VAO
    glGenVertexArrays(1, &mVAO);
    glBindVertexArray(mVAO);

    // VBO
    glGenBuffers(1, &mVBO);
    glBindBuffer(GL_ARRAY_BUFFER, mVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(mVertices), &mVertices[0], GL_STATIC_DRAW);
    glEnableVertexAttribArray(shader["position"]);
    glVertexAttribPointer(shader["position"], 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

    // IBO
    glGenBuffers(1, &mIBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(mIndices), &mIndices[0], GL_STATIC_DRAW);

    // Load Heightmap texture
    mTexture.loadTexture(heightMapFilePath, mHeightMapTextureID, 0);

    // Texture coordinates
    glGenBuffers(1, &mTexCoordID);
    glBindBuffer(GL_ARRAY_BUFFER, mTexCoordID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(mTexCoords), &mTexCoords[0], GL_STATIC_DRAW);
    glEnableVertexAttribArray(shader["texCoord"]);
    glVertexAttribPointer(shader["texCoord"], 2, GL_FLOAT, GL_FALSE, 0, (void*)0);

    // load ground texture
    mTexture.loadTexture(groundTextureFilePath, mTextureID, 0);

    shader.connectTexture(mTextureID);
}

With connectTexture being:

void TerrainShader::connectTexture(GLuint id)
{
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, id);
    glUniform1i(mUniformList["backgroundTexture"], 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

UPDATE
Fixed dereferencable error pertaining to the mUniformList. No errors of any kind whatsoever, but still nothing displayed.

terrainfrag.glsl

#version 330 core

layout (location = 0) out vec4 color;

smooth in vec2 TexCoord;
smooth in vec3 Normal;

uniform sampler2D backgroundTexture;

void main()
{
    vec3 normalized = normalize(Normal);

    color = texture(backgroundTexture, TexCoord);
    color += vec4(1, 1, 1, 1);
}


texts: Why does my code only work when there is a debug statement? (Unity)

texts:
I have a script that controls how the particles in a particle emitter should look.  (XNA example here) Yet it doesn't seem to update correctly.  With an orb that should have 50 particles only a few show up.  I tried to debug it to see what was going on and it all started working again.  I removed the debugging and I was back to only a few particles being visible.

I put in a simple debug message (Debug.Log("hi")) and it worked, but it was a little slow since I was putting out a debug message 50 times per frame.

I wanted to know if I wasn't getting the correct number of particles so I set the starting color to something with full alpha instead of 0 and all of the particles showed up even without the debug message, but they just pop in instead of fading now.  This means that somehow it's not fading in correctly unless there's a debug statement.  It makes no sense to me.

The issue seems to be in the "if (myParticles[i].ChangingColors)" section of Update.

Here are my start and update functions.

OrbBase - Handles the number of particles.
RotateParticleFinal - Holds the data that I want to set to the particle.

void Start ()
{
    myBase = gameObject.GetComponent<OrbBase>();

    emitter = (GameObject)Instantiate(ParticlePrefab);
    emitter.transform.parent = this.transform;
    emitter.transform.position = transform.position;

    myParticles = new List<RotateParticleFinal>();
    myRemovedParticles = new List<RotateParticleFinal>();

    for (int i=0; i < myBase.Particles; i++)
    {
        float r  = GetNewRadius();
        myParticles.Add(new RotateParticleFinal(r, color));
    }
}

void Update ()
{
    #region Deal with changing particle count
    while (myParticles.Count < myBase.Particles)
    {
        float r  = GetNewRadius();
        myParticles.Add(new RotateParticleFinal(r, color));
    }

    for (int i=myParticles.Count-1; i >= 0; i--)
    {
        if (myParticles[i].Dead)
            myParticles.RemoveAt(i);
    }

    while (myParticles.Count > myBase.Particles)
    {
        myParticles.RemoveAt(myParticles.Count-1);
    }
    #endregion

    //TODO: Do we really want 5000?  Can the number change to match our base particle count?
    ParticleSystem.Particle[] tempParticles = new ParticleSystem.Particle[5000];
    int count = emitter.GetComponent<ParticleSystem>().GetParticles(tempParticles);

    for (int i=0; i < count; i++)
    {
        if (i >= myBase.Particles)
        {
            //This is more than we want, destroy it immediately and make sure that we don't get more than we really want.
            tempParticles[i].lifetime = -1;
        }
        else
        {
            myParticles[i].Update();
            if (tempParticles[i].lifetime < 5)
            {
                //Don't let it die!
                tempParticles[i].lifetime = 1024;
            }

            tempParticles[i].position = myParticles[i].GetPosition();

            //Debug.Log("hi");

            if (myParticles[i].ChangingColors)
            {
                tempParticles[i].color = myParticles[i].MyColor;
                if (tempParticles[i].color.a == 1)
                {
                    //This is the only place that ChangingColors is set to false so it should never stop fading in until I've faded all the way in.
                    myParticles[i].ChangingColors = false;
                }
            }

            if (!myParticles[i].SetUp)
            {
                //This is a brand new particle, so I need to tell it a few things.
                //We don't want it moving on it's own.
                tempParticles[i].velocity = Vector3.zero;
                tempParticles[i].axisOfRotation = new Vector3(Random.Range(-0.1f, 0.1f), Random.Range(-0.1f, 0.1f));
                myParticles[i].SetUp = true;
            }
        }
    }
    emitter.GetComponent<ParticleSystem>().SetParticles(tempParticles, count);
}

Any ideas why this only works with a debug, and how to fix it?


texts: How hard is it to port games from the PC to other platforms?

texts:
I am trying to learn game development with the Unreal Development Kit and Unity, trying both out, and trying to get an idea how they work. For now, I'm mostly focusing on PC games.

How hard is the technical aspect of porting a PC game that I made in the Unreal Development Kit or Unity to another platform, such as Play Station 3, or Xbox 360? is there some kind of option where we can just select the target platform from a combo box and press deploy, or do we need to modify the game for each platform?


texts: How to make it so units don't stack up in one location?

texts:
Possible Duplicate:
  Is there a simple way to stop enemies standing in the same spot?

So I'm making a game in AS3, it's a strategy DotA-like game (for flash game equivalent, there's UDE) so far so good, I have the A* pathfinding algorithm all sorted out and the minion units move to the desired location as I want them to be.
The problem a rise when a unit stops in a node that has already occupied by another friendly unit. Both (or more than two) of them stacks up in one location, it looks like they're one unit.

I want to add collision detection so when they collide they don't stack up together. But now they stop when they collide on they way to a node. This isn't good because they won't move at all midway (they won't respond to enemy attacks like that). I've added a deltatime so they only stopped for 2 seconds before they move again to their designated designation. This moves them again but they flicker. Not how I want it.

So, like the title said. How to make more than one units don't stack up in a node? And if possible, how to make them not flicker while moving (it's good if they can tell other friendly units on the way and avoid them accordingly)?


texts: Text blits to screen at wrong y-coordinate

texts:
I have a program that is meant to scroll numbers/letters down the screen, like in the movie "The Matrix". When one of the columns reaches a letter in the user's name (obtained using user input), it freezes and all of the other characters in that column fade away. The program opens correctly,but will only print characters at a zero y-coordinate. This is the function which blits the letters and numbers to the screen. When I insert a print statement to check if it is printing the letter at the right y coordinate, it says it is incrementing by 32 pixels, like it should.

for sym in lst:
    symbol = matrixfont.render(sym, True, (0, 255, 0))
    print("Printing %s" % sym)
    print("x coord is %s and y coord is %s" % (x_coord, i))
    screen.blit(symbol, (x_coord * 30, i))
    pygame.display.update()
    i -= spacing

It just prints all of the letters at y-coordinate 0, but at the correct x-coordinates. Maybe the full code will help:

import time
import random
import pygame
pygame.init()

#----------DEFINING VARIABLES

user_name = input("Type in your first name.")
spacing = 32
symbol_list = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
               "V", "w", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
background_color = 0, 0, 0
master_list = []
matrixfont = pygame.font.Font("C:/Python34/Programs/MatrixSpeller/OCRAEXT.TTF", spacing)
pressedkey = pygame.key.get_pressed()
windowwidth = len(user_name) * 30

#----------SETTING UP WINDOW

screen = pygame.display.set_mode((windowwidth, 300))
pygame.display.set_caption('Name Speller')
screen.fill(background_color)

#----------DEFINING FUNCTIONS

def update_list(x):
    print("update list %s" % x)
    s = random.choice(symbol_list)
    lststring = master_list[x]
    lststring = s + lststring[:9]
    master_list[x] = lststring

def print_list(lst, x_coord):
    global i
    i = 0
    for sym in lst:
        symbol = matrixfont.render(sym, True, (0, 255, 0))
        print("Printing %s" % sym)
        print("x coord is %s and y coord is %s" % (x_coord, i))
        screen.blit(symbol, (x_coord * 30, i))
        pygame.display.update()
        i -= spacing

#----------MAIN LOOP

for n in range(len(user_name)):
    master_list.append("@")
    print("master list is %s" % master_list)

while True:
    for n in range(len(user_name)):
        update_list(n)
        print_list(master_list[n], n)


texts: how to play a video with Android or AndEngine

texts: I don't know if it's possible to show a video like the videos in Angry Birds (Something in Flash or another format) in middle of a game with Android or AndEngine or are they animations what they are made with Sprites and a more programming process?? How do they show those videos?


texts: UDK client, C++ server (is it possible?)

texts:
For example I have C++/C# server side with sockets or http web server and UDK client.

I am interesting what about experience with networking in UDK: could I connect UDK client to C++/C# socket server via UDP/TCP? Maybe some tutorials/examples?


texts: How can I assign entity IDs in a robust way in a network game?

texts:
I'm working on an entity system for a networked game and I'm assigning each entity a unique 32-bit integer id that I can use to serialize references to entities and the entities themselves.

Currently I'm just incrementing a counter every time an entity is created. I guess the ids will eventually run out but I don't really expect to have 4 billion entities. Also this avoids the problem if entity #5 is destroyed and we get an id of 5. Is it meant to refer to the new #5 or the old deleted #5?

The problem is that I'm not sure how to handle/avoid collisions. Currently if a client receives an update for an entity with an id higher than it's current "free id" it just bumps it's free id up to past that. But that doesn't seem very robust.

I thought about maybe assigning ranges to each client so they can allocate entities without conflicting (say the top n bits are the player number) but I'm worried about what happens if ranges began to overlap over time.

Is there a better way of handling this? Should I even care about ids overflowing or going past the end of the allowed range? I could add code to detect these cases but what would it do if they happen other than crash.

Another option is to use something with a higher chance of being unique like a 128-bit GUID but that seems really heavyweight for a game that's trying to minimize network traffic. Also, realistically I would never need more entities at one time then would fit into a 32-bit or even 24 bit integer.

Thanks!


texts: How can I render an .stl file in XNA or Monogame?

texts:
How should I go about rendering a .stl file as a 3d model in XNA? The .stl file contains a bunch of triangles that add up to a solid mesh. I have already figured out how to read the contained data. The file firstly contains the amount of facets. The file then consists of groups of data that represent the triangles. For each triangle the is a normal and 3 vectors that represent the 3 corners of the triangle.

My question is how I should go about rendering theses triangles in XNA. I guess I have to use a vertex buffer or something but I have almost no experience with 3D at all. Could someone please help?


texts: i want to add Models (FBX) to My XNA Game without adding them to the "Game Content Project" , so the user could choose his own model , how could i implement this ?


texts:
I am drawing a line in XNA which I want to never end. I also have a tool that moves forward in X-direction and a camera which is centered at this tool. However, when I reach the end of the viewport the lines are not drawn anymore. Here are some pictures to illustrate my problem:

At the start the line goes across the whole screen, but as my tool moves forward, we reach the end of the line.

Here are the method which draws the lines:

        private void DrawEvenlySpacedSprites (Texture2D texture, Vector2 point1, Vector2 point2, float increment)
{
    var distance = Vector2.Distance (point1, point2);    // the distance between two points
    var iterations = (int)(distance / increment);       // how many sprites with be drawn
    var normalizedIncrement = 1.0f / iterations;        // the Lerp method needs values between 0.0 and 1.0
    var amount = 0.0f;

    if (iterations == 0)
        iterations = 1;

    for (int i = 0; i < iterations; i++) {
        var drawPoint = Vector2.Lerp (point1, point2, amount);
        spriteBatch.Draw (texture, drawPoint, Color.White);
        amount += normalizedIncrement;
    }
}

Here are the draw method in Game. The dots are my lines:

protected override void Draw (GameTime gameTime)
{
    graphics.GraphicsDevice.Clear(Color.Black);
    nyVector = nextVector (gammelVector);
    GraphicsDevice.SetRenderTarget (renderTarget);
    spriteBatch.Begin ();
    DrawEvenlySpacedSprites (dot, gammelVector, nyVector, 0.9F);
    spriteBatch.End ();

    GraphicsDevice.SetRenderTarget (null);
    spriteBatch.Begin (SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, camera.transform);
    spriteBatch.Draw (renderTarget, new Vector2 (), Color.White);
    spriteBatch.Draw (tool, new Vector2(toolPos.X - (tool.Width/2), toolPos.Y - (tool.Height/2)), Color.White);
    spriteBatch.End ();

    gammelVector = new Vector2 (nyVector.X, nyVector.Y);
    base.Draw (gameTime);
}

Here's the next vector-method, It just finds me a new point where the line should be drawn with a new X-coordinate between 100 and 200 pixels and a random Y-coordinate between the old vector Y-coordinate and the height of the viewport:

        Vector2 nextVector (Vector2 vector)
    {
        return new Vector2 (vector.X + r.Next(100, 200), r.Next ((int)(vector.Y - 100), viewport.Height));
    }

Can anyone point me in the right direction here? I'm guessing it has to do with the viewport.width, but I'm not quite sure how to solve it. Thank you for reading!


texts: Instantiate unity sometimes lags the game some times it doesnt

texts:
I have a script that instantiates a object lets say every half a second. THis object is of the type .fbx and has a file size of 53kb, lets call this object A. When i use this object my script instantiates the objects without any freezes or any other problems.

Now i have an other object also of type .fbx and also with a filesize of 53kb lets call this object B. Now when i want to instatiate object my my game freezes a few frames upon instantiation.

Why? Is there a way to instatiate objects more efficiantly? I already looked at using object pooling but this doesnt really works in my case.

See here a screenshot for object A, and its components:

See here object B and its components:

Per request the code that does the instantiation of the objects:

public class ForLoopVisualization1 : MonoBehaviour {

    public DetectorAreaScript ElementDetector;
    public GameObject TowerElement;
    public Transform TowerElementsParent;
    public bool WigglyTower = false;
    public float ElementSpacing, Wiggeliness;

    private Collider BuildElementCollider;
    private Transform BuildElementTransform;
    private Vector3 TowerElementPos;
    private int TowerElementCount, CreatedElements;
    private bool StartBuildingTower = false;
    private float Delay = 0.5f, TowerElementSize;

    // Use this for initialization
    void Start () {
        ElementDetector.DetectedData += OnObjectEnterDetector;
        Destroy(TowerElement.GetComponent<Rigidbody>());
        TowerElementSize = TowerElement.GetComponent<Collider>().bounds.size.y;
        TowerElementPos = TowerElementsParent.position + new Vector3(0, TowerElementSize * 1.5f + ElementSpacing, 0);
    }

    // Update is called once per frame
    void Update () {
        if(StartBuildingTower && CreatedElements < TowerElementCount)
        {
            Delay -= Time.deltaTime;
            if(Delay <= 0)
            {
                CreatedElements++;
                var te = Instantiate(TowerElement, TowerElementPos, Quaternion.identity);
                te.transform.SetParent(TowerElementsParent);
                if(WigglyTower) TowerElementPos += new Vector3(Random.Range(-Wiggeliness, Wiggeliness), TowerElementSize + ElementSpacing, Random.Range(-Wiggeliness, Wiggeliness));
                else TowerElementPos += new Vector3(0, TowerElementSize + ElementSpacing, 0);
                Delay = 0.4f;
            }
        }
        else if(StartBuildingTower)
        {
            StartBuildingTower = false;
            // StartCoroutine(EjectVar()); // add when bugs are fixed..
        }
    }

    void OnObjectEnterDetector(System.Object sender, DetectedVariableData data)
    {
        if(data.DetectedObjectType == DetectedType.Variable)
        {
            var vals = ElementDetector.DetectedVariable.GetVariableValue();
            TowerElementCount = vals.IntValue;
            if(CreatedElements > 0)
            {
                foreach (Transform child in TowerElementsParent)
                {
                    Destroy(child.gameObject);
                }
                CreatedElements = 0;
            }
            TowerElementPos = TowerElementsParent.position + new Vector3(0, TowerElementSize * 1.5f + ElementSpacing, 0);
            StartBuildingTower = true;
        }
    }

    IEnumerator EjectVar()
    {
        yield return new WaitForSeconds(0.8f);
        ElementDetector.EjectDetectedElement(new Vector3(-1, 0, -1));
    }
}

If something is unclear let me know so i can clarify the post!


texts: 2D top down RPG animation architecture problem

texts:
I have a problem with my sprite animations right now. I have different animations and sequences for each character so an specific archer might do a ranged attack in which he just plays one animation and shoots an arrow at the enemy. The other might be melee and has to move close to the enemy while having an animation for that and when he reaches the enemy do its attack animation and return back to its original position also having its own animation. And I could go on and on for maybe like bosses etc.

As you can see there are many possible animation sequences for quite a variety of characters. My question is what is the best way to program this into my game. Should I have a base class for the battler which has all the common methods and than inherent each character from that class with its own attack sequences? Because that is what I thought of first but I'm affraid its the wrong approach since I will have many classes doing the same kind of sequences. Or maybe should I create a sequence base class and each different animation sequence will inherent from that class. Than play the sequence on the base Battler class?

I'm developing the game in SFML C++ and here is a gif of the battle screen right now so you can get an idea of how a battle is in my game.

Battle scene of my game


texts: What are the limits for UDK's landscape size?

texts:
With the new (as of March 2011) landscape tool, the Unreal Development Kit supports bigger and (potentially) streaming landscapes than the old terrain tool. However, in my tests trying to import or create from scratch a small island (specifically, the island of Tenerife including some of the surrounding sea at 2m horizontal resolution, resulting in a roughly 35.000x20.000 pixel heightmap image - downright tiny in comparison to your usual GIS raster datasets), the UDK simply crashes. No error message or anything like that, simple program crash.

It seems as if I run against some kind of internal limit there, but without any clue as to where it happens and with the tool being rather new and undocumented, it's hard to say where those limits are.

Thus the question - what's the maximum size of a heightmap which can be used with the landscape tool in UDK, both in terms of the "amount of heightmap points" and the "width and height in Unreal Units"? In addition, if there are special tricks possible to break those limits (Streaming in the landscape? Portals?), some pointers would be nice ...